text
stringlengths
180
608k
[Question] [ My friend and I have this game that we play with words. It is a fun pastime and it involves "canceling out" letters in a word until there is nothing left. I am really tired of him being so much faster than me at it, so it is *your* job to implement it and let me finally beat him. Obviously, since I have to make the program as easy to hide as possible, it has to be small as possible. ## How does this game work? The game is a pretty simple algorithm. It reduces a alphabetical string until it can't be reduced any further, thus making it a sort of hash. The actual game that we humans do is very hard to implement, but it can be simplified into the following algorithm: You start by folding the alphabet in half and lining up the two pieces like such: ``` a b c d e f g h i j k l m z y x w v u t s r p q o n ``` Then, starting from the middle, you assign the positive integers to the top half and the negative to the bottom: ``` a b c d e f g h i j k l m 13 12 11 10 9 8 7 6 5 4 3 2 1 z y x w v u t s r p q o n -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ``` Then you take your string (we will be using `hello world`) and ignoring any non-alphabetical characters, translate it: ``` h e l l o w o r l d 6 9 2 2 -2 -10 -2 -5 2 10 ``` Then you sum the letter values. The ones that lined up in the earlier diagram (e.g. `d` and `w`, `l` and `o`) will cancel out, while the others will add up. ``` sum(6 9 2 2 -2 -10 -2 -5 2 10 )=12 ``` 12 is the number for `b`, so the hash of `hello world` is `b` For a word that completely cancels out (e.g. `love`), you output the "0 character": `-`. Note that in the input, `-` will still be disregarded. It only matters in the output. If the number's magnitude is larger than 13, then you start doubling up on the `a`'s and the `z`'s You basically take as many `a`'s or `z`'s fit into the number and take whatever is left into the last letter like so: ``` code golf: 43. ``` Fits 3 `a`'s and has 4 left over: ``` aaa 4: j result: aaaj ``` Hint: This part is basically `divmod` except that it rounds toward zero, not `-infinity` (e.g. -43 would become 3 `z`'s and and a `-4` which is `p` so `zzzp`). Note: the dash does not come if the `a`'s or `z`'s fit in perfectly, only if it is exactly `0`. ## Clarifications: * The hash is case **in**sensitive * [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are not allowed * I/O can be in any format that isn't too outlandish, stdin, stdout, command-line arg, function, etc. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest size in **bytes** wins. ## Examples: ``` hello world --> b love --> - this is an example --> aak hello *&*(&(*&%& world --> b good bye --> ae root users --> zzs ``` [Answer] # CJam, 46 bytes [Try it online](http://cjam.aditsu.net/#code=lel%7B'n-_W%3E%2B_zE%3C*%7D%25%3A%2B%7B_De%3CC~e%3E___0%3E-'n%2B'-%3Fo-%7Dh%3B&input=hello%20world), or [try the test suite online](http://cjam.aditsu.net/#code=qN%25%7Bel%7B'n-_W%3E%2B_zE%3C*%7D%25%3A%2B%7B_De%3CC~e%3E___0%3E-'n%2B'-%3Fo-%7Dh%3BNo%7D%2F&input=hello%20world%0Alove%0Athis%20is%20an%20example%0Ahello%20*%26*(%26(*%26%25%26%20world%0Agood%20bye%0Aroot%20users). ``` lel{'n-_W>+_zE<*}%:+{_De<C~e>___0>-'n+'-?o-}h; ``` ### Explanation The algorithm works how you might expect: read the input, convert to lowercase, map each character to a value, sum the values, and print characters and adjust the sum accordingly until the sum is zero. Probably the most interesting optimization (although it only saves two bytes) is that negated character mappings are used instead, as this avoids swapping subtraction arguments to correct the sign when computing the mapped value and avoids swapping again when mapping back to a letter due to the subtraction of a negated value being replaceable by addition. ``` lel "Read a line of input and convert all letters to lowercase."; { "Map each character:"; 'n-_W>+ "Map each character to its negated value by subtracting 'n' and incrementing if the result is nonnegative."; _zE<* "If the value is out of the letter range, use 0 instead."; }% :+ "Compute the sum of the mapped character values."; { "Do..."; _De<C~e> "Compute the sum clamped to the letter range."; __ "If the clamped sum is nonzero, ..."; _0>-'n+ "... then produce the clamped sum mapped back to a letter by decrementing if it is positive and adding 'n', ..."; '- "... else produce '-'."; ? o "Output the character produced above."; - "Subtract the clamped sum out of the sum."; }h "... while the sum is nonzero."; ; "Clean up."; ``` [Answer] # Pyth, 79 78 77 65 61 58 ``` J+\-GK+0fTr13_14=ZsX@JzJKMe,pk*G/H13%H13@JxK?g\aZ>Z0_g\z_Z ``` [Answer] # [Clip 10](http://esolangs.org/wiki/Clip), 87 ``` Fr+`m[y?cAyg#Ay-v,-RRZ]0]}m.U`[Fx?x?<x0,:-/xR'z*m'm%xR!!%xR],:/xR'a*m'n%xR!!%xR]]'-[R13 ``` [Answer] # R, 258 bytes ``` function(s){a=13;r=data.frame;z=strsplit(gsub("[^a-z]","",tolower(s)),"")[[1]];d=r(l=rev(letters),h=c(-1*a:1,1:a));m=merge(r(l=z),d);n=sum(m$h);q=abs(n);v=rep(ifelse(n>0,"a","z"),q%/%a);paste0(paste(v,collapse=""),d$l[d$h==sign(n)*q%%a],ifelse(n==0,"-",""))} ``` This has to be the grossest R code ever. I figured R might be a decent choice since it has a vector of all letters "a" through "z" as a built-in global variable. But it turns out the rest is a mess. Ungolfed + explanation: ``` function(s) { a <- 13 # Store the value associated with a r <- data.frame # Store the `data.frame` function # Split the input into a vector, ignoring case and non-letters z <- strsplit(gsub("[^a-z]", "", tolower(s)), "")[[1]] # Create a data frame where the first column is the letters # z through a and the second is the associated scores d <- data.frame(l=reverse(letters), h=c(-1*a:1, 1:a)) # Merge the split vector with the data frame of scores m <- merge(data.frame(l=z), d) # Get the total score for the input n <- sum(m$h) q <- abs(n) # Pad the output with a or z as necessary v <- rep(ifelse(n > 0, "a", "z"), q %/% a) # Collapse the vector of a's or z's into a string out1 <- paste(v, collapse="") # Look up the letter associated with remainder out2 <- d$l[d$h == sign(n)*q%%a] # If n = 0, we still want a dash out3 <- ifelse(n == 0, "-", "") # Return the concatenation of all pieces of the output paste0(out1, out2, out3) } ``` This creates an unnamed function object that accepts a string as input and returns the associated hash value. To call it, give it a name, e.g. `f=function(s){...}`. Examples: ``` > f("this is an example") [1] "aak" > f("root users") [1] "zzs" > f("love") [1] "-" > f("People like grapes.") [1] "aaag" ``` [Try it online!](http://www.r-fiddle.org/#/fiddle?id=VZC0Rz3N&version=1) Questions? I'll happily provide any further explanation. Suggestions? Suggestions are more than welcome! [Answer] # Haskell, 171 bytes ``` import Data.Char m=13 l=zip['a'..'z'][-i|i<-[-m..m],i/=0] p 0="-" p n|n>m='a':p(n-m)|n<(-m)='z':p(n+m)|1<2=[c|(c,i)<-l,i==n] f n=p$sum[y|Just y<-[lookup(toLower x)l|x<-n]] ``` Test run: ``` > map f ["hello world", "love", "this is an example", "hello *&*(&(*&%& world", "good bye", "root users"] ["b","-","aak","b","ae","zzs"] ``` How it works: `l` is a lookup table from letters to the corresponding value. Lookup all characters from the input string and discard those not found. Sum the resulting list. Depending on the sum `p` prints `-` or maybe first some `a`s or `z`s and finally (reverse-)lookups the letter from `l`. [Answer] # R - 200 ``` function(s){l=letters N=setNames x=strsplit(tolower(s),'')[[1]] n=(13:-13)[-14] v=sum(N(n,l)[x[x%in%l]]) o='' while(v){d=min(max(v,-13),13) o=paste0(o,N(l,n)[as.character(d)]) v=v-d} if(o=='')o='-' o} ``` ]
[Question] [ The king of Ancient Rome is having difficulties determining if a magic square is valid or not, because the magic square he is checking does not include any separators between the numbers. He has hired a software engineer to help him determine if a magic square is valid or not. **Input Description** Input comes in on STDIN or command line arguments. You cannot have the input pre-initialised in a variable (e.g. "this program expects the input in a variable `x`"). Input is in the following format: ``` <top>,<middle>,<bottom> ``` Each of `<top>`, `<middle>`, and `<bottom>` is a string that will only ever contain the uppercase characters `I`, `V`, and `X`. It will not contain spaces or any other characters. Each string represents three Roman numerals, thus resulting in a 3x3 matrix of numbers. However, these Roman numerals may (but not necessarily) be *ambiguous*. Allow me to illustrate this with an example. Consider the following example row of three Roman numerals, with no spaces between each number: ``` IVIIIIX ``` Because there are no spaces between the letters, there are two possibilites to the numbers here: * 1, 8, 9 (`I VIII IX`) * 4, 3, 9 (`IV III IX`) When you consider that all three rows of the matrix can be ambigious, there is the potential for there to be many different 3x3 matrixes from a single input. Note that sequences such as 1, 7, 1, 9 (`I VII I IX`) are not possible because each row will always represent three Roman numerals. Also note that the Roman numerals must be valid, so sequences such as 1, 7, 8 (`I VII IIX`) are also not possible. **Output Description** Output: * An integer `A`, where `A` is the number of unique 3x3 matrixes that can be formed from the ambigious input, and: * A [**truthy**](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value if *any* of the unique 3x3 matrixes form a magic square, or: * A [**falsy**](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value if *none* of the unique 3x3 matrixes form a magic square. The truthy and falsy values must be consistent. They are seperated by a comma. Some explanation is required on what is counted as unique. As long as a matrix does not have exactly the same numbers in exactly the same positions as a previously found matrix, it is counted as unique. This means that reflections, etc. of previously found matrixes are counted as unique. **Example Inputs and Outputs** In these examples, I use `true` as my truthy value and `false` as my falsy value. Input: `VIIIIVI,IIIVVII,IVIXII` Output: `24,true` (The magic triangle is 8-1-6, 3-5-7, 4-9-2.) Input: `IIIXVIII,IVIII,VIIII` Output: `210,false` **Extras** * You are not allowed to use inbuilt Roman Numeral conversion functions if your chosen language has one. [Answer] # Perl, 219 ~~237~~ Line breaks added for clarity. ``` #!perl -p %x=(I,1,IV,4,V,5,IX,9,X,10); $a="(X{0,3}(?:V?I{1,3}|I?V|IX)|X{1,3})"x3; m*^$a,$a,$a$(?{ @z=map"$$_",0..9; $r|=!grep$x-$_,map{$x=eval s/./ $z[$&]/gr=~s/IX|IV|\S/+$x{$&}/gr}123,456,789,147,258,369,159,357; ++$- })^*; $_="$-,$r" ``` Test [me](http://ideone.com/p580tK). [Answer] # Prolog - 686 ``` :-lib(util),lib(sd). r(S,R):-string_list(S,L),g(L,R). g(L,[N1,N2,N3]):-append(L1,X,L),append(L2,L3,X),n(L1,N1),n(L2,N2),n(L3,N3). n([73,86],4). n([73,88],9). n([73,73,73],3). n([73,73],2). n([73],1). n([86],5). n([86|N],D):-n(N,E),E<4,D is E+5. n([88|N],D):-n(N,E),D is E+10. n([88],10). m(M,[X1,X2,X3,Y1,Y2,Y3,Z1,Z2,Z3]):-split_string(M,",","",[X,Y,Z]),r(X,[X1,X2,X3]),r(Y,[Y1,Y2,Y3]),r(Z,[Z1,Z2,Z3]). a(L):-alldifferent(L),L=[X1,X2,X3,Y1,Y2,Y3,Z1,Z2,Z3],l(X1,X2,X3,T),l(Y1,Y2,Y3,T),l(Z1,Z2,Z3,T),l(X1,Y1,Z1,T),l(X2,Y2,Z2,T),l(X3,Y3,Z3,T). l(A,B,C,T):-T is A+B+C. p:-read_line(S),findall(L,m(S,L),A),length(A,C),findall(L,(member(L,A),a(L)),B),(B=[_|_]->R=true;R=false),writeln((C,R)). ``` # Ungolfed ``` % I : 73 % V : 86 % X : 88 :-lib(util). :-lib(sd). r(S,R) :- string_list(S,L), g(L,R). g(L,[N1,N2,N3]):- append(L1,X,L), append(L2,L3,X), n(L1,N1),n(L2,N2),n(L3,N3). n([73,86],4). n([73,88],9). n([73,73,73],3). n([73,73],2). n([73],1). n([86],5). n([86|N],D):-n(N,E),E<4,D is E+5. n([88|N],D):-n(N,E), D is E+10. n([88],10). m(M,[X1,X2,X3,Y1,Y2,Y3,Z1,Z2,Z3]) :- split_string(M,",","",[X,Y,Z]), r(X,[X1,X2,X3]), r(Y,[Y1,Y2,Y3]), r(Z,[Z1,Z2,Z3]). a(L) :- alldifferent(L), L=[X1,X2,X3,Y1,Y2,Y3,Z1,Z2,Z3], l(X1,X2,X3,T), l(Y1,Y2,Y3,T), l(Z1,Z2,Z3,T), l(X1,Y1,Z1,T), l(X2,Y2,Z2,T), l(X3,Y3,Z3,T). l(A,B,C,T):-T is A+B+C. p :- read_line(S), findall(L,m(S,L),A), length(A,C), findall(L,(member(L,A),a(L)),B), (B=[_|_]->R=true;R=false), writeln((C,R)). ``` Of course, `p` could also be defined as: ``` p :- read_line(S), findall(L,m(S,L),A), length(A,C), findall(L,(member(L,A),a(L)),B), writeln(C), B=[_|_]. ``` In that case, the environment would say 'Yes' or 'No' after writing the number of squares. # Example Using [eclipse](http://eclipseclp.org/). ``` [eclipse 105]: p. VIIIIVI,IIIVVII,IVIXII 24, true [eclipse 106]: p. IIIXVIII,IVIII,VIIII 210, false ``` Example results for the second one are [pasted here](http://pastebin.com/raw.php?i=7XFkhQyM). [Answer] ## Python, 442 chars ``` R=range L=len S=sum N={} for i in R(40): r="";j=i while j>9:r+="X";j-=10 if j>8:r+="IX";j-=9 if j>4:r+="V";j-=5 if j>3:r+="IV";j-=4 N[r+"III"[:j]]=i a,b,c=map(lambda x:sum([[Z]*all(Z)for i in R(L(x))for j in R(L(x))for Z in[map(N.get,(x[:i],x[i:j],x[j:]))]],[]),raw_input().split(",")) print L(a)*L(b)*L(c),any(S(x)==S(y)==S(z)==S(q[::3])==S(q[1::3])==S(q[2::3])==S(q[::4])==S(q[2:-1:2])for x in a for y in b for z in c for q in[x+y+z]) ``` The code first builds `N` which is a mapping from roman numeral string to its value for all possible numbers we might need. Splits each line into three in every possible way and checks which of the resulting triples all have mappings in `N`. The final `any` sees if any combination is a magic square. [Answer] # Haskell, 451 429 423 bytes ``` import Data.List (#)=splitAt (%)=map w=length r"X"=10 r('X':a)=10+r a r a=case elemIndex a["I","II","III","IV","V","VI","VII","VIII","IX"]of Just i->i+1;_->0 s l=[r%[a,b,c]|x<-[2..w l],y<-[1..x],let(d,c)=x#l;(a,b)=y#d,r a*r b*r c>0] e[a,b,c]=a==b&&a==c p[l,m,n]=[1|a<-l,b<-m,c<-n,e$sum%[a,b,c],e$sum%(transpose[a,b,c])] f i=(show$product$w%(s%i))++","++(show$0<(w$p$s%i)) q ','='\n' q a=a i=getLine>>=putStrLn.f.lines.map q ``` Usage: ``` *Main> i -- repl prompt, call i VIIIIVI,IIIVVII,IVIXII -- input via STDIN 24,True -- output *Main> i IIIXVIII,IVIII,VIIII 210,False ``` About 70 bytes just to get the input and output format right. The function `r` converts a roman number (given as a string) to an integer (if it's not a valid roman number `0` is returned). `s` splits a string of roman digits into 3 substring and keeps those triples with valid roman numbers and converts them via `r` to integers . `e` checks if all integers of a three element list are equal. `p` takes three strings of roman digits, splits them via `s` into lists of integers, combines one integer of each list to triples and keeps those with equal sums in all directions. `f` calculates the number of valid matrices and checks if `p` returns the empty list (no valid solution) or not (valid solution exists). The main function `i` reads the input from STDIN, converts it to a list of strings (`q` helps by replacing `,` with `\n`) and calls `p`. [Answer] # R, ~~489~~ ~~474~~ 464 This got a lot bigger than I wanted, but I suspect I can golf it down a bit. It uses a brute force method, by calculating all the possible Roman Numeral combinations and their corresponding digits. Once that is done it compares the input to the Roman Numeral list and gets the possible digits. From there it goes through each matrix of numbers and test for the magic square, finally outputting the result. ``` s=strsplit;e=expand.grid;P=paste0;d=do.call;i=readline();i=s(i,',');n=1:39;r=c(t(outer(c('','X','XX','XXX'),c('I','II','III','IV','V','VI','VII','VIII','IX','X'),P)))[n];p=d(P,e(r,r,r));n=d(paste,e(n,n,n));m=lapply(i[[1]],function(x)which(p==x));C=e(s(n[m[[1]]],' '),s(n[m[[2]]],' '),s(n[m[[3]]],' '));E=F;N=nrow(C);for(n in 1:N){T=matrix(strtoi(unlist(C[n,])),nr=3);E=E||length(unique(c(rowSums(T),colSums(T),sum(diag(T)),sum(diag(T[3:1,])))))==1};P(N,',',any(E)) ``` Test Run. It waits for input once pasted into the RGui. ``` > e=expand.grid;l=length;s=strsplit;P=paste0;i=readline();i=s(i,',');n=1:39;r=c(t(outer(c('','X','XX','XXX'),c('I','II','III','IV','V','VI','VII','VIII','IX','X'),P)))[-40];p=do.call(P,e(r,r,r));n=do.call(paste,e(n,n,n));m=lapply(i[[1]],function(x)which(p==x));C=e(s(n[m[[1]]],' '),s(n[m[[2]]],' '),s(n[m[[3]]],' '));E=c();N=nrow(C);for(n in 1:N){T=matrix(as.integer(unlist(C[n,])),nr=3);E=c(E,length(unique(c(rowSums(T),colSums(T),sum(diag(T)),sum(diag(T[3:1,])))))==1)};paste(N,',',any(E)) VIIIIVI,IIIVVII,IVIXII [1] "24 , TRUE" > e=expand.grid;l=length;s=strsplit;P=paste0;i=readline();i=s(i,',');n=1:39;r=c(t(outer(c('','X','XX','XXX'),c('I','II','III','IV','V','VI','VII','VIII','IX','X'),P)))[-40];p=do.call(P,e(r,r,r));n=do.call(paste,e(n,n,n));m=lapply(i[[1]],function(x)which(p==x));C=e(s(n[m[[1]]],' '),s(n[m[[2]]],' '),s(n[m[[3]]],' '));E=c();N=nrow(C);for(n in 1:N){T=matrix(as.integer(unlist(C[n,])),nr=3);E=c(E,length(unique(c(rowSums(T),colSums(T),sum(diag(T)),sum(diag(T[3:1,])))))==1)};paste(N,',',any(E)) IIIXVIII,IVIII,VIIII [1] "210 , FALSE" > ``` ]
[Question] [ # Introduction In this challenge, your task is to correctly list the [cases](http://en.wikipedia.org/wiki/Finnish_noun_cases) of two Finnish nouns. The twist is that you may use one of the listings as a guide to produce the other. ### The Nouns We use the following two declination tables as our data. They list the cases of two nouns, one case per line in the same order as in the Wikipedia article linked above, in the form *singular : plural* where applicable. **Table 1: Cases of *ovi* ("door")** ``` ovi : ovet oven : ovien oven : ovet ovea : ovia ovessa : ovissa ovesta : ovista oveen : oviin ovella : ovilla ovelta : ovilta ovelle : oville ovena : ovina oveksi : oviksi ovin ovetta : ovitta ovine ``` **Table 2: Cases of *jalka* ("foot")** ``` jalka : jalat jalan : jalkojen jalan : jalat jalkaa : jalkoja jalassa : jaloissa jalasta : jaloista jalkaan : jalkoihin jalalla : jaloilla jalalta : jaloilta jalalle : jaloille jalkana : jalkoina jalaksi : jaloiksi jaloin jalatta : jaloitta jalkoine ``` # The Task Your task is to write two programs `f` and `g` (possibly with different names) that take one string as input, give one string as output, and have the following property. If Table 1 is given to `f` as input, it outputs Table 2, and if Table 2 is given to `g`, it outputs Table 1. All other inputs result in undefined behavior. The tables must appear *exactly* as above in both input and output. You may optionally assume that there is a trailing newline, but then it must be used in both tables, and in both input and output. There is no preceding newline. # Rules and Bonuses You can write `f` and `g` as either functions or full programs, but they must be of the same type, and they must be completely separate (if you write a helper function for `f`, you must re-write it in `g` if you want to use it there). The lowest total byte count wins, and standard loopholes are disallowed. There is a **bonus of -25 %** for not using regular expressions. ### Some Clarifications It is perfectly fine to write a function/program `f` that ignores its input and always returns Table 2, and a function/program `g` that always returns Table 1. It is only required that `f(*Table 1*) == *Table 2*` and `g(*Table 2*) == *Table 1*`; the behavior of `f` and `g` on all other inputs is irrelevant. The "completely separate" part means the following. Your answer provides two pieces of code, one for `f` and one for `g`, preferably in different code boxes. If I put the code for `f` in a file and run it, it works, and the same for `g`. Your score is the sum of the byte counts of the two pieces of code. Any duplicated code is counted twice. [Answer] # Perl, 105 + 54 = 159 Program `f` (try [me](http://ideone.com/txg3B5)): ``` #!perl -p s/vi /vka /;s/ve/va/g;s/en/an/;s/vi/voi/;s/ov/1&34960>>$.?jalk:jal/eg;s/ii/ihi/;s/loia/lkoje/;s/oia/oja/ ``` Program `g` (try [me](http://ideone.com/WFuced)): ``` #!perl -p s/jalk?o?/ov/g;s/va /vi /;s/va/ve/g;s/an/en/;y/jh/i/d ``` An alternative version of `f`, only 2 bytes longer (this method can be also applied to `g` but it would be too long): ``` #!perl -p0 ka1a1a1koj1a1a1ka1koj1a1o0a1o0kaa2koih1a1o0a1o0a1o0ka1ko0a1o0o0a1o0ko=~s!\D+!"s/ov".'.'x$'."/jal$&/"!gree ``` Technically this still uses a regexp (to decode the substitution string and then to apply them) so I cannot claim the bonus here. [Answer] # Perl, 131 + 74 = 205 ### Table 1 to Table 2 ``` $_=join"",<>;s/ee/kaa/;s/ii/koihi/;s/i(e|a)/koj$1/g;s/i(na|ne)/koi$1/g;s/v[ie](.?a| )/vka$1/g;s/vi/voi/g;s/ve/va/g;s/ov/jal/g;print ``` **Expanded:** ``` $_=join"",<>; s/ee/kaa/; s/ii/koihi/; s/i(e|a)/koj$1/g; s/i(na|ne)/koi$1/g; s/v[ie](.?a| )/vka$1/g; s/vi/voi/g; s/ve/va/g; s/ov/jal/g; print ``` ### Table 2 to Table 1 ``` $_=join"",<>;s/aan/aen/;s/jal(ka\b|oi|ko[ij]h?)/ovi/g;s/jalk?a/ove/g;print ``` **Expanded:** ``` $_=join"",<>; s/aan/aen/; s/jal(ka\b|oi|ko[ij]h?)/ovi/g; s/jalk?a/ove/g; print ``` *(Thanks to @nutki for some Perl tips)* Despite the penalty on regexes, I decided to tackle it anyway and learn Perl while I was at it. I'm assuming there's some Perl tricks which might let me chain replacements, but I couldn't find any in my quick search online. It's much harder to go from the *ovi* table to *jalka* table, which I'm guessing is because the *jalka* table has additional nuances to make words easier to pronounce. --- Here's the replacement table I was working off: ``` i <-> ka -------- ov i jal ka e <-> ka -------- ov e a jal ka a ov e na jal ka na e <-> a ------- ov e t jal a t ov e n jal a n ov e ssa jal a ssa ov e sta jal a sta ov e lla jal a lla ov e lta jal a lta ov e lle jal a lle ov e ksi jal a ksi ov e tta jal a tta i <-> oi -------- ov i ssa jal oi ssa ov i sta jal oi sta ov i lla jal oi lla ov i lta jal oi lta ov i lle jal oi lle ov i ksi jal oi ksi ov i n jal oi n ov i tta jal oi tta i <-> koi --------- ov i na jal koi na ov i ne jal koi ne i <-> koj --------- ov i en jal koj en ov i a jal koj a i <-> koih ------------ ov i in jal koih in ee <-> kaa ---------- ov ee n jal kaa n ``` [Answer] # Python 2, 371 - 25% = 278 When table 1 is the input to function f, it returns table 2. If the input is not table 1, it's output is undefined (however likely but not guaranteed to return table 2). For example, calling `f(9**9**9**9)` will probably not return table 2. ``` f=lambda a:'jalkaBatAanBkojenAanBatAkaaBkojaAassaBoissaAastaBoistaAkaanBkoihinAallaBoillaAaltaBoiltaAalleBoilleAkanaBkoinaAaksiBoiksiAoinAattaBoittaAkoine'.replace('A','\njal').replace('B',' : jal') ``` The same logic is used with function g: ``` g=lambda a:'oviBetAenBienAenBetAeaBiaAessaBissaAestaBistaAeenBiinAellaBillaAeltaBiltaAelleBilleAenaBinaAeksiBiksiAinAettaBittaAine'.replace('A','\nov').replace('B',' : ov') ``` The functions are independent. [Answer] # Python - 462 - 25% = 346.5 This program does the obvious, direct approach except for a few data golfing tricks. For the undefined behavior it print the table just like the defined behavior. What an amazing "coincidence"! :) ``` x,y="""ovi:ovet oven:ovien oven:ovet ovea:ovia ovessa:ovissa ovesta:ovista oveen:oviin ovella:ovilla ovelta:ovilta ovelle:oville ovena:ovina oveksi:oviksi ovin ovetta:ovitta ovineXjalka:jalat jalan:jalkojen jalan:jalat jalkaa:jalkoja jalassa:jaloissa jalasta:jaloista jalkaan:jalkoihin jalalla:jaloilla jalalta:jaloilta jalalle:jaloille jalkana:jalkoina jalaksi:jaloiksi jaloin jalatta:jaloitta jalkoine""".replace(':',' : ').split('X') f=lambda n:y g=lambda n:x ``` Now, if one would consider this cheating (yeah right), I can follow the spirit of the rules for 20 more characters **= 482 - 25%=361.5**. Just replace the last two lines with: ``` f=lambda n:[x,y][n==x] g=lambda n:[y,x][n==y] ``` This would make the undefined behavior return not the correct table but the input table. [Answer] # VBA ~~1204 (1605 - 25%)~~ 1191 (1587 - 25%) The direct approach. ### Edit: Corrected bug and used replace trick from @Maltysen ``` Function f(s) If Replace(s, " : ", ":") = "ovi:ovet" & vbLf & "oven:ovien" & vbLf & "oven:ovet" & vbLf & "ovea:ovia" & vbLf & "ovessa:ovissa" & vbLf & "ovesta:ovista" & vbLf & "oveen:oviin" & vbLf & "ovella:ovilla" & vbLf & "ovelta:ovilta" & vbLf & "ovelle:oville" & vbLf & "ovena:ovina" & vbLf & "oveksi:oviksi" & vbLf & "ovin" & vbLf & "ovetta:ovitta" & vbLf & "ovine" Then f = Replace("jalka:jalat" & vbLf & "jalan:jalkojen" & vbLf & "jalan:jalat" & vbLf & "jalkaa:jalkoja" & vbLf & "jalassa:jaloissa" & vbLf & "jalasta:jaloista" & vbLf & "jalkaan:jalkoihin" & vbLf & "jalalla:jaloilla" & vbLf & "jalalta:jaloilta" & vbLf & "jalalle:jaloille" & vbLf & "jalkana:jalkoina" & vbLf & "jalaksi:jaloiksi" & vbLf & "jaloin" & vbLf & "jalatta:jaloitta" & vbLf & "jalkoine", ":", " : ") End Function Function g(s) If Replace(s, " : ", ":") = "jalka:jalat" & vbLf & "jalan:jalkojen" & vbLf & "jalan:jalat" & vbLf & "jalkaa:jalkoja" & vbLf & "jalassa:jaloissa" & vbLf & "jalasta:jaloista" & vbLf & "jalkaan:jalkoihin" & vbLf & "jalalla:jaloilla" & vbLf & "jalalta:jaloilta" & vbLf & "jalalle:jaloille" & vbLf & "jalkana:jalkoina" & vbLf & "jalaksi:jaloiksi" & vbLf & "jaloin" & vbLf & "jalatta:jaloitta" & vbLf & "jalkoine" Then f = Replace("ovi:ovet" & vbLf & "oven:ovien" & vbLf & "oven:ovet" & vbLf & "ovea:ovia" & vbLf & "ovessa:ovissa" & vbLf & "ovesta:ovista" & vbLf & "oveen:oviin" & vbLf & "ovella:ovilla" & vbLf & "ovelta:ovilta" & vbLf & "ovelle:oville" & vbLf & "ovena:ovina" & vbLf & "oveksi:oviksi" & vbLf & "ovin" & vbLf & "ovetta:ovitta" & vbLf & "ovine", ":", " : ") End Function ``` Run from the Immediate window: ``` msgbox f("ovi : ovet" & vbLf & "oven : ovien" & vbLf & "oven : ovet" & vbLf & "ovea : ovia" & vbLf & "ovessa : ovissa" & vbLf & "ovesta : ovista" & vbLf & "oveen : oviin" & vbLf & "ovella : ovilla" & vbLf & "ovelta : ovilta" & vbLf & "ovelle : oville" & vbLf & "ovena : ovina" & vbLf & "oveksi : oviksi" & vbLf & "ovin" & vbLf & "ovetta : ovitta" & vbLf & "ovine") ``` [Answer] # JavaScript (ES6) 271 (165 + 196 -25%) Starting simple. The functions ignore input parameter at all. Using split/join instead of replace to avoid regular expressions. ``` g=_=>'ovi1et0n1ien0n1et0a1ia0ssa1issa0sta1ista0en1iin0lla1illa0lta1ilta0lle1ille0na1ina0ksi1iksi\novin0tta1itta\novine' .split(0).join('\nove').split(1).join(' : ov') f=_=>'jalka1at0an1kojen0an1at0kaa1koja0assa1oissa0asta1oista0kaan1koihin0alla1oilla0alta1oilta0alle1oille0kana1koina0aksi1oiksi0oin0atta1oitta0koine' .split(0).join('\njal').split(1).join(' : jal') ``` **Test** in Firefox/FireBug console ``` console.log(f('ovi : ovet\noven : ovien\noven : ovet\novea : ovia\novessa : ovissa\novesta : ovista\noveen : oviin\novella : ovilla\novelta : ovilta\novelle : oville\novena : ovina\noveksi : oviksi\novin\novetta : ovitta\novine')) ``` > > jalka : jalat > > jalan : jalkojen > > jalan : jalat > > jalkaa : jalkoja > > jalassa : jaloissa > > jalasta : jaloista > > jalkaan : jalkoihin > > jalalla : jaloilla > > jalalta : jaloilta > > jalalle : jaloille > > jalkana : jalkoina > > jalaksi : jaloiksi > > jaloin > > jalatta : jaloitta > > jalkoine > > > ``` console.log(g("jalka : jalat\njalan : jalkojen\njalan : jalat\njalkaa : jalkoja\njalassa : jaloissa\njalasta : jaloista\njalkaan : jalkoihin\njalalla : jaloilla\njalalta : jaloilta\njalalle : jaloille\njalkana : jalkoina\njalaksi : jaloiksi\njaloin\njalatta : jaloitta\njalkoine")) ``` > > ovi : ovet > > oven : ovien > > oven : ovet > > ovea : ovia > > ovessa : ovissa > > ovesta : ovista > > oveen : oviin > > ovella : ovilla > > ovelta : ovilta > > ovelle : oville > > ovena : ovina > > oveksi : oviksi > > ovin > > ovetta : ovitta > > ovine > > > ]
[Question] [ In [this question](https://codegolf.stackexchange.com/questions/24925/ebcdic-code-golf-happy-birthday-system-360), a mapping is defined between EBCDIC and a superset of ISO-8859-1. Your task is to build a network of two-input NAND gates that will take eight inputs `A1, A2, A4, ..., A128` representing an EBCDIC character and return eight outputs `B1, B2, B4, ..., B128` that represent the corresponding "ISO-8859-1" character according to that mapping. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores: * `NOT: 1` * `AND: 2` * `OR: 3` * `XOR: 4` Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate. The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins. [Answer] ### 727 Gates How I did it: 1. turned the [code page translation from wikipedia](http://en.wikipedia.org/wiki/EBCDIC_037#Code_page_translation) into an appropriately formatted truth table using Excel (15 minutes) 2. minimized the truth table using Espresso (5 minutes, 30 minutes on 1st iteration getting back into the saddle) 3. fed the minimized truth table into a schematic generator (1 minute) 4. iterated on 2&3 until I got a reasonable answer (<1 hour) 5. turned the schematic into an uploadable image (30 min, %$#@! Microsoft) Here's the 100% NAND gate result: ![enter image description here](https://i.stack.imgur.com/QJCdQ.png) If I was actually going to implement this, I'd drop the NAND-centric scoring. Building XOR gates out of NANDs is a big waste of transistors. Then I'd start worrying about UMC, fire up the FPGA design tools, maybe break out the HDL manuals, etc. Whew! I love software. NB, for hobbyists interested in FPGAs, I'll recommend [FPGA4fun](http://www.fpga4fun.com/). [Answer] #309 NANDs# A really low solution in the number of NANDs, but I can go even lower. One just have to stop somewhere, some time, and 309 seems good for that. No pencil drawn image of the circuit this time. Perhaps later if I some day return to this problem and hit a lower edge, ledge, limit, in the increasingly dense thicket of wrong circuits. The circuit is presented in obvious Verilog code, ready for running with test included. Verilog code: ``` // EBCDIC to ISO-latin-1 converter circuit // Made of just 309 NANDs // // By Kim Øyhus 2018 (c) into (CC BY-SA 3.0) // This work is licensed under the Creative Commons Attribution 3.0 // Unported License. To view a copy of this license, visit // https://creativecommons.org/licenses/by-sa/3.0/ // // This is my entry to win this Programming Puzzle & Code Golf // at Stack Exchange: // https://codegolf.stackexchange.com/questions/26252/build-an-ebcdic-converter-using-nand-logic-gates // // There are even simpler solutions to this puzzle, // but I just had to stop somewhere, and 309 NAND gates is // a very low number anyway. module EBCDIC_to_ISO_latin_1 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, out000, out001, out002, out003, out004, out005, out006, out007 ); input in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007; output out000, out001, out002, out003, out004, out005, out006, out007; wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032, wir033, wir034, wir035, wir036, wir037, wir038, wir039, wir040, wir041, wir042, wir043, wir044, wir045, wir046, wir047, wir048, wir049, wir050, wir051, wir052, wir053, wir054, wir055, wir056, wir057, wir058, wir059, wir060, wir061, wir062, wir063, wir064, wir065, wir066, wir067, wir068, wir069, wir070, wir071, wir072, wir073, wir074, wir075, wir076, wir077, wir078, wir079, wir080, wir081, wir082, wir083, wir084, wir085, wir086, wir087, wir088, wir089, wir090, wir091, wir092, wir093, wir094, wir095, wir096, wir097, wir098, wir099, wir100, wir101, wir102, wir103, wir104, wir105, wir106, wir107, wir108, wir109, wir110, wir111, wir112, wir113, wir114, wir115, wir116, wir117, wir118, wir119, wir120, wir121, wir122, wir123, wir124, wir125, wir126, wir127, wir128, wir129, wir130, wir131, wir132, wir133, wir134, wir135, wir136, wir137, wir138, wir139, wir140, wir141, wir142, wir143, wir144, wir145, wir146, wir147, wir148, wir149, wir150, wir151, wir152, wir153, wir154, wir155, wir156, wir157, wir158, wir159, wir160, wir161, wir162, wir163, wir164, wir165, wir166, wir167, wir168, wir169, wir170, wir171, wir172, wir173, wir174, wir175, wir176, wir177, wir178, wir179, wir180, wir181, wir182, wir183, wir184, wir185, wir186, wir187, wir188, wir189, wir190, wir191, wir192, wir193, wir194, wir195, wir196, wir197, wir198, wir199, wir200, wir201, wir202, wir203, wir204, wir205, wir206, wir207, wir208, wir209, wir210, wir211, wir212, wir213, wir214, wir215, wir216, wir217, wir218, wir219, wir220, wir221, wir222, wir223, wir224, wir225, wir226, wir227, wir228, wir229, wir230, wir231, wir232, wir233, wir234, wir235, wir236, wir237, wir238, wir239, wir240, wir241, wir242, wir243, wir244, wir245, wir246, wir247, wir248, wir249, wir250, wir251, wir252, wir253, wir254, wir255, wir256, wir257, wir258, wir259, wir260, wir261, wir262, wir263, wir264, wir265, wir266, wir267, wir268, wir269, wir270, wir271, wir272, wir273, wir274, wir275, wir276, wir277, wir278, wir279, wir280, wir281, wir282, wir283, wir284, wir285, wir286, wir287, wir288, wir289, wir290, wir291, wir292, wir293, wir294, wir295, wir296, wir297, wir298, wir299, wir300, wir301, wir302; nand gate000 ( wir000, in_003, in_000 ); nand gate001 ( wir001, in_002, in_002 ); nand gate002 ( wir002, in_000, in_000 ); nand gate003 ( wir003, in_000, in_004 ); nand gate004 ( wir004, wir003, in_001 ); nand gate005 ( wir005, in_006, in_003 ); nand gate006 ( wir006, wir003, wir005 ); nand gate007 ( wir007, in_007, in_007 ); nand gate008 ( wir008, wir003, wir004 ); nand gate009 ( wir009, wir003, wir006 ); nand gate010 ( wir010, in_005, wir009 ); nand gate011 ( wir011, wir008, wir009 ); nand gate012 ( wir012, wir009, wir011 ); nand gate013 ( wir013, in_004, wir002 ); nand gate014 ( wir014, wir013, wir009 ); nand gate015 ( wir015, in_006, wir007 ); nand gate016 ( wir016, wir001, wir015 ); nand gate017 ( wir017, wir015, wir015 ); nand gate018 ( wir018, in_003, wir015 ); nand gate019 ( wir019, wir018, wir018 ); nand gate020 ( wir020, wir000, wir007 ); nand gate021 ( wir021, wir005, wir017 ); nand gate022 ( wir022, wir018, wir011 ); nand gate023 ( wir023, in_002, wir018 ); nand gate024 ( wir024, in_001, in_003 ); nand gate025 ( wir025, wir010, in_004 ); nand gate026 ( wir026, wir017, wir024 ); nand gate027 ( wir027, wir001, wir007 ); nand gate028 ( wir028, in_004, wir024 ); nand gate029 ( wir029, wir024, wir024 ); nand gate030 ( wir030, in_004, wir023 ); nand gate031 ( wir031, wir022, wir030 ); nand gate032 ( wir032, wir026, wir030 ); nand gate033 ( wir033, wir030, wir020 ); nand gate034 ( wir034, wir001, wir026 ); nand gate035 ( wir035, wir022, in_007 ); nand gate036 ( wir036, wir020, wir034 ); nand gate037 ( wir037, wir007, wir023 ); nand gate038 ( wir038, wir034, wir023 ); nand gate039 ( wir039, wir031, wir033 ); nand gate040 ( wir040, wir028, wir019 ); nand gate041 ( wir041, wir036, wir040 ); nand gate042 ( wir042, in_001, wir025 ); nand gate043 ( wir043, wir041, wir010 ); nand gate044 ( wir044, wir038, wir000 ); nand gate045 ( wir045, wir033, wir004 ); nand gate046 ( wir046, wir039, wir045 ); nand gate047 ( wir047, in_002, wir046 ); nand gate048 ( wir048, wir011, wir037 ); nand gate049 ( wir049, wir012, in_006 ); nand gate050 ( wir050, wir048, wir007 ); nand gate051 ( wir051, wir048, wir049 ); nand gate052 ( wir052, in_006, in_004 ); nand gate053 ( wir053, wir043, wir001 ); nand gate054 ( wir054, wir042, wir053 ); nand gate055 ( wir055, wir019, wir007 ); nand gate056 ( wir056, wir016, wir039 ); nand gate057 ( wir057, in_003, wir026 ); nand gate058 ( wir058, wir029, in_007 ); nand gate059 ( wir059, in_005, wir055 ); nand gate060 ( wir060, wir035, wir054 ); nand gate061 ( wir061, wir055, wir060 ); nand gate062 ( wir062, wir032, in_003 ); nand gate063 ( wir063, wir002, wir059 ); nand gate064 ( wir064, wir062, wir025 ); nand gate065 ( wir065, wir063, wir036 ); nand gate066 ( wir066, wir060, wir065 ); nand gate067 ( wir067, wir037, wir065 ); nand gate068 ( wir068, wir029, in_006 ); nand gate069 ( wir069, wir067, wir043 ); nand gate070 ( wir070, wir061, wir069 ); nand gate071 ( wir071, wir047, wir070 ); nand gate072 ( wir072, wir071, wir071 ); nand gate073 ( wir073, wir071, wir038 ); nand gate074 ( wir074, wir010, wir073 ); nand gate075 ( wir075, wir021, wir038 ); nand gate076 ( wir076, wir028, wir066 ); nand gate077 ( wir077, wir076, wir056 ); nand gate078 ( wir078, wir077, wir077 ); nand gate079 ( wir079, wir072, wir013 ); nand gate080 ( wir080, wir079, wir026 ); nand gate081 ( wir081, wir080, wir080 ); nand gate082 ( wir082, wir078, wir025 ); nand gate083 ( wir083, wir022, wir082 ); nand gate084 ( wir084, in_001, wir083 ); nand gate085 ( wir085, wir044, wir083 ); nand gate086 ( wir086, wir085, wir081 ); nand gate087 ( wir087, wir027, wir086 ); nand gate088 ( wir088, wir087, wir007 ); nand gate089 ( wir089, wir074, wir087 ); nand gate090 ( wir090, wir051, wir075 ); nand gate091 ( wir091, wir068, wir089 ); nand gate092 ( wir092, wir091, wir091 ); nand gate093 ( wir093, wir084, wir002 ); nand gate094 ( wir094, wir051, wir091 ); nand gate095 ( wir095, wir094, wir042 ); nand gate096 ( wir096, wir021, wir094 ); nand gate097 ( wir097, wir093, wir096 ); nand gate098 ( wir098, wir096, wir044 ); nand gate099 ( wir099, wir063, wir096 ); nand gate100 ( wir100, wir088, wir026 ); nand gate101 ( wir101, wir090, wir099 ); nand gate102 ( wir102, wir101, wir101 ); nand gate103 ( wir103, wir100, wir066 ); nand gate104 ( wir104, wir057, wir102 ); nand gate105 ( wir105, wir102, wir092 ); nand gate106 ( wir106, wir102, wir059 ); nand gate107 ( wir107, wir038, wir103 ); nand gate108 ( wir108, wir072, wir102 ); nand gate109 ( wir109, wir108, wir052 ); nand gate110 ( wir110, wir052, wir021 ); nand gate111 ( wir111, wir100, wir110 ); nand gate112 ( wir112, wir110, wir106 ); nand gate113 ( wir113, wir109, wir112 ); nand gate114 ( wir114, wir104, wir038 ); nand gate115 ( wir115, in_007, wir113 ); nand gate116 ( wir116, wir060, wir115 ); nand gate117 ( wir117, wir115, wir058 ); nand gate118 ( wir118, wir117, wir038 ); nand gate119 ( wir119, wir117, wir117 ); nand gate120 ( wir120, wir116, in_006 ); nand gate121 ( wir121, wir093, wir081 ); nand gate122 ( wir122, wir119, wir120 ); nand gate123 ( wir123, wir120, wir002 ); nand gate124 ( wir124, wir119, in_007 ); nand gate125 ( wir125, wir052, wir120 ); nand gate126 ( wir126, wir120, wir020 ); nand gate127 ( wir127, wir020, wir126 ); nand gate128 ( wir128, wir126, wir124 ); nand gate129 ( wir129, wir128, wir106 ); nand gate130 ( wir130, wir100, wir104 ); nand gate131 ( wir131, in_007, wir128 ); nand gate132 ( wir132, wir061, wir128 ); nand gate133 ( wir133, wir064, wir050 ); nand gate134 ( wir134, wir068, wir093 ); nand gate135 ( wir135, wir134, wir044 ); nand gate136 ( wir136, wir127, wir121 ); nand gate137 ( wir137, wir095, wir136 ); nand gate138 ( wir138, wir105, wir137 ); nand gate139 ( wir139, wir058, wir138 ); nand gate140 ( wir140, wir138, wir118 ); nand gate141 ( wir141, wir078, wir131 ); nand gate142 ( wir142, wir140, wir140 ); nand gate143 ( wir143, wir129, wir140 ); nand gate144 ( wir144, wir129, wir109 ); nand gate145 ( wir145, wir090, in_005 ); nand gate146 ( wir146, wir145, wir145 ); nand gate147 ( wir147, wir133, wir059 ); nand gate148 ( wir148, wir093, wir147 ); nand gate149 ( wir149, wir148, wir148 ); nand gate150 ( wir150, wir131, wir131 ); nand gate151 ( wir151, wir143, wir116 ); nand gate152 ( wir152, wir021, wir132 ); nand gate153 ( wir153, wir144, wir051 ); nand gate154 ( wir154, wir122, wir149 ); nand gate155 ( wir155, wir149, wir142 ); nand gate156 ( wir156, in_001, wir149 ); nand gate157 ( wir157, wir123, wir098 ); nand gate158 ( wir158, wir058, wir133 ); nand gate159 ( wir159, in_007, wir158 ); nand gate160 ( wir160, wir133, wir157 ); nand gate161 ( wir161, wir129, wir159 ); nand gate162 ( wir162, wir059, wir100 ); nand gate163 ( wir163, wir130, wir159 ); nand gate164 ( wir164, wir152, wir146 ); nand gate165 ( wir165, wir164, wir155 ); nand gate166 ( wir166, wir121, wir164 ); nand gate167 ( wir167, wir166, wir157 ); nand gate168 ( wir168, wir167, wir058 ); nand gate169 ( wir169, wir059, wir104 ); nand gate170 ( wir170, wir139, wir169 ); nand gate171 ( wir171, wir135, wir168 ); nand gate172 ( wir172, wir171, wir156 ); nand gate173 ( wir173, wir025, in_004 ); nand gate174 ( wir174, wir172, wir143 ); nand gate175 ( wir175, wir000, wir172 ); nand gate176 ( wir176, wir154, wir172 ); nand gate177 ( wir177, wir176, wir162 ); nand gate178 ( wir178, wir111, in_005 ); nand gate179 ( wir179, in_004, wir144 ); nand gate180 ( wir180, wir162, wir178 ); nand gate181 ( wir181, wir173, wir141 ); nand gate182 ( wir182, wir180, wir131 ); nand gate183 ( wir183, wir154, wir182 ); nand gate184 ( wir184, wir090, wir183 ); nand gate185 ( wir185, wir184, wir179 ); nand gate186 ( wir186, wir107, wir058 ); nand gate187 ( wir187, wir097, wir184 ); nand gate188 ( wir188, wir016, wir177 ); nand gate189 ( wir189, wir114, wir188 ); nand gate190 ( wir190, wir189, wir143 ); nand gate191 ( wir191, wir109, wir190 ); nand gate192 ( wir192, wir185, wir190 ); nand gate193 ( wir193, wir190, in_004 ); nand gate194 ( wir194, wir193, wir135 ); nand gate195 ( wir195, wir192, wir165 ); nand gate196 ( wir196, wir194, wir161 ); nand gate197 ( wir197, wir161, wir196 ); nand gate198 ( wir198, wir196, wir185 ); nand gate199 ( wir199, wir198, wir198 ); nand gate200 ( wir200, wir155, wir181 ); nand gate201 ( wir201, wir200, wir119 ); nand gate202 ( wir202, in_006, wir090 ); nand gate203 ( wir203, in_001, wir052 ); nand gate204 ( wir204, wir185, wir202 ); nand gate205 ( wir205, wir175, wir198 ); nand gate206 ( wir206, wir205, wir150 ); nand gate207 ( wir207, wir205, wir200 ); nand gate208 ( wir208, wir207, wir168 ); nand gate209 ( wir209, wir208, wir185 ); nand gate210 ( wir210, wir144, wir199 ); nand gate211 ( wir211, wir210, wir187 ); nand gate212 ( wir212, wir210, wir135 ); nand gate213 ( wir213, wir187, wir144 ); nand gate214 ( wir214, wir151, wir210 ); nand gate215 ( wir215, wir143, wir105 ); nand gate216 ( wir216, wir021, wir215 ); nand gate217 ( wir217, wir160, wir160 ); nand gate218 ( wir218, wir186, wir061 ); nand gate219 ( wir219, wir216, wir025 ); nand gate220 ( wir220, wir219, wir122 ); nand gate221 ( wir221, wir212, wir219 ); nand gate222 ( wir222, wir209, wir105 ); nand gate223 ( wir223, wir191, wir213 ); nand gate224 ( wir224, wir168, wir221 ); nand gate225 ( wir225, wir224, wir224 ); nand gate226 ( wir226, wir144, wir209 ); nand gate227 ( wir227, wir020, wir222 ); nand gate228 ( wir228, wir129, wir226 ); nand gate229 ( wir229, wir228, wir160 ); nand gate230 ( wir230, wir229, wir229 ); nand gate231 ( wir231, wir197, wir230 ); nand gate232 ( wir232, wir230, wir214 ); nand gate233 ( wir233, wir173, wir230 ); nand gate234 ( wir234, wir056, wir174 ); nand gate235 ( wir235, wir146, wir181 ); nand gate236 ( wir236, wir235, wir225 ); nand gate237 ( wir237, wir236, wir014 ); nand gate238 ( wir238, wir236, wir174 ); nand gate239 ( wir239, wir155, wir203 ); nand gate240 ( wir240, wir209, wir236 ); nand gate241 ( wir241, wir146, wir225 ); nand gate242 ( wir242, wir191, wir241 ); nand gate243 ( wir243, wir241, wir209 ); nand gate244 ( wir244, wir206, wir111 ); nand gate245 ( wir245, wir243, wir233 ); nand gate246 ( wir246, wir223, wir234 ); nand gate247 ( wir247, wir191, wir186 ); nand gate248 ( wir248, wir056, wir238 ); nand gate249 ( wir249, wir248, wir218 ); nand gate250 ( wir250, wir243, wir249 ); nand gate251 ( wir251, wir239, wir174 ); nand gate252 ( wir252, wir251, wir231 ); nand gate253 ( wir253, wir249, wir244 ); nand gate254 ( wir254, wir240, wir150 ); nand gate255 ( wir255, wir253, wir139 ); nand gate256 ( wir256, wir242, wir253 ); nand gate257 ( wir257, wir244, wir195 ); nand gate258 ( wir258, wir204, wir201 ); nand gate259 ( out007, wir254, wir255 ); nand gate260 ( wir259, wir217, wir253 ); nand gate261 ( wir260, wir258, wir259 ); nand gate262 ( wir261, wir197, wir260 ); nand gate263 ( wir262, wir220, wir261 ); nand gate264 ( wir263, wir261, wir192 ); nand gate265 ( wir264, wir262, wir263 ); nand gate266 ( wir265, wir201, wir125 ); nand gate267 ( wir266, wir265, wir250 ); nand gate268 ( wir267, wir266, wir237 ); nand gate269 ( wir268, wir266, wir199 ); nand gate270 ( wir269, wir136, wir244 ); nand gate271 ( wir270, wir264, wir195 ); nand gate272 ( wir271, wir256, wir268 ); nand gate273 ( wir272, wir247, wir269 ); nand gate274 ( wir273, wir271, in_001 ); nand gate275 ( wir274, wir256, wir271 ); nand gate276 ( wir275, wir273, wir274 ); nand gate277 ( wir276, wir275, wir275 ); nand gate278 ( wir277, wir249, wir227 ); nand gate279 ( wir278, wir222, in_006 ); nand gate280 ( wir279, wir278, wir153 ); nand gate281 ( wir280, wir272, wir163 ); nand gate282 ( wir281, wir278, wir170 ); nand gate283 ( wir282, wir245, wir281 ); nand gate284 ( wir283, wir204, wir282 ); nand gate285 ( out005, wir283, wir254 ); nand gate286 ( wir284, wir232, wir201 ); nand gate287 ( wir285, wir284, wir197 ); nand gate288 ( wir286, wir257, wir285 ); nand gate289 ( wir287, out007, wir279 ); nand gate290 ( wir288, wir163, wir287 ); nand gate291 ( wir289, wir245, wir288 ); nand gate292 ( wir290, wir288, wir247 ); nand gate293 ( wir291, wir252, wir211 ); nand gate294 ( wir292, wir277, wir232 ); nand gate295 ( wir293, wir192, wir292 ); nand gate296 ( wir294, wir290, wir280 ); nand gate297 ( wir295, wir264, wir292 ); nand gate298 ( wir296, wir217, wir264 ); nand gate299 ( wir297, wir221, wir295 ); nand gate300 ( out003, wir294, wir295 ); nand gate301 ( wir298, wir273, wir297 ); nand gate302 ( out002, wir298, wir246 ); nand gate303 ( out006, wir240, wir289 ); nand gate304 ( wir299, wir293, wir250 ); nand gate305 ( out000, wir270, wir267 ); nand gate306 ( out001, wir276, wir291 ); nand gate307 ( wir300, wir299, wir296 ); nand gate308 ( out004, wir286, wir300 ); endmodule module test; reg [7:0] AB; // C=A*B wire [7:0] C; EBCDIC_to_ISO_latin_1 U1 ( .in_000 (AB[0]), .in_001 (AB[1]), .in_002 (AB[2]), .in_003 (AB[3]), .in_004 (AB[4]), .in_005 (AB[5]), .in_006 (AB[6]), .in_007 (AB[7]), .out000 (C[0]), .out001 (C[1]), .out002 (C[2]), .out003 (C[3]), .out004 (C[4]), .out005 (C[5]), .out006 (C[6]), .out007 (C[7]) ); initial AB=0; always #1 AB = AB+1; initial begin $display("\t\ttime,\tEBCDIC \tISO-latin-1"); $monitor("%d,\t%b %b\t%b %b\t%c",$time, AB[7:4], AB[3:0], C[7:4], C[3:0], C); end initial #255 $finish; endmodule // iverilog -o EBCDIC_309 EBCDIC_309.v // vvp EBCDIC_309 /* https://codegolf.stackexchange.com/questions/24925/ebcdic-code-golf-happy-birthday-system-360 EBCDIC037_to_Latin1 = [ 0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f, 0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f, 0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07, 0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a, 0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c, 0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac, 0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f, 0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22, 0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1, 0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4, 0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae, 0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7, 0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5, 0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff, 0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f]; */ ``` Kim Øyhus ]
[Question] [ **Important edit: Earlier, there was an incorrect value in Example 1. It has been fixed.** You are given a two-dimensional array in which each cell contains one of four values. Examples: ``` 1 2 2 2 2 1 @ . . X X V 1 3 1 4 1 4 e . @ I C V 2 3 1 3 4 2 H H @ X I V 1 4 4 2 1 3 V C C 2 2 2 3 2 3 X X X ``` The four values represent directional arrows (up, down, left, and right), although you don't know which value represents which direction. The directional arrows form an unbroken path that includes every cell in the array, although you don't know where the start or end points are. Write some code that determines which direction each of the four values represents and where the start and end points are. An acceptable return value for an array that contains the values A, B, C, and D would be something like: ``` { up: A, down: C, left: D, right: B, start: [2, 0], end: [4, 2] } ``` ~~Because you can traverse the path both ways (from start to end and from end to start), there will always be more than one correct solution, and there might be more than two.~~ Assume that the inputs you receive (as in the above examples) always have at least one correct solution. In cases where there is more than one correct solution, returning just one of the correct solutions is sufficient. Shortest code wins. I'll pick the winner after 7 days or 24 hours without a new submission, whichever comes first. I'm including solutions to the examples above, but I'd encourage you to only check them once you've written your code: One: > > { up: 3, down: 1, left: 4, right: 2, start: [0,0], end: [2,5] } > > > Two: > > { up: '@', down: 'e', left: '.', right: 'H', start: [1,1], end: [0,0] } > > > Three: > > { up: 'I', down: 'V', left: 'C', right: 'X', start: [0,2], end: [4,2] } > > > [Answer] ## C# EDIT: Fixed a division and formatting. And added the helper class. This is the golfed code, 807 chars ``` class M{public int c,x,y,u;} void G(string[] z){ M K;int[]x={0,0,-1,1},y={-1,1,0,0},I={0,0,0,0}; string[]T={"Up","Down","Left","Right"}; int X,Y,R,n=0,H=z.Length,W=z[0].Length;W-=W/2;var D= string.Join(" ", z).Where(c=>c!=' ').Select(c=>new M(){c=c,x=n%W,y=n++/W}).ToList();n=0;var S=D.GroupBy(k=>k.c).ToDictionary(k=>k.Key,k =>n++); for(;I[0]<4;I[0]++)for(I[1]=0;I[1]<4;I[1]++)for(I[2]=0;I[2]<4;I[2]++)for(I[3]=0;I[3]<4;I[3]++){ if ((1<<I[0]|1<<I[1]|1<<I[2]|1<<I[3])!=15)continue; foreach (var Q in D){D.ForEach(p=>p.u=-1);R=1;K=Q;j:if((X=K.x+x[n=I[S[K.c]]])>=0&&X<W&&(Y=K.y+y[n])>=0&&Y<H&&(K=D[X+Y*W]).u<0){ K.u=1;if(++R==D.Count){Console.WriteLine("{4} Start({0}:{1}) End({2}:{3})",Q.x,Q.y,K.x,K.y,string.Join(", ",S.Select(k=>string.Format("{1}: '{0}'",(char)k.Key,T[I[k.Value]])).ToArray()));return;}goto j;}}} } ``` Results for the three test cases: > > Down: '1', Right: '2', Up: '3', Left: '4' Start(0:0) End(5:2) > > Up: '@', Left: '.', Down: 'e', Right: 'H' Start(1:1) End(0:0) > > Right: 'X', Down: 'V', Up: 'I', Left: 'C' Start(0:2) End(2:4) > > > This is the raw code without "golf", almost 4,000 characters: ``` class Program { static string[] input1 = { "1 2 2 2 2 1", "1 3 4 4 1 4", "2 3 1 3 4 2", "1 4 4 2 1 3", "2 2 2 3 2 3"}; static string[] input2 = { "@ . .", "e . @", "H H @", }; static string[] input3 = { "0 0 1", "0 0 1", "3 2 2", }; static void Main(string[] args) { Resolve(input1); Resolve(input2); Resolve(input3); Console.ReadLine(); } class N { public int c; public int x, y, i, u; } static void Resolve(string[] input) { int[] ox = { -1, 1, 0, 0 }, oy = { 0, 0, -1, 1 }, I = { 0, 0, 0, 0 }; string[] TXT = { "Left", "Right", "Up", "Down" }; int X, Y, R, n = 0, H = input.Length, W = input[0].Length; W -= W / 2; N K = null; var data = string.Join(" ", input).Where(c => c != ' ').Select(c => new N() { c = c, x = (n % W), y = (n / W), i = n++, u = -1 }).ToList(); n = 0; var S = data.GroupBy(k => k.c).ToDictionary(k => k.Key, k => n++); for (; I[0] < 4; I[0]++) for (I[1] = 0; I[1] < 4; I[1]++) for (I[2] = 0; I[2] < 4; I[2]++) for (I[3] = 0; I[3] < 4; I[3]++) { if (((1 << I[0]) | (1 << I[1]) | (1 << I[2]) | (1 << I[3])) != 15) continue; foreach(var Q in data) { data.ForEach(p => p.u = -1); R = 0; K = Q; while (K != null) { n = I[S[K.c]]; X = K.x + ox[n]; Y = K.y + oy[n]; if (X >= 0 && X < W && Y >= 0 && Y < H) { n = X + Y * W; if (data[n].u < 0) { data[n].u = K.i; K = data[n]; R++; if (R == data.Count - 1) { Console.WriteLine(); Console.WriteLine("Start({0}:{1}) End({2}:{3})", Q.x, Q.y, K.x, K.y); Console.WriteLine(string.Join(", ", S.Select(k => string.Format("'{0}': {1}", (char)k.Key, TXT[I[k.Value]])).ToArray())); Action<N> Write = null; Write = (k) => { if (k.u != -1) { Write(data[k.u]); } Console.Write(string.Format("({0}:{1}){2}", k.x, k.y, k == K ? "\n" : " => ")); }; Write(K); return; } continue; } } K = null; } } } Console.WriteLine("Solution not found"); } } } ``` These are the results for the three examples: > > Solution not found > > > Start(1:1) End(0:0) '@': Up, '.': Left, 'e': Down, 'H': Right > > > (1:1) => (0:1) => (0:2) => (1:2) => (2:2) => (2:1) => (2:0) => (1:0) => (0:0) > > > Start(0:0) End(1:1) '0': Right, '1': Down, '3': Up, '2': Left > > > (0:0) => (1:0) => (2:0) => (2:1) => (2:2) => (1:2) => (0:2) => (0:1) => (1:1) > > > [Answer] ## Mathematica 278 Spaces added for "clarity" ``` k@l_ := (s = #~Join~-# &@{{1, 0}, {0, 1}}; f@r_ := Flatten[MapIndexed[#2 -> #2 + (#1 /. r) &, l, {2}], 1]; g = Subgraph[#, t = Tuples@Range@Dimensions@l] & /@ Graph /@ f /@ (r = Thread[# -> s] & /@ Permutations[Union @@ l]); {t[[#]] & /@ Ordering[Tr /@ IncidenceMatrix@g[[#]]][[{1, -1}]], r[[#]]} & @@@ Position[PathGraphQ /@ g, True]) ``` Session & Output: ``` l = l1 = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2}, {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}}; ; k@l1 {{{{1, 1}, {3, 6}}, {1 -> {1, 0}, 2 -> {0, 1}, 3 -> {-1, 0}, 4 -> {0, -1}}}} ``` Which is the start Vertex, End Vertex and the transition rules associated with each symbol. Here is the complementary code to show the oriented graph: ``` sol = sg[[Position[PathGraphQ /@ sg, True][[1, 1]]]]; Framed@Graph[ VertexList@sol, EdgeList@sol, VertexCoordinates -> VertexList@sol /. {x_, y_} :> {y, -x}, VertexLabels -> MapThread[Rule, {VertexList@sol, Flatten@l}], EdgeShapeFunction -> GraphElementData["FilledArcArrow", "ArrowSize" -> 0.03], ImagePadding -> 20] ``` ![Mathematica graphics](https://i.stack.imgur.com/kipgh.png) [Answer] # Mathematica (151) ``` L = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2}, {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}}; PathGraphQ@#~If~Print@{TopologicalSort[#]〚{1,-2}〛,r}&@ Graph@Flatten@MapIndexed[#2->#2+(#/.r)&,L,{2}]~Do~{r, Thread[Union@@L->#]&/@{-1,0,1}~Tuples~{4,2}} ``` It returns start point, end point, and transition rules. The first index is row, the second is column ``` {{{1,1},{3,6}},{1->{1,0},2->{0,1},3->{-1,0},4->{0,-1}}} ``` Note that my code works even with `{-1,0,1}~Tuples~{4,2}`. For speeding up you can use `Permutations@{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}` instead. [Answer] # APL (207) I couldn't make it shorter than Mathematica, because I couldn't reason in terms of TopologicalSort and such. Smarter people are welcome to squeeze it further. **Golfed:** ``` {u←∪,t←⍵⋄q r←↑(0≠+/¨r)/⊂[2]p,⍪r←{m←,⍵[u⍳t]⋄v r←⊂[1]⊃{{(↑⍴∪⍵),⊂(↑⍵)(↑⌽⍵)}n↑{3::⍬⋄i←↑⌽⍵⋄⍵,i+i⌷m}⍣n,⍵}¨⍳n←↑⍴,t⋄↑(v=n)/r}¨p←⊂[2]{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}d←¯1 1,¯1 1×c←¯1↑⍴t⋄⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1} ``` **Ungolfed:** ``` D←{⎕ML ⎕IO←3 1 pmat←{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵} ⍝ utility: permutations of the given vector u←∪,t←⍵ ⍝ the 4 unique symbols in t←⍵ n←↑⍴,t ⍝ number of elements in t d←¯1 1,¯1 1×c←¯1↑⍴t ⍝ the four ∆i (+1, -1, +cols, -cols) p←⊂[2]pmat d ⍝ list of permutations of the four ∆i r←{ ⍝ for each permutation ⍵∊p (=interpretation of the 4 symbols) m←,⍵[u⍳t] ⍝ (ravelled) t-shaped matrix of ∆i, using interpretation ⍵ v r←⊂[1]⊃{ ⍝ for each starting index ⍵∊⍳n v←n↑{ ⍝ trail of visited cells after n steps 3::⍬ ⍝ if index out of bounds return empty list i←↑⌽⍵ ⍝ take last visited index ⍵,i+i⌷m ⍝ follow the directions and add it to the list }⍣n,⍵ (↑⍴∪v),⊂(↑v),↑⌽v ⍝ number of unique cells, plus start/end indices }¨⍳n ↑(v=n)/r ⍝ 1st couple of start/end indices to visit all cells (if any) }¨p q r←↑(0≠+/¨r)/⊂[2]p,⍪r ⍝ select first perm. and start/end indices to visit all cells ⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1 ⍝ return char mapping and start/end indices } ``` **Examples:** (Indices start at 1) ``` D⊃'122221' '131414' '231342' '144213' '222323' ← 4 → 2 ↑ 3 ↓ 1 1 1 3 6 D⊃'@..' 'e.@' 'HH@' ← . → H ↑ @ ↓ e 2 2 1 1 D⊃'XXV' 'ICV' 'XIV' 'VCC' 'XXX' ← C → X ↑ I ↓ V 3 1 5 3 ``` ]
[Question] [ Those of you who like Numberphile would be familiar with Dr. James Grime, who [described a non-transitive dice game on his channel](https://www.youtube.com/watch?v=zWUrwhaqq_c). The game consists of three 6-faced dice: * Die 1: 3,3,3,3,3,6 * Die 2: 2,2,2,5,5,5 * Die 3: 1,4,4,4,4,4 Two players each select a die to use. They roll them and the higher die wins, best-of-whatever. Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1. Write a program taking `1`, `2` or `3` as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "`Computer/User wins with x points`" # Rules * Code-golf, votes as tiebreaker * You must use RNG (or the likes) to actually simulate the dice rolls. * I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above. * Input can be stdin, command line argument, from screen, etc. # Example **Input** ``` 1 ``` **Output** ``` 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 6 1 3 4 3 4 3 1 3 4 3 1 3 4 3 4 3 4 3 4 3 4 6 Computer wins with 16 points ``` Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him. [Answer] ## APL (~~106~~ 114) ``` 'Computer' 'User'[1+X],'wins with','points',⍨|Z-21×X←11>Z←+/>/⎕←⍉↑{⍵[{?6}¨⍳21]}¨(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2] ``` Explanation: * `(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]`: The big number is a base-7 representation of the dice. We make a 6x5 matrix containing the values of the dice in the order: 2 3 1 2 3. Ask for user input and add this to the vector `1 2`, and select these lines from the matrix. Because the list of dice is shifted, the user now gets the one he selected (on the right) and the computer gets the stronger one. * `{⍵[{?6}¨⍳21]}¨`: do 21 rolls for each of these two dice. * `⎕←⍉↑`: put the rolls in matrix form and output them. * `Z←+/>/`: get the score of the computer (amount of times the computer's value was higher than the user's) * `X←11>Z`: set `X` to whether the user won (if 11 is higher than the computer's score). * `'Computer' 'User'[1+X]`. `X` is whether the user won. * `'wins with','points',⍨|Z-21×X`: `Z` is the computer's score, so if the computer won display `Z`, otherwise display `21-Z`. [Answer] # R - 228 ``` d=matrix(rep(c(rep(3,5),6,2,2,2,5,5,5,1,rep(4,5)),2),6) x=scan() r=expand.grid(Computer=d[,x+2],User=d[,x])[sample(36,21,T),] print(r) s=summary.factor(names(r)[max.col(r)]) cat(names(which.max(s)),"wins with",max(s),"points\n") ``` Example run: ``` > source('ntd.R') 1: 2 2: Read 1 item Computer User 28 3 5 31 3 5 36 6 5 18 6 2 11 3 2 31.1 3 5 14 3 2 8 3 2 9 3 2 17 3 2 2 3 2 29 3 5 3 3 2 16 3 2 4 3 2 21 3 5 14.1 3 2 23 3 5 16.1 3 2 17.1 3 2 19 3 5 Computer wins with 14 points ``` [Answer] ## Mathematica ~~208~~ ~~172~~ ~~166~~ 159 Spaces added for clarity ``` b=Boole;{#, Row@{ If[# > 10, "Play", "Comput"], "er wins with ", Max[#, 21 - #], " points"} &@ Total[b[#1 > #2] & @@@ #]} &@ Table[1 + i + 3 b[6 Random[] > 2 i + 1],{21}, {i, {#, Mod[# + 1, 3]}}] & ``` [Answer] ### GolfScript, 112 105 characters ``` 3,21*{..+6rand<3*+)}%3/\{)\.+-1%>2<.p~<}+,,"User Computer"n/1$11<=" wins with "+\[.~22+]$1>~+" points"+ ``` Run it [online](http://golfscript.apphb.com/?c=OyIxIgoKMywyMSp7Li4rNnJhbmQ8MyorKX0lMy9ceylcListMSU%2BMjwucH48fSssLCJVc2VyCkNvbXB1dGVyIm4vMSQxMTw9IiB3aW5zIHdpdGggIitcWy5%2BMjIrXSQxPn4rIiBwb2ludHMiKw%3D%3D&run=true). The script expects the input on STDIN and then prints the outcome of the dice rolls (first column computer, second user) and the final statistics to STDOUT. [Answer] ## **Ruby 1.8, 165** ``` i,s,*d=getc,21,[4]*5<<1,[3]*5<<6,[2,5]*3 puts"#{s.times{p r=[i,i-1].map{|o|d[o%3][rand 6]};s+=r[0]<=>r[1]}>s?"Human":"Computer"} wins with #{[s/=2,21-s].max} points" ``` `getc` gets the ascii value of the input (ruby 1.8 only), which happily is congruent modulo 3 to its integer value. `s` starts out at 21, so `s.times{code}` will execute `code` 21 times and return 21. On each iteration, the loop either adds or subtracts 1 from s depending on who wins, so we can see who won by seeing whether `s` has ended up below 21. Neat so far, but then I need the clumsy expression `[s/=2,21-s].max` to extract the actual number of points. I've long wanted to do arithmetic with the return value of `<=>`, so I'm happy anyway. [Answer] ## Mathematica 234 247 **Code** ``` g@n_ := {t = RandomChoice[{{5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}}, {5, 1, 5, 1}/12 -> {{2, 3}, {2, 6}, {5, 3}, {5, 6}}, {1, 1, 5, 5}/12 -> {{1, 2}, {1, 5}, {4, 2}, {4, 5}}}[[n]], 21], Row[{If[(c = Count[t, {x_, y_} /; y > x]) > 10, "Computer ", "Player "], "wins with ", If[c > 10, c, 21 - c], " points"}]} ``` --- **Usage** > > {Player's roll, Computer's roll} > > > ``` g[1] g[2] g[3] ``` ![results](https://i.stack.imgur.com/Y0Lj3.png) --- **Explanation** `n` is the number 1, 2, or 3 that corresponds to the die of the player. Because n also determines (but does not equal) the die of the computer, we can generate all possible rolls of the dice when n=1, n=2, n=3. We can also determine their respective probabilities. Examine the data right after `RandomChoice`: > > {5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}} > > > If the player draws die 1, the only possible outcomes are the following 4 pairs `{{3, 1}, {3, 4}, {6, 1}, {6, 4}}` The respective probabilities of these pairs are `{5, 25, 1, 5}/36`, that is, `{5/36, 25/36, 1/36, 5/36}` `RandomChoice[<data>, 21]` outputs 21 rolls of the two dice. [Answer] ## C, ~~205~~ 191 ``` p;r(c){return 1+c+3*(rand()%6>2*c);}main(i,c,q,s){for(c=51-getchar();++i<23;printf("%u %u\n",q,s))q=r(c),p+=(s=r(-~c%3))<q;printf("%ser wins with %u points",p<11?"Comput":"Us",p<11?21-p:p);} ``` Reads the user's choice from stdin. [Answer] # Factor ## With includes: 388 ## Without: 300 ``` USING: arrays formatting io kernel math math.parser prettyprint random sequences ; IN: N CONSTANT: d { { 3 3 3 3 3 6 } { 2 2 2 5 5 5 } { 1 4 4 4 4 4 } } : p ( -- ) 1 read string>number [ 3 mod 1 + ] keep [ 1 - d nth ] bi@ 2array 21 iota [ drop first2 [ random ] bi@ [ 2array . ] 2keep < ] with map [ ] count [ 11 > "Comput" "Play" ? ] [ "er wins with %d points" sprintf ] bi append print ; ``` Yeah, Factor's not really the language to use when golfing, but it's nice. [Answer] # Python 182 ``` from random import* u=2+input() r=[eval("int(choice(`0x1d67e987c0e17c9`[i%3::3])),"*21)for i in(u,u-1)] U,C=map(sum,r) print r,['Us','Comput'][U<C]+'er wins with %d points'%abs(U-C) ``` [Answer] ## R 206 ``` u=scan() D=list(c(rep(3,5),6),c(2,5),c(1,rep(4,5))) S=sample U=S(D[[u]],21,T) C=S(D[[(u+1)%%3+1]],21,T) print(cbind(U,C)) W=sum(U>C) I=(W>10)+1 cat(c("Computer","User")[I],"wins with",c(21-W,W)[I],"points") ``` ]
[Question] [ Your lab needed to simulate how a particular cell evolves over time in a 2D grid space. A sample 2D grid space below shows a single cell at the centre of the grid. ``` 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ``` The cell evolution follows these rules: 1. '0' indicates no live cell 2. A positive number indicates a live cell. The number indicates its age. 3. A cell will grow from age 1 to 5 in each evolution 4. After age 5, a cell will die at the next evolution (resetting to '0') 5. If a cell has 4 or more neighbours (adjacent and diagonally), it will die due to over-crowding. 6. In each evolution, a live cell will spread to its neighbour (adjacent and diagonally) if there is no live cell there # Rule change Given an integer `n` in the input, which represents the size of the grid given, output the **next `n` evolution of cells** Extra rules: 1. The first live cell is always in the center of the grid 2. `n` must be odd so the live cell is always centered 3. The first grid of the 1 in the center is not counted as an evolution # Test case Only 1 to save space in question Input: 3 ``` 0 0 0 0 1 0 0 0 0 ``` ``` 1 1 1 1 2 1 1 1 1 ``` ``` 2 0 2 0 0 0 2 0 2 ``` ``` 3 1 3 1 1 1 3 1 3 ``` This is code-golf, so shortest bytes wins! [Answer] # JavaScript (ES6), 222 bytes This version uses the cumbersome output format mentioned in the comments. ``` n=>(v=[...Array(n)],z=~-n/2*~n,g=m=>~n--?[m.map(r=>r.join` `).join` `,...g(m.map((r,y)=>r.map((v,x)=>[t=0,..."1235678"].map(d=>(m[y+~-(d/3)]||0)[x+d%3-1]&&t++)|v++?v%=t>3||6:+!!t)))]:[])(v.map(_=>v.map(_=>+!z++))).join` ` ``` [Try it online!](https://tio.run/##PY/hboIwFIX/8xTFRO1daRXI3KK7mD1HbQYRIRppTSWNOMarM8Rs/76Te869554yl1339nipuTb5oS@w15hQh1II8Wlt1lANKrhjx/Uieul0UGKFSac538pKVNmFWkysOJmjTkkKT/DSYIiX9GmgNmjgYRqFC26DkDUuH55JGMWvq7f3iRqn@XC7kg3rOM0XMai2XYK8sXwa81DNZjVj0DrGtm6KdRK37WrNfL8GALWWCqgbl3xh8g/Mvw8Z@OvlpX1hLNUESbwhmnwgCcMHMCQRkG@PkL3RV3M@iLMpaTE8TxiZ7/QcNt5P/ws "JavaScript (Node.js) – Try It Online") Or **[187 bytes](https://tio.run/##TY/hboJAEIT/@xSLiXrbAxRIbSNdTJ@DkoaIEAx3Zw5CxFJenR7YNP33zc7sbuaStml90uW1caTKzmNOo6SItRS7rvuuddoxiYl9p8GRW/9pkHZBgqJBOs4xFrYJFUy4Ir0ypu0OKdIP0do3I@KGdlNm6fnB8/7ldZnMbmY@iLjjg8OybYBJ3@8wvvFsFThesl43nGPfcn5sV9REQd/vD9yyGkRMDnGCrJ2PfFL0B9y6mx3EMVeaSSAIQpDwRuB5E3ACH@FrAVCVdWPs3JQKjTwpWavq7FaqYJM13xNAETw66Qm1e1GlZBvYIP7ih/zPkwIO8zRcfI8/)** if a standard output is allowed (a list of matrices). ### Center cell of the matrix Given the width \$n\$ of the matrix, we define: $$z=\frac{(n-1)\times(-n-1)}{2}$$ Or as JS code: `z=~-n/2*~n` We increment \$z\$ after each visited cell while walking through the matrix from left to right and top to bottom. The center cell is reached when \$z=0\$. For instance, for \$n=5\$ we start with \$z=-12\$, leading to: $$\begin{pmatrix}-12&-11&-10&-9&-8\\ -7&-6&-5&-4&-3\\ -2&-1&0&1&2\\ 3&4&5&6&7\\ 8&9&10&11&12\end{pmatrix}$$ This is -- I think -- shorter than keeping track of \$(x,y)\$ and doing the test on them. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 62 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {(0,⍳⍵){(6|{(+/∊8⍳⍤-4×5⊃⊢)×,⍵}⌺3 3×1+⊢)⍣⍺⊢⍵}¨⊂⍵ ⍵⍴1↑⍨-⌈2÷⍨⍵*2} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=HYo7DkBAFEW3ohyGMH6xt6EhEZl4hWp6FHpEojQ7uSvxKG5ycs7VIglBO@j0tShrLWSMwVS/WqPc2QKmg5l9Z/l3NhjvzMucVfKToAV0M33p2WBaBo8HOhT6CbRFGIfUXUysg7R5AQ&f=S1Mw5jIy0FfXVedKUzBFMM0B&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Or 54 bytes as a full program with a questionable output format: ``` {(6|{(+/∊8⍳⍤-4×5⊃⊢)×,⍵}⌺3 3×1+⎕∘←)⍣⍵⊢⍵ ⍵⍴1↑⍨-⌈2÷⍨⍵*2}⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X@1hllNtYa2/qOOLo1HvZstdE0OTzd91NX8qGuRpubh6TqPerfWPurZZaxgfHi6ofajvqmPOmY8apug@ah3MVAKqApIKoBYvVsMH7VNfNS7QvdRT4fR4e1AFlBYy6gWqAdk1f80LgVjLiMDfXVddS4g2xSJbQ4A "APL (Dyalog Unicode) – Try It Online") Slightly adjusted to run on the version 17 on TIO. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 287 bytes ``` N=int(input()) K=range(N) G=[[+(i==j==N//2)for j in K]for i in K] F=lambda:print('\n'.join(' '.join(str(c)for c in r)for r in G)+'\n') F() for _ in K:G=[[-~G[i][j]%6*(0<sum(-1<I<N and-1<J<N and G[I][J]>0for J in[j-1,j,j+1]for I in[i-1,i,i+1])<5+5*(not G[i][j]))for j in K]for i in K];F() ``` [Try it online!](https://tio.run/##dY/BTsMwDIbveYpcUJ21ZSuoExoNx1XtpL5AiFDZBjhibpVlBy68eom7Xbl9@uT/tz3@hK@BHp9GP02dRgqANF4CKCV22vf0eYROiVobkwJq7bTulssH9TF46SSS3FlGvKLY6u/@9H7oN6PnquSVkns3IEEib3AOHvZzfM8ZP6NnrFXK80psQQm2b3Pphnfnv7VBa5y9Wy9gVZ0vJ8iLqqk62dMhUnslWZvGmta@rDjfxrxxeZG5zKXFfGfDCqPCDKNSVZmWC6AhyFu/@uez53jUNJV/ "Python 3.8 (pre-release) – Try It Online") This is the version with a nice, tidy output method. ## Explanation Take integer as input (call it N) representing the size of the grid. Make a variable for its range, to save bytes. (The range is used quite a few times.) Set up the grid by placing 1 in the center (the row and column are N//2) and 0 in all other places. Make a function to print the grid. Print the grid. Change the grid N times, by changing the element at i, j to `-~G[i][j]%6` (one plus the existing one, modulo 6: the modulo 6 ensures that 5 becomes 6%6 = 0) if there is at least one live element in its neighborhood (which includes itself; if no live elements are in the area, it cannot come alive) and at most 5 live elements if that element is itself live (this is the part which kills overcrowded elements), and 10 live elements if that element is dead (it doesn't matter how overcrowded the element is, because if there is at least one live element around it, which is not itself as it is dead, it comes alive regardless). If those conditions are not satisfied, set it to zero. Then print the grid at each iteration. ## "the first grid is not an evolution" # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 270 bytes ``` N=int(input()) K=range(N) G=[[+(i==j==N//2)for j in K]for i in K] for _ in K:G=[[-~G[i][j]%6*(0<sum(-1<I<N and-1<J<N and G[I][J]>0for J in[j-1,j,j+1]for I in[i-1,i,i+1])<5+5*(not G[i][j]))for j in K]for i in K];print('\n'.join(' '.join(str(c)for c in r)for r in G)+'\n') ``` [Try it online!](https://tio.run/##dc/BboMwDAbgO0@RS4VTYIVOVNNGdkWAxAtkUYVYtznSDArpYZe9OsPAdbdPv/xb9vjjvwZ6fBrdPLcKyQPSePcgZdAo19HnDVoZlErrCFApq1R7Op3lx@CEFUiiMUzcGLCvq5@5kvyWGo225nA5QlpM929IsqIqWtHR@6J6kyh1ZXRtXlPu10tf2ySLbWyjbF1fcYRLhDEukSzyKD8CDV7s@@U/B72Mjl8K3yh8sAMShGLH5B30a6vnUbfSMUsZ8byc5/wP "Python 3.8 (pre-release) – Try It Online") At present, I am not sure if the first grid is an evolution, but just in case, I have provided both versions. (The statement that the first grid is not an evolution conflicts with the test case output.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~55~~ ~~54~~ 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` δ‚·<QPIƒD»,¶?0δ.ø¬0*šĆ2Fø€ü3}εε˜DÅsD>I>%Š_iOĀ*ëĀO5‹* ``` Formats by joining each row with a space-delimiter and then all lines with a newline-delimiter. The output can therefore be a bit wonky if it contains any multi-digit integers (for inputs \$n\geq17\$). The `D»,¶?` could have been `=` (-4 bytes) without the strict output format, by just outputting the matrices as is (without popping). [Try it online](https://tio.run/##AVkApv9vc2FiaWX//8604oCawrc8UVBJxpJEwrsswrY/MM60LsO4wqwwKsWhxIYyRsO44oKsw7wzfc61zrXLnETDhXNEPkk@JcWgX2lPxIAqw6vEgE814oC5Kv//NQ) or [verify all test cases below 10](https://tio.run/##AYEAfv9vc2FiaWX/VMOFw4l2IklucHV0OiBuPSI/eSwKIk91dHB1dDogIix5w5BVRCL/zrTigJrCtzxRUFjGkkTCuyzCtj8wzrQuw7jCrDAqxaHEhjJGw7jigqzDvDN9zrXOtcucRMOFc0Q@WD4lxaBfaU/EgCrDq8SATzXigLkq/yIuVv8). **Explanation:** Step 1: Using the input \$n\$, create an \$n\times n\$ matrix of \$0\$s with a \$1\$ in the center: ``` δ # Apply double-vectorized: # (which implicitly converts the implicit input-integer to # the range [1,input] first, used twice) ‚ # Pair them together · # Double each inner integer < # Decrease each by 1 Q # Check for each value if it's equal to the (implicit) input P # Get the product of each inner pair ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f//3JZHDbMObbcJDPj/3xQA) Step 2: Loop \$n+1\$ amount of times, and pretty-print the matrix at the start of each iteration: ``` Iƒ # Loop the input+1 amount of times: D # Duplicate the current matrix » # Join each inner list by spaces, # and then each string by newlines , # Pop and print it with trailing newline ¶? # Print an additional empty line ``` [Try steps 1 & 2 online.](https://tio.run/##AR8A4P9vc2FiaWX//8604oCawrc8UVBJxpJEwrsswrY///81) Step 3a: Surround the entire matrix with a ring of 0s: ``` δ # Map over each row: 0 .ø # Surround it with a leading/trailing 0 ¬ # Push the first row (without popping the matrix) 0* # Convert all its values to 0 š # Prepend this list to the matrix Ć # Enclose; append its first row ``` Step 3b: And then get all overlapping 3x3 blocks. Each of these 3x3 blocks will have the current value at the center, and its 8 neighbors around it. ``` 2F # Loop 2 times: ø # Zip/transpose; swapping rows/columns € # Map over each row: ü3 # Create overlapping triplets of this row } # Close the loop ``` [Try steps 1 & 3 online.](https://tio.run/##AS4A0f9vc2FiaWX//8604oCawrc8UVAwzrQuw7jCrDAqxaHEhjJGw7jigqzDvDN9//81) Step 4: Based on these 3x3 blocks, determine the next value for the cell: ``` εε # Map over each inner 3x3 block: ˜ # Flatten it to a single list of 9 values D # Duplicate this list Ås # Pop and push the middle cell value D # Duplicate this middle value > # Increase it by 1 I>% # Modulo the (input+1) Š # Triple-swap list,middle,middle+1 to middle+1,list,middle _i # If the middle cell is 0: O # Sum its neighbors together Ā # Check if this is not 0 (0 if 0; 1 otherwise) * # Multiply this by the middle+1 ë # Else: Ā # Check for each value that it's NOT 0 O # Sum to get the amount of filled cells, including itself 5‹ # Check if this is smaller than 5, # so there are not 4 or more filled neighbors * # Multiply this by the middle+1 ``` [Answer] # [J](http://jsoftware.com/), 62 bytes ``` <@>:_&(](-~&*+(5>])*[+0<[)[:+/(>,{;~i:1)|.!.0*@])[:*/~<.@-:=i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bRzsrOLVNGI1dOvUtLQ1TO1iNbWitQ1sojWjrbT1Nex0qq3rMq0MNWv0FPUMtBxigcJa@nU2eg66VraZev81uVKTM/IV0hRMIQx1XV1ddZiY8X8A "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 214 bytes ``` E=enumerate n=input() g=eval(`[[0]*n]*n`) g[n/2][n/2]=1 exec'print("%d "*n+"\\n")*n%tuple(sum(g,[]));g=[[(0<sum(e>0for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2])<5+4*0**v)*-~v%6for x,v in E(r)]for y,r in E(g)];'*-~n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY9NasMwEEb3PoUxiOjHoa7bhpBE3eUUiiChnaiGZOKokpE2vkg37qL0RoXeplZcGIb5Hm8W38d3G93bBeth-PLuOF_-_mwloD-DPTjIUDbYekdZZiR0hxPdK1VpjuPsR6bwrta3Je8zCPAya22DjhbkNS84imK3w4JxJM63J6Dv_kxNqTRjayOVotUmEXiujhebX_MGc6OiiKSPqyhqnSgkelVBBNKHVRgp2zyJR15x3jE-7zuySFoouyRuqWW3t1jaKRum17PRw6ndf8nh82E6_gA) Because of the fixed output format switching to Python 3 could actually save a few bytes here: [ATO](https://ato.pxeger.com/run?1=LY87DsIwEET7nCINwnaCYr5CVswhaI2FEDImBZvEJChuchGaUMB1qLkNNqZZjWbfjnbur8o25xKG4dk2p8n6895ycwCtEDBeQIMKqNoGYYwjzQUQQeWpNPE-LiDeykgLyLKZDJNPI9WpIxp7wjiC6FRIVhmfQwzegYsQiObX9oLUhnqs9kFa2MSOestsMvvFK-cKmpJaio51yVzifJksCCUE3Rh3uPMlxmTS30Yrf9CFf7y0Qe5g7NaAQ61_u-ExD-IL) The most interesting part of this program is the following expression: ``` (0<sum(e>0for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2])<5+4*0**v)*-~v%6 ``` Given the previous state in `g`, the indices of a cell `y, x` and the value of that cell `v`, this generates the next state of that cell. To select three rows of `g` centered on `y` the slice `g[y-1:y+2]`. This works if `y` is not on the boundaries of `g` or if `y == n-1`. For `y == 0` the slice would start at the end of `g`, which is not what we want. To adjust for that we can use `y-(y>0)` instead, but `y+y%~y` is a shorter expression that achieves the same. In conclusion `[e for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2]]` lists all values in a truncated 3x3 block centered on `y, x`. We then count the non-zero values and check for overpopulation if `v>0`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 74 bytes ``` Nθ≔EθEθ⁰η§≔§η⊘θ⊘θ¹F⊕θ«Eη⪫κωFθFθ«Jλκ§≔§ηκλ∧›5KK⎇ΣKK∧›⁴LΦKMΣμ⊕KK‹0⌈KM»UE¹D⎚D ``` [Try it online!](https://tio.run/##VVBNT4QwED3Dr2g4DUlNNNGD2ROR1bBxzSbuH@jCuDT0A0qrGLO/HVtgDc5lOm/em3nTsmam1EyMY6FaZ9@cPKGBLt3EWd/zs4I9a6GjZEmZqmDbOSZ64JSIlJKlyrU7CayAeyjH0qBEZX3dpSEoqf3ED20IFOpfk/zE0cFwZadFNSU7zRU0lHx52SaOJk2Xkmv29GjnZHvUIChpAiWanWa2UBUOcM11aHuPs@kXg8z6y5KHhJIDYgPB1RGNYuYb3p2EP3BNv6fkFdXZ1vDMRQACa6@1QfDMIJPzfeuzlklp0PY9JLdJ@L@By2XLop/C@7/E0Xaw6LfehTL310F4PAlkBtbQZRwfx5tP8Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔EθEθ⁰η§≔§η⊘θ⊘θ¹ ``` Create an `n×n` matrix whose centre element is `1`. ``` F⊕θ« ``` Loop `n+1` times, because we output the position first. ``` Eη⪫κω ``` Output the current position to the canvas. ``` FθFθ«Jλκ ``` Loop over each cell. ``` §≔§ηκλ∧›5KK⎇ΣKK∧›⁴LΦKMΣμ⊕KK‹0⌈KM ``` If the current cell is less than `5`, then if it is a `0` then set it to `1` if it has any neighbours, otherwise increment it if it has fewer than `4` neighbours. Otherwise, set it to `0`. ``` »UE¹D⎚D ``` Output the canvas neatly. (`D⎚` would work but the output would be much less readable.) ]
[Question] [ The string ``` abaaba ``` Is a palindrome, meaning it doesn't change when it's reversed. However we can split it in half to make two palindromes ``` aba aba ``` We could also split it up this way: ``` a baab a ``` And all three of those are palindromes. In fact there are only two ways to split the string into smaller strings such that *none* of them are palindromes: ``` abaa ba ab aaba ``` Any other way we split this there is going to be at least one palidrome. So we will say that this string has a **palindromy number** of 2. More generally a string's palindromy number is the number of ways to partition it into contiguous substrings such that none are a palindrome. Your task will be to take a string as input and determine its palindromy number. Your answer must work correctly for inputs containing lowercase letters (`a`-`z`) along with any characters used in the source code of your program. ## Scoring Your answer will be scored by it's own palindromy number. With a lower score being the goal. In the case of ties the tie breaker is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") This scoring does mean if you solve this in brainfuck you can get a lenguage answer with a primary score of 0. So if you are a lenguage enthusiast this is just code-golf. [Here's a program to score your code](https://tio.run/##JY4xb4QwDIX3/IonxJAIDqkrFFSp800dKUJBBEgbCAqhB1X/OzXcYMv@7PfsQS7fypjj0ONsnce7nbyzJrnbSbaMddjwR5HncOpHuUWdDcqKqPWDcg9NiEC5VRVjPbhMmzdep7UQhHkTo5SVQIpRzuDdlWVKQ96jESBFffkxtl7O58EoAm8t7cXnyusNPbYM@qw6yAxfZ7Wiyegnv7oJISESaYhjyYPBjtbYfg/YKPWUt5YBRnnM0vmFTqxYiMxOT56URk29H55DwvTgvQb/5Fu8i1sxr/7DO74M9oEtioIUgSiKp3YX4a@ey5ckqULyPP4B "Haskell – Try It Online"). ## Test cases ``` a -> 0 aba -> 0 ababa -> 0 abababa -> 0 ffffffff -> 0 xyz -> 1 abaa -> 1 abaaa -> 1 abaaaaa -> 1 ooooooops -> 1 kvxb -> 2 kayak -> 2 abaaba -> 2 abaaaba -> 2 avakava -> 2 aaaaakykaaaaa -> 2 abaaaaba -> 3 ababab -> 4 abababab -> 8 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 3, 755962277730462996760664 bytes ``` ...‘‘‘‘ṃØJV ``` [Try it online!](https://tio.run/##y0rNyan8/9/c1NTSzMjI3Nzc2MDEzMjS0szczMDMzODhzubDM7zC/hsZHFr0qGlN5P9ErsQkMIaRQDoNCrgqKqtAgmAZGAmk8yGgoJgru6wiiSs7sTIxGyyZBFUDossSs4GYC6wjuzIbohNiAtwqmI1JXI8aZuBBUFcDAA "Jelly – Try It Online") -5 score and +tons of bytes thanks to @ovs's idea. `...‘‘‘‘` part contains exactly 755962277730462996760660 copies of `‘` character, whose length encodes the following program in base 256: # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ɠŒṖŒḂ€€§¬S ``` [Try it online!](https://tio.run/##y0rNyan8///kgqOTHu6cBiR2ND1qWgNEh5YfWhP838jg0CIgJ/J/IldiEhjDSCCdBgVcFZVVIEGwDIwE0vkQUFDMlV1WkcSVnViZmA2WTIKqAdFlidlAzAXWkV2ZDdEJMQFuFczGJK5HDTPwoIc7mw/P8AoDAA "Jelly – Try It Online") The main code is a minor variation of [Dude's answer](https://codegolf.stackexchange.com/a/233917/78410) (use of alternative built-ins, and input method changed to "a single line from stdin"), so here goes an explanation for the encoding part instead: ``` ...‘‘‘‘ṃØJV Main link (niladic). ...‘‘‘‘ Increment from zero 755..whatever..660 times ṃØJ Base decompress into Jelly's code page V Eval as a nilad (input is handled in the code itself) ``` The 3 non-palindromic partitions of `...aaaabcde` are: ``` ...aaaabcde ...aaaabc|de ...aaaab|cde ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score ~~14~~ 12, 9 bytes ``` ŒṖŒḂ€€§¬§ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7pwGJHU2PmtYA0aHlh4D4/8Mdmx7uWHS4nevh7i2H24Hikf//Jyro2ikYcCUmIRgoTBgnDQogvIrKKhDDEKQmEcFCZsI4@RBQUAzhZpdVJIFYRlzZiZWJ2RAmSAPEIggbwSlLzAZiKAcEsiuz4YZDFUNVG0MdDGKbwBwP5llwYQ8QsIuMAA "Jelly – Try It Online") I thought this would be more of a baseline contender, but any modification I make to it to try to make it more palindromy only increases it instead. So, this is just the straight forward implementation. -2 points thanks to [xigoi](https://codegolf.stackexchange.com/users/98955/xigoi) ## How it works ``` ŒṖŒḂ€€§¬§ - Main link. Takes a string S on the left ŒṖ - Get all partitions of S € - Over each partition: € - Over each substring in the partition: ŒḂ - Is the substring a palindrome? § - Get the sum of each (counting how many substrings are palindromic) ¬ - Logical not. Map zeros to one, everything else to zero § - Sum, counting the zeros ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 18 (9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` .œεεÂÊ]PO ``` [Try it online](https://tio.run/##yy9OTMpM/f9f7@jkc1vPbT3cdLgrNsD////EpEQgAgA) or [verify all test cases, including itself](https://tio.run/##yy9OTMpM/a/0X@/o5HNbz2093HS4KzbA/7/SoW0X9hxa6Vl8dGFZpb2SwqO2SQpK9pWH1umF6fjFZx7aZv8/WilRSUdBKTEJRiExIMw0KACxKyqroLIwVUgMCDMfAgqKQZzssookMJ1YmZgNU5iE0AJlliVmAzGYCQLZldlw4yAmIzsKyXlJSrEA). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string ε # Map over each partition: ε # Map over each part in this partition: # Check that it's NOT a palindrome by:  # Bifurcating it (short for Duplicate & Reverse copy) Ê # And check that this reversed copy is not equal to the original string ] # Close both nested maps P # Check for each partition whether no part was a palindrome O # Sum to get the amount of truthy values # (after which the result is output implicitly) ``` I don't think this score nor byte-count can be improved, but I'd like to be proven wrong. Increasing the program size overall increases the score, otherwise `Ê]PO` to `Q]O_O` would have been a decent change with the palindrome `O_O` (this scores 22 at 10 bytes btw). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 25 bytes, score 46368 ``` LṄvṖ⁽JḭUƛvɾ:?f$•;'ƛḂ≠;A;L ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=L%E1%B9%84v%E1%B9%96%E2%81%BDJ%E1%B8%ADU%C6%9Bv%C9%BE%3A%3Ff%24%E2%80%A2%3B%27%C6%9B%E1%B8%82%E2%89%A0%3BA%3BL&inputs=abaaba&header=&footer=) -3 thanks to Aaron Miller. A big mess. Part of the code [shamelessly stolen from Lyxal](https://codegolf.stackexchange.com/a/233186/100664). ``` L # Length ṄvṖ # All permutations of partitions ⁽Jḭ # Flatten by 1 level U # Uniquify ƛ ; # Foreach vɾ:?f$• # Mold input to those pieces (see above link) ' ;L # Number of values where ƛḂ≠;A # All aren't palindromes. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), score 21 (9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)) ``` Æ₧ⁿ+Ü█>la ``` [Run and debug it](https://staxlang.xyz/#p=929efc2b9adb3e6c61&i=%C3%86%E2%82%A7%E2%81%BF%2B%C3%9C%E2%96%88%3Ela%0A%3A%21%7B%7Bcr%3Df%21f%25%0Aa%0Aaba%0Aababa%0Aabababa%0Affffffff%0Axyz%0Aabaa%0Aabaaa%0Aabaaaaa%0Aooooooops%0Akvxb%0Akayak%0Aabaaba%0Aabaaaba%0Aavakava%0Aaaaaakykaaaaa%0Aabaaaaba%0Aababab%0Aabababab%0A&m=2) the packed representation scores lesser, as shown in the tests. Despite the existence of `f!f` and `{{` in the unpacked version, the number of characters simply doubles the score. ]
[Question] [ The word "levencycle" is inspired by [cyclic levenquine](https://codegolf.stackexchange.com/q/116189/78410) challenge. ## Definitions A **1-dup permutation** of order \$n\$ is some permutation of \$1, \cdots, n\$ plus one duplicate number in the range. For example, 1-dup permutations of order 3 include `1, 3, 2, 2` and `3, 2, 1, 3`. There are 36 distinct 1-dup permutations of order 3, and \$\frac{(n+1)!\cdot n}{2}\$ of those of order \$n\$ in general. A **Hamiltonian levencycle** combines the concept of Hamiltonian cycle (a cycle going through all vertices in a given graph) and Levenstein distance (minimal edit distance between two strings). Informally, it is a cycle going through all possible sequences by changing only one number at once. For example, the following is a Hamiltonian levencycle of order 2: (the connection from the last to the start is implied) ``` (1, 1, 2) -> (1, 2, 2) -> (1, 2, 1) -> (2, 2, 1) -> (2, 1, 1) -> (2, 1, 2) ``` For order 3, found by automated search using Z3: ``` (1, 1, 2, 3) -> (1, 2, 2, 3) -> (1, 2, 1, 3) -> (1, 2, 3, 3) -> (1, 2, 3, 2) -> (1, 3, 3, 2) -> (1, 1, 3, 2) -> (3, 1, 3, 2) -> (3, 1, 2, 2) -> (3, 1, 2, 1) -> (3, 1, 2, 3) -> (2, 1, 2, 3) -> (2, 1, 1, 3) -> (2, 1, 3, 3) -> (2, 1, 3, 2) -> (2, 1, 3, 1) -> (2, 2, 3, 1) -> (1, 2, 3, 1) -> (3, 2, 3, 1) -> (3, 2, 1, 1) -> (3, 2, 2, 1) -> (3, 3, 2, 1) -> (1, 3, 2, 1) -> (2, 3, 2, 1) -> (2, 3, 3, 1) -> (2, 3, 1, 1) -> (2, 3, 1, 2) -> (2, 3, 1, 3) -> (2, 2, 1, 3) -> (3, 2, 1, 3) -> (3, 2, 1, 2) -> (3, 1, 1, 2) -> (3, 3, 1, 2) -> (1, 3, 1, 2) -> (1, 3, 2, 2) -> (1, 3, 2, 3) ``` ## Challenge Given an integer \$n \ge 2\$, output a Hamiltonian levencycle of 1-dup permutations of order \$n\$. The output format is flexible. Assume that such a cycle exists; for values of \$n\$ where it does not exist, the behavior is undefined (you may do whatever you want). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 110 bytes ``` ñ-ị$X⁸ṣU2¦jɗ 0ịị®ḟ Œ!⁸œṖþẎṣ€Ẏ¥þ⁸Q€;@"Ẏ¥þ@";þ`ạ/Þ€;"Q¥U$ƊẎḅQ¥€⁸ṢFỤ’:‘sʋ1ịLƊƲ©ṛ1ç`X;@ṛÑ¥¹?Ɗ,®Ẉ⁻/Ɗ¿Ñç0ċ1¬Ɗ¿ƲịḢ€Ɗḃ ``` [Try it online!](https://tio.run/##y0rNyan8///wRt2Hu7tVIh417ni4c3Go0aFlWSencxkAxYDo0LqHO@ZzHZ2kCJQ9OvnhzmmH9z3c1QdU96hpDZBxaOnhfUCZQCDP2kEJKuCgZH14X8LDXQv1D88DSSgFHloaqnKsC6RxRyuQAxQEW7bI7eHuJY8aZlo9aphRfKrbEGifz7GuY5sOrXy4c7bh4eUJEdYOQNbhiYeWHtppf6xLB@iaXR2PGnfrH@s6tP/wxMPLDY50Gx5aA@Id2wRy8I5FQLOBNu1o/m94ZD@X9aOGOQq6dgqPGuZaGx/Z/3DnPhWuw@1AJZH//5sCAA "Jelly – Try It Online") A full program that takes an integer and returns a list of lists of integers. Not written primarily to be compact but for efficiency and speed. Can solve the problem for n=5 in around 5 seconds on TIO and gets most of the way for n=6 within 60 seconds. This uses a modified version of the algorithm described in the post linked by Jonah. However, that lost only covered a Hamiltonian path and so there’s an additional bit to ensure a cycle is found. The code to find the Levenstein neighbours is also longer than minimal so that it completes in time - a more naive but shorter solution for that bit still completes within a few seconds for n=5 but rapidly becomes unworkable for bigger n. Full explanation to follow. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 172 bytes ``` (DeleteDuplicates[Flatten[Table[Permutations[Join[{i},Range[#]]],{i,Range[#]}],1]]//FindHamiltonianPath[AdjacencyGraph[Table[If[1==EditDistance[i,j],1,0],{i,#},{j,#}]]]&)&; ``` [Try it online!](https://tio.run/##PY07C8JAEIR7/4YgCge@SkkhJL4qEbtli/WyMRsuGzFrISG/PR4iNsPMMHxTk5Vck4mnoUiGacqBjdPXI8TGuIVdIDNWuNItMJz5Wb8szhtt4dSIQie9u5DeGcaI6Dr5px7dEnE@34nmB6olWKNCeo6PsM0r8qz@vX/So/zBjwUskyTLxVJpjdQziKsixS2@4HHvuipq/JnMJpsh82UDBawQRz@7Rhw@ "Wolfram Language (Mathematica) – Try It Online") This is my first Wolfram golf, and as a golf I think it's pretty terrible, but I'm posting because it calculates n=3 almost instantly, which seems to support my conjecture from the other answer that there is a more efficient (possibly probabilistic) algorithm for this. [These docs](https://mathworld.wolfram.com/HamiltonianPath.html) suggest this as well, though don't say which of the algorithms discussed powers `FindHamiltonianPath`. `n=4` times out on TIO, and I haven't tested it longer than a minute, so I'm not sure how long its execution time would be. [Answer] # [J](http://jsoftware.com/), 76 bytes ``` 0{[:(#~([:*/2(1=1#.*@|@-/)\],{.)"2)@(i.@!@#A."2])@~.[:,/i.@!@>:A."1,"0 1~@i. ``` [Try it online!](https://tio.run/##dY9PS8QwEMXv/RTPFNxkaad/9pbdLlFBEMSD11qllIStxGbpFkEq@eo1qwdPe5h3eG8e85v3hdHKoJJYIUEOGSYl3D0/3i/5XEsee17LdVbyoipiWqtvlWbipUlmEqwUivekrlR8Q6xshPJUyyT7tfYyeEXCchRe9bSI6OmWMGrbTv2ntl/4cKOGNqbv9DChPR5H13YH8NPUW4vBTeisO2kYN2KoNn/9tzIwgeMsOyUfCAh4W95gF46rhMUhmP0sRUqNuKa9eJWtREhzEVb/fxCsyDyAMzMuQUeR7g4OBuXyAw "J – Try It Online") Brute force, not a great golf. Should work in theory but too slow to test on anything above 2. General Hamiltonian circuit is NP, but I'm wondering if there's something special about the structure of this problem that allows a clever, much faster algorithm? I had another approach that's 2^n instead of n! but that's still not close to good enough. Perhaps this? <https://stackoverflow.com/questions/1987183/randomized-algorithm-for-finding-hamiltonian-path-in-a-directed-graph> Maybe I'll give it a shot tomorrow... [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 21 bytes ``` R;€`Œ!€ẎQŒ!ṙ1nƊ§ỊẠƲƇḢ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJSO+KCrGDFkiHigqzhuo5RxZIh4bmZMW7GisKn4buK4bqgxrLGh+G4oiIsIiIsIiIsWyIyIl1d) -1 byte thanks to Nick Kennedy, then fixed for +1 thanks to Nick Kennedy Full explanation to come if I remember. ]
[Question] [ # Convert NFA to DFA as quickly as possible. **Input** Your input will be an [NFA](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton). In order to be able to test your code, it needs to be able to handle an NFA in the following format. This is taken directly from [GAP](https://www.gap-system.org/Manuals/pkg/automata-1.14/doc/chap2.html#X821C3B3687B1F2FF) (and slightly simplified). ``` Automaton( Type, Size, Alphabet, TransitionTable, Initial, Accepting ) ``` For the input, Type will always be "nondet". 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 lists of non-negative integers not greater than the size of the automaton are also allowed. Initial and Accepting are, respectively, the lists of initial and accepting states. Example input: ``` Automaton("nondet", 4, 2, [[[], [2], [3], [1, 2, 3, 4], [2, 4]], [[], [1, 3, 4], [1], [2, 4]]], [1], [2, 3]) ``` This is slightly easier to read as a transition table. ``` | 1 2 3 4 -------------------------------------------------- a | [ 2 ] [ 1, 2, 3, 4 ] [ 2, 4 ] b | [ 1, 3, 4 ] [ 1 ] [ 2, 4 ] Initial state: [ 1 ] Accepting states: [ 2, 3 ] ``` **Output** Your output must be a [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) that is **equivalent** to the input NFA. There is no need for your DFA to be minimal. For the output, 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. The states should be labelled by consecutive integers. Initial and Accepting are, respectively, the lists of initial and accepting states. In the case of the example above, this would be: ``` Automaton("det", 2, 2, [[2, 2], [2, 2]], [1], []) ``` As a transition table this is: ``` | 1 2 ----------- a | 2 2 b | 2 2 Initial state: [ 1 ] Accepting state: [ ] ``` (It is now clear this is a DFA that will not accept any input strings.) # Test cases: 1. Input: ``` Automaton("nondet",2,4,[[[1], [2]], [[2], []], [[2], []] , [[1], [2]]],[1],[1, 2]) ``` As a transition matrix: ``` | 1 2 ------------------- a | [ 1 ] [ 2 ] b | [ 2 ] c | [ 2 ] d | [ 1 ] [ 2 ] Initial state: [ 1 ] Accepting states: [ 1, 2 ] ``` Here is the diagram of the NFA. [![enter image description here](https://i.stack.imgur.com/fzm1q.png)](https://i.stack.imgur.com/fzm1q.png) Output: ``` Automaton("det",3, 4,[[1, 2, 3], [2, 3, 3], [2, 3, 3], [1, 2, 3]], [1],[1, 2]) ``` As a transition matrix: ``` | 1 2 3 -------------- a | 1 2 3 b | 2 3 3 c | 2 3 3 d | 1 2 3 Initial state: [ 1 ] Accepting states: [ 1, 2 ] ``` Here is the diagram of the DFA. [![enter image description here](https://i.stack.imgur.com/S1uMn.png)](https://i.stack.imgur.com/S1uMn.png) 2. Input: ``` Automaton("nondet",7,4,[[[1, 3, 4, 5], [2], [3], [3, 4], [3, 5], [], []], [[2, 3, 4, 7], [3], [], [], [3, 7], [3, 4], []], [[2, 3, 5, 6], [3], [], [3, 6], [], [], [3, 5]], [[1, 3, 6, 7], [2], [3], [], [], [3, 6], [3, 7]]],[1],[1, 2, 3, 4, 5, 6, 7]) ``` Output: ``` 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]) ``` 3. Input: ``` Automaton("nondet",12, 4,[[[1, 3, 5, 6], [2, 4, 7, 8], [3], [6], [3, 5], [3, 6], [4, 7], [4, 8], [4, 7], [4, 8], [], []], [[2, 3, 5, 10], [3, 4, 7, 12], [6], [], [4, 7], [3, 10], [], [4, 12], [3, 5], [4, 12], [4, 7], []], [[2, 3, 6, 9], [3, 4, 8, 11], [6], [], [3, 9], [4, 8], [4, 11], [], [4, 11], [3, 6], [], [4, 8 ]], [[1, 3, 9, 10], [2, 4, 11, 12], [3], [6], [4, 11], [4, 12], [], [], [3, 9], [3, 10], [4, 11], [4, 12]]],[1],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) ``` Output: ``` Automaton("det",39,4,[ [ 1, 19, 8, 5, 10, 10, 9, 25, 10, 10, 25, 10, 13, 35, 15, 20, 15, 19, 19, 21, 21, 10, 13, 19, 25, 25, 25, 36, 35, 10, 35, 35, 10, 10, 35, 36, 25, 19, 25 ], [ 1, 23, 1, 3, 6, 39, 39, 7, 39, 12, 8, 12, 32, 23, 21, 36, 16, 36, 32, 36, 32, 12, 32, 13, 22, 29, 32, 23, 39, 32, 39, 12, 32, 31, 12, 22, 22, 23, 7 ], [ 1, 30, 4, 1, 4, 10, 25, 4, 8, 5, 5, 10, 14, 34, 2, 14, 38, 30, 30, 14, 14, 10, 14, 30, 5, 4, 5, 34, 27, 5, 30, 30, 10, 4, 34, 34, 5, 30, 4 ], [ 1, 2, 39, 8, 39, 12, 7, 3, 25, 37, 37, 12, 27, 28, 15, 18, 15, 19, 19, 19, 19, 6, 33, 2, 11, 26, 27, 28, 22, 27, 12, 12, 33, 26, 37, 37, 37, 24, 39 ] ],[ 17 ],[ 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 ]) ``` 4. Input: ``` Automaton("nondet",25,4,[[[1, 3, 6, 7], [2, 4, 8, 9], [3, 5, 10, 11], [4], [5], [3, 5, 6, 10, 18], [3, 5, 7, 11, 19], [4, 8], [4, 9], [5, 10], [5, 11], [4, 5, 8, 10, 22], [4, 5, 9, 11, 23], [5, 10], [5, 11], [], [], [5, 10, 18], [5, 11, 19], [5, 10, 22], [5, 11, 23], [], [], [], []], [[2, 3, 6, 13], [3, 4, 8, 15], [4, 5, 10, 17], [5], [], [4, 5, 8, 10, 18], [3, 5, 13, 17, 21], [5, 10], [4, 15], [], [5, 17], [3, 5, 6, 10, 22], [4, 5, 15, 17, 25], [4, 8], [5, 17], [5, 10], [], [], [5, 17, 21], [], [5, 17, 25], [5, 10, 18], [], [5, 10, 22], []], [[2, 3, 7, 12], [3, 4, 9, 14], [4, 5, 11, 16], [5], [], [3, 5, 12, 16, 20], [4, 5, 9, 11, 19], [4, 14], [5, 11], [5, 16], [], [4, 5, 14, 16, 24], [3, 5, 7, 11, 23], [5, 16], [4, 9], [], [5, 11], [5, 16, 20], [], [5, 16, 24], [], [], [5, 11, 19], [], [5, 11, 23]], [[1, 3, 12, 13], [2, 4, 14, 15], [3, 5, 16, 17], [4], [5], [4, 5, 14, 16, 20], [4, 5, 15, 17, 21], [5, 16], [5, 17], [], [], [3, 5, 12, 16, 24], [3, 5, 13, 17, 25], [4, 14], [4, 15], [5, 16], [5, 17], [], [], [], [], [5, 16, 20], [5, 17, 21], [5, 16, 24], [5, 17, 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 ]) ``` 5. Input: ``` Automaton("nondet",38,4,[[[1, 3, 7, 8], [2, 4, 9, 10], [3, 5, 11, 12], [4, 6, 13, 14], [7], [8], [3, 5, 7, 11, 23], [3, 5, 8, 12, 24], [4, 6, 9, 13, 25], [4, 6, 10, 14, 26], [5, 11], [5, 12], [6, 13], [6, 14], [4, 5, 9, 11, 31], [4, 5, 10, 12, 32], [5, 6, 11, 13, 33], [5, 6, 12, 14, 34], [6, 13], [6, 14], [], [], [5, 11, 23], [5, 12, 24], [6, 13, 25], [6, 14, 26], [5, 11, 31], [5, 12, 32], [6, 13, 33], [6, 14, 34], [6, 13, 25], [6, 14, 26], [], [], [6, 13, 33], [6, 14, 34], [], []], [[2, 3, 7, 16], [3, 4, 9, 18], [4, 5, 11, 20], [5, 6, 13, 22], [8], [], [4, 5, 9, 11, 23], [3, 5, 16, 20, 28], [5, 6, 11, 13, 25], [4, 6, 18, 22, 30], [6, 13], [5, 20], [], [6, 22], [3, 5, 7, 11, 31], [4, 5, 18, 20, 36], [4, 6, 9, 13, 33], [5, 6, 20, 22, 38], [5, 11], [6, 22], [6, 13], [], [6, 13, 25], [5, 20, 28], [], [6, 22, 30], [6, 13, 33], [5, 20, 36], [], [6, 22, 38], [5, 11, 23], [6, 22, 30], [6, 13, 25], [], [5, 11, 31], [6, 22, 38], [6, 13, 33], []], [[2, 3, 8, 15], [3, 4, 10, 17], [4, 5, 12, 19], [5, 6, 14, 21], [8], [], [3, 5, 15, 19, 27], [4, 5, 10, 12, 24], [4, 6, 17, 21, 29], [5, 6, 12, 14, 26], [5, 19], [6, 14], [6, 21], [], [4, 5, 17, 19, 35], [3, 5, 8, 12, 32], [5, 6, 19, 21, 37], [4, 6, 10, 14, 34], [6, 21], [5, 12], [], [6, 14], [5, 19, 27], [6, 14, 26], [6, 21, 29], [], [5, 19, 35], [6, 14, 34], [6, 21, 37], [], [6, 21, 29], [5, 12, 24], [], [6, 14, 26 ], [6, 21, 37], [5, 12, 32], [], [6, 14, 34]], [[1, 3, 15, 16], [2, 4, 17, 18], [3, 5, 19, 20], [4, 6, 21, 22], [7], [8], [ 4, 5, 17, 19, 27], [4, 5, 18, 20, 28], [5, 6, 19, 21, 29], [5, 6, 20, 22, 30], [6, 21], [6, 22], [], [], [3, 5, 15, 19, 35], [3, 5, 16, 20, 36], [4, 6, 17, 21, 37], [4, 6, 18, 22, 38], [5, 19], [5, 20], [6, 21], [6, 22], [6, 21, 29], [6, 22, 30], [], [], [6, 21, 37], [6, 22, 38], [], [], [5, 19, 27], [5, 20, 28], [6, 21, 29], [6, 22, 30], [5, 19, 35], [5, 20, 36], [6, 21, 37], [6, 22, 38]]],[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]) ``` 6. Input: ``` Automaton("nondet",67,4,[[[1, 3, 8, 9], [2, 4, 10, 11], [3, 5, 12, 13], [4, 6, 14, 15], [5, 7, 16, 17], [8], [8], [3, 5, 8, 12, 28], [3, 5, 9, 13, 29], [4, 6, 10, 14, 30], [4, 6, 11, 15, 31], [5, 7, 12, 16, 32], [5, 7, 13, 17, 33], [6, 14], [6, 15], [ 7, 16], [7, 17], [4, 5, 10, 12, 40], [4, 5, 11, 13, 41], [5, 6, 12, 14, 42], [5, 6, 13, 15, 43], [6, 7, 14, 16, 44], [6, 7, 15, 17, 45], [7, 16], [7, 17], [], [], [5, 7, 12, 16, 28, 32, 52], [5, 7, 13, 17, 29, 33, 53], [6, 14, 30], [6, 15, 31], [7, 16, 32], [7, 17, 33], [5, 7, 12, 16, 40, 44, 56], [5, 7, 13, 17, 41, 45, 57], [6, 14, 42], [6, 15, 43], [7, 16, 44], [7, 17, 45], [6, 7, 14, 16, 30, 32, 60], [6, 7, 15, 17, 31, 33, 61], [7, 16, 32], [7, 17, 33], [], [], [6, 7, 14, 16, 42, 44, 64], [6, 7, 15, 17, 43, 45, 65], [7, 16, 44], [7, 17, 45], [], [], [7, 16, 32, 52], [7, 17, 33, 53], [7, 16, 44, 56], [7, 17, 45, 57], [7, 16, 32, 60], [7, 17, 33, 61], [7, 16, 44, 64], [7, 17, 45, 65], [], [], [], [], [], [], [], []], [[2, 3, 8, 19], [3, 4, 10, 21], [4, 5, 12, 23], [5, 6, 14, 25], [6, 7, 16, 27], [8], [], [4, 5, 10, 12, 28], [3, 5, 19, 23, 35], [5, 6, 12, 14, 30], [4, 6, 21, 25, 37], [6, 7, 14, 16, 32], [5, 7, 23, 27, 39], [7, 16], [6, 25], [], [7, 27], [3, 5, 8, 12, 40], [4, 5, 21, 23, 47], [4, 6, 10, 14, 42], [5, 6, 23, 25, 49], [5, 7, 12, 16, 44], [6, 7, 25, 27, 51], [6, 14], [7, 27], [7, 16], [], [6, 7, 14, 16, 30, 32, 52], [5, 7, 23, 27, 35, 39, 55], [7, 16, 32], [6, 25, 37], [], [7, 27, 39], [6, 7, 14, 16, 42, 44, 56], [5, 7, 23, 27, 47, 51, 59], [7, 16, 44], [6, 25, 49], [], [7, 27, 51], [5, 7, 12, 16, 28, 32, 60], [6, 7, 25, 27, 37, 39, 63], [6, 14, 30], [7, 27, 39], [7, 16, 32], [], [5, 7, 12, 16, 40, 44, 64], [6, 7, 25, 27, 49, 51, 67], [6, 14, 42], [7, 27, 51], [7, 16, 44], [], [], [7, 27, 39, 55], [], [7, 27, 51, 59], [], [7, 27, 39, 63], [], [7, 27, 51, 67], [7, 16, 32, 52], [], [7, 16, 44, 56], [], [7, 16, 32, 60], [], [7, 16, 44, 64], []], [[2, 3, 9, 18], [3, 4, 11, 20], [4, 5, 13, 22], [5, 6, 15, 24], [6, 7, 17, 26], [8], [], [3, 5, 18, 22, 34], [4, 5, 11, 13, 29], [4, 6, 20, 24, 36], [5, 6, 13, 15, 31], [5, 7, 22, 26, 38], [6, 7, 15, 17, 33], [6, 24], [7, 17], [7, 26 ], [], [4, 5, 20, 22, 46], [3, 5, 9, 13, 41], [5, 6, 22, 24, 48], [4, 6, 11, 15, 43], [6, 7, 24, 26, 50], [5, 7, 13, 17, 45], [7, 26], [6, 15], [], [7, 17], [5, 7, 22, 26, 34, 38, 54], [6, 7, 15, 17, 31, 33, 53], [6, 24, 36], [7, 17, 33], [7, 26, 38], [], [ 5, 7, 22, 26, 46, 50, 58], [6, 7, 15, 17, 43, 45, 57], [6, 24, 48], [7, 17, 45], [7, 26, 50], [], [6, 7, 24, 26, 36, 38, 62], [5, 7, 13, 17, 29, 33, 61], [7, 26, 38], [6, 15, 31], [], [7, 17, 33], [6, 7, 24, 26, 48, 50, 66], [5, 7, 13, 17, 41, 45, 65], [7, 26, 50], [6, 15, 43], [], [7, 17, 45], [7, 26, 38, 54], [], [7, 26, 50, 58], [], [7, 26, 38, 62], [], [7, 26, 50, 66], [], [], [7, 17, 33, 53], [], [7, 17, 45, 57], [], [7, 17, 33, 61], [], [7, 17, 45, 65]], [[1, 3, 18, 19], [2, 4, 20, 21], [3, 5, 22, 23 ], [4, 6, 24, 25], [5, 7, 26, 27], [8], [8], [4, 5, 20, 22, 34], [4, 5, 21, 23, 35], [5, 6, 22, 24, 36], [5, 6, 23, 25, 37], [6, 7, 24, 26, 38], [6, 7, 25, 27, 39], [7, 26], [7, 27], [], [], [3, 5, 18, 22, 46], [3, 5, 19, 23, 47], [4, 6, 20, 24, 48], [4, 6, 21, 25, 49], [5, 7, 22, 26, 50], [5, 7, 23, 27, 51], [6, 24], [6, 25], [7, 26], [7, 27], [6, 7, 24, 26, 36, 38, 54], [6, 7, 25, 27, 37, 39, 55], [7, 26, 38], [7, 27, 39], [], [], [6, 7, 24, 26, 48, 50, 58], [6, 7, 25, 27, 49, 51, 59], [7, 26, 50], [7, 27, 51], [], [], [5, 7, 22, 26, 34, 38, 62], [5, 7, 23, 27, 35, 39, 63], [6, 24, 36], [6, 25, 37], [7, 26, 38], [7, 27, 39], [5, 7, 22, 26, 46, 50, 66], [5, 7, 23, 27, 47, 51, 67], [6, 24, 48], [6, 25, 49], [7, 26, 50], [7, 27, 51], [], [], [], [], [], [], [], [], [7, 26, 38, 54], [7, 27, 39, 55], [7, 26, 50, 58], [7, 27, 51, 59], [7, 26, 38, 62], [7, 27, 39, 63], [7, 26, 50, 66], [7, 27, 51, 67]]],[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]) ``` 7. Input: ``` Automaton("nondet",96,4,[[[1, 3, 9, 10], [2, 4, 11, 12], [3, 5, 13, 14], [4, 6, 15, 16], [5, 7, 17, 18], [6, 8, 19, 20], [7 ], [8], [3, 5, 9, 13, 33], [3, 5, 10, 14, 34], [4, 6, 11, 15, 35], [4, 6, 12, 16, 36], [5, 7, 13, 17, 37], [5, 7, 14, 18, 38], [6, 8, 15, 19, 39], [6, 8, 16, 20, 40], [7, 17], [7, 18], [8, 19], [8, 20], [4, 5, 11, 13, 49], [4, 5, 12, 14, 50], [5, 6, 13, 15, 51], [5, 6, 14, 16, 52], [6, 7, 15, 17, 53], [6, 7, 16, 18, 54], [7, 8, 17, 19, 55], [7, 8, 18, 20, 56], [8, 19], [8, 20], [], [], [5, 7, 13, 17, 33, 37, 65], [5, 7, 14, 18, 34, 38, 66], [6, 8, 15, 19, 35, 39, 67], [6, 8, 16, 20, 36, 40, 68], [7, 17, 37], [7, 18, 38], [8, 19, 39], [8, 20, 40], [5, 7, 13, 17, 49, 53, 73], [5, 7, 14, 18, 50, 54, 74], [6, 8, 15, 19, 51, 55, 75], [6, 8, 16, 20, 52, 56, 76], [7, 17, 53], [7, 18, 54], [8, 19, 55], [8, 20, 56], [6, 7, 15, 17, 35, 37, 81], [6, 7, 16, 18, 36, 38, 82], [7, 8, 17, 19, 37, 39, 83], [7, 8, 18, 20, 38, 40, 84], [8, 19, 39], [8, 20, 40], [], [], [6, 7, 15, 17, 51, 53, 89], [6, 7, 16, 18, 52, 54, 90], [7, 8, 17, 19, 53, 55, 91], [7, 8, 18, 20, 54, 56, 92], [8, 19, 55], [8, 20, 56], [], [], [7, 17, 37, 65], [7, 18, 38, 66 ], [8, 19, 39, 67], [8, 20, 40, 68], [7, 17, 53, 73], [7, 18, 54, 74], [8, 19, 55, 75], [8, 20, 56, 76], [7, 17, 37, 81], [7, 18, 38, 82], [8, 19, 39, 83], [8, 20, 40, 84], [7, 17, 53, 89], [7, 18, 54, 90], [8, 19, 55, 91], [8, 20, 56, 92], [8, 19, 39, 67], [8, 20, 40, 68], [], [], [8, 19, 55, 75], [8, 20, 56, 76], [], [], [8, 19, 39, 83], [8, 20, 40, 84], [], [], [8, 19, 55, 91], [8, 20, 56, 92], [], []], [[2, 3, 9, 22], [3, 4, 11, 24], [4, 5, 13, 26], [5, 6, 15, 28], [6, 7, 17, 30], [7, 8, 19, 32], [8 ], [], [4, 5, 11, 13, 33], [3, 5, 22, 26, 42], [5, 6, 13, 15, 35], [4, 6, 24, 28, 44], [6, 7, 15, 17, 37], [5, 7, 26, 30, 46], [7, 8, 17, 19, 39], [6, 8, 28, 32, 48], [8, 19], [7, 30], [], [8, 32], [3, 5, 9, 13, 49], [4, 5, 24, 26, 58], [4, 6, 11, 15, 51], [ 5, 6, 26, 28, 60], [5, 7, 13, 17, 53], [6, 7, 28, 30, 62], [6, 8, 15, 19, 55], [7, 8, 30, 32, 64], [7, 17], [8, 32], [8, 19], [], [6, 7, 15, 17, 35, 37, 65], [5, 7, 26, 30, 42, 46, 70], [7, 8, 17, 19, 37, 39, 67], [6, 8, 28, 32, 44, 48, 72], [8, 19, 39], [7, 30, 46], [], [8, 32, 48], [6, 7, 15, 17, 51, 53, 73], [5, 7, 26, 30, 58, 62, 78], [7, 8, 17, 19, 53, 55, 75], [6, 8, 28, 32, 60, 64, 80], [8, 19, 55], [7, 30, 62], [], [8, 32, 64], [5, 7, 13, 17, 33, 37, 81], [6, 7, 28, 30, 44, 46, 86], [6, 8, 15, 19, 35, 39, 83], [7, 8, 30, 32, 46, 48, 88], [7, 17, 37], [8, 32, 48], [8, 19, 39], [], [5, 7, 13, 17, 49, 53, 89], [6, 7, 28, 30, 60, 62, 94], [6, 8, 15, 19, 51, 55, 91], [7, 8, 30, 32, 62, 64, 96], [7, 17, 53], [8, 32, 64], [8, 19, 55], [], [8, 19, 39, 67], [7, 30, 46, 70], [], [8, 32, 48, 72], [8, 19, 55, 75], [7, 30, 62, 78], [], [8, 32, 64, 80], [8, 19, 39, 83], [7, 30, 46, 86], [], [8, 32, 48, 88], [8, 19, 55, 91], [7, 30, 62, 94], [], [8, 32, 64, 96], [7, 17, 37, 65], [8, 32, 48, 72], [8, 19, 39, 67], [], [7, 17, 53, 73], [8, 32, 64, 80], [8, 19, 55, 75], [], [7, 17, 37, 81], [8, 32, 48, 88], [8, 19, 39, 83], [], [7, 17, 53, 89], [8, 32, 64, 96 ], [8, 19, 55, 91], []], [[2, 3, 10, 21], [3, 4, 12, 23], [4, 5, 14, 25], [5, 6, 16, 27], [6, 7, 18, 29], [7, 8, 20, 31], [8], [], [3, 5, 21, 25, 41], [4, 5, 12, 14, 34], [4, 6, 23, 27, 43], [5, 6, 14, 16, 36], [5, 7, 25, 29, 45], [6, 7, 16, 18, 38], [6, 8, 27, 31, 47], [7, 8, 18, 20, 40], [7, 29], [8, 20], [8, 31], [], [4, 5, 23, 25, 57], [3, 5, 10, 14, 50], [5, 6, 25, 27, 59], [ 4, 6, 12, 16, 52], [6, 7, 27, 29, 61], [5, 7, 14, 18, 54], [7, 8, 29, 31, 63], [6, 8, 16, 20, 56], [8, 31], [7, 18], [], [8, 20 ], [5, 7, 25, 29, 41, 45, 69], [6, 7, 16, 18, 36, 38, 66], [6, 8, 27, 31, 43, 47, 71], [7, 8, 18, 20, 38, 40, 68], [7, 29, 45], [8, 20, 40], [8, 31, 47], [], [5, 7, 25, 29, 57, 61, 77], [6, 7, 16, 18, 52, 54, 74], [6, 8, 27, 31, 59, 63, 79], [7, 8, 18, 20, 54, 56, 76], [7, 29, 61], [8, 20, 56], [8, 31, 63], [], [6, 7, 27, 29, 43, 45, 85], [5, 7, 14, 18, 34, 38, 82], [7, 8, 29, 31, 45, 47, 87], [6, 8, 16, 20, 36, 40, 84], [8, 31, 47], [7, 18, 38], [], [8, 20, 40], [6, 7, 27, 29, 59, 61, 93], [5, 7, 14, 18, 50, 54, 90], [7, 8, 29, 31, 61, 63, 95], [6, 8, 16, 20, 52, 56, 92], [8, 31, 63], [7, 18, 54], [], [8, 20, 56], [7, 29, 45, 69], [8, 20, 40, 68], [8, 31, 47, 71], [], [7, 29, 61, 77], [8, 20, 56, 76], [8, 31, 63, 79], [], [7, 29, 45, 85], [8, 20, 40, 84], [8, 31, 47, 87], [], [7, 29, 61, 93], [8, 20, 56, 92], [8, 31, 63, 95], [], [8, 31, 47, 71], [7, 18, 38, 66], [], [8, 20, 40, 68], [8, 31, 63, 79], [7, 18, 54, 74], [], [8, 20, 56, 76], [8, 31, 47, 87], [7, 18, 38, 82], [], [8, 20, 40, 84], [8, 31, 63, 95], [7, 18, 54, 90 ], [], [8, 20, 56, 92]], [[1, 3, 21, 22], [2, 4, 23, 24], [3, 5, 25, 26], [4, 6, 27, 28], [5, 7, 29, 30], [6, 8, 31, 32], [8], [8], [4, 5, 23, 25, 41], [4, 5, 24, 26, 42], [5, 6, 25, 27, 43], [5, 6, 26, 28, 44], [6, 7, 27, 29, 45], [6, 7, 28, 30, 46], [7, 8, 29, 31, 47], [7, 8, 30, 32, 48], [8, 31], [8, 32], [], [], [3, 5, 21, 25, 57], [3, 5, 22, 26, 58], [4, 6, 23, 27, 59], [4, 6, 24, 28, 60], [5, 7, 25, 29, 61], [5, 7, 26, 30, 62], [6, 8, 27, 31, 63], [6, 8, 28, 32, 64], [7, 29], [7, 30], [8, 31], [8, 32], [6, 7, 27, 29, 43, 45, 69], [6, 7, 28, 30, 44, 46, 70], [7, 8, 29, 31, 45, 47, 71], [7, 8, 30, 32, 46, 48, 72], [8, 31, 47], [8, 32, 48], [], [], [6, 7, 27, 29, 59, 61, 77], [6, 7, 28, 30, 60, 62, 78], [7, 8, 29, 31, 61, 63, 79], [7, 8, 30, 32, 62, 64, 80], [8, 31, 63], [8, 32, 64], [], [], [5, 7, 25, 29, 41, 45, 85], [5, 7, 26, 30, 42, 46, 86], [6, 8, 27, 31, 43, 47, 87], [6, 8, 28, 32, 44, 48, 88], [7, 29, 45], [7, 30, 46], [8, 31, 47], [8, 32, 48], [5, 7, 25, 29, 57, 61, 93], [5, 7, 26, 30, 58, 62, 94], [6, 8, 27, 31, 59, 63, 95], [6, 8, 28, 32, 60, 64, 96], [7, 29, 61], [7, 30, 62], [8, 31, 63], [8, 32, 64], [8, 31, 47, 71], [8, 32, 48, 72 ], [], [], [8, 31, 63, 79], [8, 32, 64, 80], [], [], [8, 31, 47, 87], [8, 32, 48, 88], [], [], [8, 31, 63, 95], [8, 32, 64, 96 ], [], [], [7, 29, 45, 69], [7, 30, 46, 70], [8, 31, 47, 71], [8, 32, 48, 72], [7, 29, 61, 77], [7, 30, 62, 78], [8, 31, 63, 79], [8, 32, 64, 80], [7, 29, 45, 85], [7, 30, 46, 86], [8, 31, 47, 87], [8, 32, 48, 88], [7, 29, 61, 93], [7, 30, 62, 94], [8, 31, 63, 95], [8, 32, 64, 96]]],[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]) ``` 8. The NFAs for 8, 9, 10, 11, 12, 13, 14, 15, 16 are [here](https://gist.github.com/Anush-ccgc/2fa45d31934e7b7062a6140d634c79fa/archive/22076b470d0715f1e39867bae6741c41ebc5b7d5.zip).The files have names k7nfa, k8nfa etc. As an example, the input for problem 7 is k7nfa. Hopefully the rest of the names are clear. If your code is correct for problem sizes I can test, I am happy to believe it is correct in general. # Score I will time your code on test cases 1..16 from above of increasing size. For each test \$n\$, the time limit is \$2^n\$ seconds. Your score will be the largest test case your code can process within its time limit. If two answers get to the same size then the one that is fastest on that largest test case wins. The test machine is an Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz. You can use at most 16 of its cores. # A possible solution method One method for converting NFAs to DFAs is called [subset construction](https://www.youtube.com/watch?v=fiT1nYM1j0Q). Because our NFAs will not have any \$\epsilon\$-moves it is slightly simpler than usual. Here is an overview of the algorithm: Start at the initial state 1. Perform the following for the new DFA state. For each possible input symbol: Apply move to the newly-created state and the input symbol; this will return a set of states. This set of NFA states will be a single state in the DFA. 2. Each time we generate a new DFA state, we must apply step 1 to it. The process is complete when applying step 1 does not yield any new states. The accepting states of the DFA are those which contain any of the finish states of the NFA. # How can this be sped up? There are have been some attempts to parallelize subset construction. E.g. * <https://crpit.scem.westernsydney.edu.au/confpapers/CRPITV140Choi.pdf> * <https://link.springer.com/chapter/10.1007/978-3-662-47401-3_3> Other work has focussed on making the data structures as fast as possible, amongst other things. * <http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=D48BED26B35E96F5FB5E9740585F5C67?doi=10.1.1.8.7435&rep=rep1&type=pdf> # Testing I will check your answers (for the smaller cases) using [AreEquivAut](https://www.gap-system.org/Manuals/pkg/automata-1.14/doc/chap4.html#X8346D1B17DBF96E7) . [Thank you to Christian Sievers for the example NFAs.] # Results * **16** in \$33812 < 2^{16} = 65536\$ seconds in **Rust** by Anders Kaseorg. [Answer] # Rust, score 15 in ‚âà 6000 s Most of my optimization effort has actually gone into memory usage rather than speed, for reasons you can see in this table of results on my system (AMD Ryzen 1800X): ``` case time memory DFA size 1 0.00 s 2 MiB 3 2 0.00 s 2 MiB 18 3 0.00 s 2 MiB 57 4 0.00 s 2 MiB 207 5 0.00 s 2 MiB 318 6 0.00 s 2 MiB 1201 7 0.01 s 3 MiB 12230 8 0.14 s 9 MiB 66324 9 0.47 s 18 MiB 179766 10 3.16 s 68 MiB 879932 11 11.40 s 241 MiB 2385052 12 100.64 s 886 MiB 10750324 13 333.82 s 2026 MiB 29158718 14 1810.72 s 9073 MiB 123222354 15 6008.30 s 20631 MiB 333765796 ``` Build with `cargo build --release` and run with `target/release/automaton < INPUT`. ### `src/main.rs` ``` use ahash::AHasher; use hashbrown::hash_map::{HashMap, RawEntryMut}; use mimalloc::MiMalloc; use nom::bytes::complete::tag; use nom::character::complete::{char, digit1, multispace0}; use nom::combinator::{map, map_res}; use nom::multi::separated_list0; use nom::sequence::{delimited, preceded}; use nom::IResult; use std::collections::VecDeque; use std::convert::TryInto; use std::error::Error; use std::hash::{Hash, Hasher}; use std::io; use std::mem; use std::str::FromStr; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; #[derive(Debug)] struct Automaton<Set> { size: u32, alphabet: usize, transitions: Vec<Vec<Set>>, initial: Set, accepting: Vec<u32>, } fn parse_vec<'a, T>( item: impl FnMut(&'a str) -> IResult<&'a str, T>, input: &'a str, ) -> IResult<&'a str, Vec<T>> { delimited( char('['), map( separated_list0( preceded(multispace0, char(',')), preceded(multispace0, item), ), |v| v.into_iter().collect(), ), preceded(multispace0, char(']')), )(input) } type Id = u32; type Node = u128; const ID_BITS: u32 = mem::size_of::<Id>() as u32 * 8; const NODE_BITS: u32 = mem::size_of::<Node>() as u32 * 8; const DEGREE: u32 = NODE_BITS / ID_BITS; struct Trie { size: u32, nodes: Vec<Node>, ids: HashMap<Id, ()>, } fn pack(ids: [Id; DEGREE as usize]) -> Node { let mut node = 0; for k in 0..DEGREE { node |= (ids[k as usize] as Node) << ID_BITS * k; } node } fn unpack(node: Node) -> [Id; DEGREE as usize] { let mut ids = [0; DEGREE as usize]; for k in 0..DEGREE { ids[k as usize] = (node >> ID_BITS * k) as Id; } ids } fn node_hash(node: Node) -> u64 { let mut hasher = AHasher::default(); node.hash(&mut hasher); hasher.finish() } impl Trie { fn new(real_size: u32) -> Trie { let mut size = NODE_BITS; while size < real_size { size *= DEGREE; } let mut trie = Trie { size, nodes: vec![], ids: HashMap::new(), }; let zero_id = trie.node_id(0); debug_assert_eq!(zero_id, 0); trie } fn node_id(&mut self, node: Node) -> Id { let hash = node_hash(node); let nodes = &mut self.nodes; match self .ids .raw_entry_mut() .from_hash(hash, |&id| nodes[id as usize] == node) { RawEntryMut::Occupied(e) => *e.key(), RawEntryMut::Vacant(e) => { let id: Id = nodes.len().try_into().unwrap(); nodes.push(node); e.insert_with_hasher(hash, id, (), |&id| node_hash(nodes[id as usize])); id } } } fn vec_id(&mut self, low: u32, high: u32, vec: Vec<u32>) -> Id { if vec.is_empty() { 0 } else if high - low <= NODE_BITS { let mut node: Node = 0; for n in vec { node |= 1 << n - low; } self.node_id(node) } else { let step = (high - low) / DEGREE; let mut vecs: [Vec<u32>; DEGREE as usize] = Default::default(); for n in vec { vecs[((n - low) / step) as usize].push(n); } let mut ids = [0; DEGREE as usize]; for k in 0..DEGREE { ids[k as usize] = self.vec_id( low + k * step, low + (k + 1) * step, mem::take(&mut vecs[k as usize]), ); } self.node_id(pack(ids)) } } fn parse_set<'a>(&mut self, input: &'a str) -> IResult<&'a str, Id> { let (input, vec) = parse_vec(map_res(digit1, u32::from_str), input)?; Ok((input, self.vec_id(0, self.size, vec))) } fn intersects(&self, size: u32, a: Id, b: Id) -> bool { if a == 0 || b == 0 { false } else { let a_node = self.nodes[a as usize]; let b_node = self.nodes[b as usize]; if size <= NODE_BITS { a_node & b_node != 0 } else { let step = size / DEGREE; let a_ids = unpack(a_node); let b_ids = unpack(b_node); (0..DEGREE).any(|k| self.intersects(step, a_ids[k as usize], b_ids[k as usize])) } } } fn union(&mut self, size: u32, ids: &mut Vec<Id>) -> Id { ids.retain(|&id| id != 0); if ids.len() < 2 { ids.drain(..).next().unwrap_or(0) } else { let mut node; if size <= NODE_BITS { node = 0; for id in ids.drain(..) { node |= self.nodes[id as usize]; } } else { let step = size / DEGREE; let mut vecs: [Vec<Id>; DEGREE as usize] = Default::default(); for vec in &mut vecs { vec.reserve(ids.len()); } for id in ids.drain(..) { let ids1 = unpack(self.nodes[id as usize]); for k in 0..DEGREE { vecs[k as usize].push(ids1[k as usize]); } } let mut ids = [0; DEGREE as usize]; for k in 0..DEGREE { ids[k as usize] = self.union(step, &mut vecs[k as usize]); } node = pack(ids) }; self.node_id(node) } } fn for_each(&self, low: u32, high: u32, id: Id, f: &mut impl FnMut(u32)) { if id != 0 { let mut node = self.nodes[id as usize]; if high - low <= NODE_BITS { while node != 0 { let k = node.trailing_zeros(); f(low + k); node &= !(1 << k); } } else { let step = (high - low) / DEGREE; let ids = unpack(node); for k in 0..DEGREE { self.for_each(low + k * step, low + (k + 1) * step, ids[k as usize], f); } } } } } fn parse_nfa(input: &str) -> IResult<&str, (Trie, Automaton<Id>)> { let (input, _) = tag("Automaton")(input)?; let (input, _) = preceded(multispace0, char('('))(input)?; let (input, _) = preceded(multispace0, tag("\"nondet\""))(input)?; let (input, _) = preceded(multispace0, char(','))(input)?; let (input, size) = preceded(multispace0, map_res(digit1, u32::from_str))(input)?; let mut trie = Trie::new(size); let (input, _) = preceded(multispace0, char(','))(input)?; let (input, alphabet) = preceded(multispace0, map_res(digit1, usize::from_str))(input)?; let (input, _) = preceded(multispace0, char(','))(input)?; let (input, transitions) = preceded(multispace0, |input| { parse_vec( |input| parse_vec(|input| trie.parse_set(input), input), input, ) })(input)?; let (input, _) = preceded(multispace0, char(','))(input)?; let (input, initial) = preceded(multispace0, |input| trie.parse_set(input))(input)?; let (input, _) = preceded(multispace0, char(','))(input)?; let (input, accepting) = preceded(multispace0, |input| { parse_vec(|input| map_res(digit1, u32::from_str)(input), input) })(input)?; let (input, _) = preceded(multispace0, char(')'))(input)?; Ok(( input, ( trie, Automaton { size, alphabet, transitions, initial, accepting, }, ), )) } struct DFABuilder { nfa_accepting: Id, trie: Trie, set_dstate: HashMap<Id, u32>, queue: VecDeque<Id>, dfa: Automaton<u32>, } impl DFABuilder { fn visit(&mut self, set: Id) -> u32 { let DFABuilder { nfa_accepting, trie, set_dstate, queue, dfa, } = self; *set_dstate.entry(set).or_insert_with(|| { dfa.size += 1; if trie.intersects(trie.size, *nfa_accepting, set) { dfa.accepting.push(dfa.size); } queue.push_back(set); dfa.size }) } } fn nfa_to_dfa(mut trie: Trie, nfa: Automaton<Id>) -> Automaton<u32> { let mut builder = DFABuilder { nfa_accepting: trie.vec_id(0, trie.size, nfa.accepting.clone()), trie, set_dstate: HashMap::new(), queue: VecDeque::new(), dfa: Automaton { size: 0, alphabet: nfa.alphabet, transitions: vec![vec![]; nfa.alphabet], initial: !0, accepting: vec![], }, }; builder.dfa.initial = builder.visit(nfa.initial); let mut sets = Vec::new(); while let Some(set) = builder.queue.pop_front() { for (letter, transition) in nfa.transitions.iter().enumerate() { builder .trie .for_each(0, builder.trie.size, set, &mut |nstate| { sets.push(transition[nstate as usize - 1]) }); let set1 = builder.trie.union(builder.trie.size, &mut sets); debug_assert!(sets.is_empty()); let dstate = builder.visit(set1); builder.dfa.transitions[letter].push(dstate); } } builder.dfa } fn main() -> Result<(), Box<dyn Error>> { let mut line = String::new(); io::stdin().read_line(&mut line)?; let (rest, (trie, nfa)) = delimited(multispace0, parse_nfa, multispace0)(&line).map_err(|e| e.to_string())?; if rest != "" { return Err("expected end of input".into()); } let dfa = nfa_to_dfa(trie, nfa); println!( "Automaton(\"det\", {}, {}, {:?}, [{}], {:?})", dfa.size, dfa.alphabet, dfa.transitions, dfa.initial, dfa.accepting ); Ok(()) } ``` ### `Cargo.toml` ``` [package] name = "automaton" version = "0.1.0" authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"] edition = "2018" [dependencies] nom = "6.2.1" mimalloc = { version = "0.1.26", default-features = false } hashbrown = { version = "0.11.2", features = ["raw"] } ahash = "0.7.4" ``` ]
[Question] [ ## Background An [Eisenstein integer](https://en.wikipedia.org/wiki/Eisenstein_integer) is a complex number of the form \$ z = a + b\omega \$ where \$a, b\$ are integers and \$\omega\$ is the third root of unity \$\frac{1-\sqrt3i}{2}\$. The Eisenstein integers can be viewed as the triangular lattice points, as shown in the image below (from Wikipedia): [![enter image description here](https://i.stack.imgur.com/5FDgS.png)](https://i.stack.imgur.com/5FDgS.png) Following the triangular grid, one step of movement can be done in six directions: $$ \begin{array}{r|r} \text{Direction} & \text{Step} \\ \hline E & 1 \\ NE & 1 + \omega \\ NW & \omega \\ W & -1 \\ SW & -1 - \omega \\ SE & -\omega \end{array} $$ ## Task Given an Eisenstein integer \$z\$, count all shortest paths from the origin (\$0\$) to the point equivalent to \$z\$ on the triangular grid. Since \$z = a + b \omega\$ can be represented by two integers \$ a, b \$, you can take the input as two integers \$a, b\$ in any consistent order and structure of your choice. One way to compute this is (thanks to @xnor): ``` Take the absolute values of [a, b, a-b], and call it L Calculate binomial(max(L), any other value in L) ``` ## Test cases ``` a b ans 0 0 1 2 0 1 5 3 10 4 4 1 2 3 3 0 2 1 -2 2 6 -4 0 1 -5 -3 10 -1 -1 1 -3 -5 10 0 -3 1 4 -1 5 -4 -9 126 7 -4 330 8 1 8 3 -3 20 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` Max[l=Abs@{#,#2,#-#2}]~Binomial~Min@l& ``` [Try it online!](https://tio.run/##Vc4/C8IwEAXw3U8hBJzuIM0f1KGQuhfcS4coUgNJCpqhIParR13kbvxx7x4v@XK/JV/C1deprb1fhth2l6d7CRAKBAr1HtdTyHMKPq59yC7u6vkRctm6aZAgx81fismCJjJgWJLeJCgiVJyGtaIFpL/YADbUGtCybuQzePrrI/EekM48AA3rX1WtHw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;IAṀc$Ṁ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/a0/HhzoZkFSDx////aF0THQVdy1gA "Jelly – Try It Online")** ### How? ``` ;IAṀc$Ṁ - Link: list of two integers e.g. [-4, -9] I - incremental differences [-5] (since -9 - -4 = -5) ; - concatenate [-4, -9, -5] A - absolute values [4, 9, 5] $ - last two links as a monad: Ṁ - maximum 9 c - choose (vectorises) [126, 1, 126] (9c4=9c5=126 and 9c9=1) Ṁ - maximum 126 ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~69~~ 68 bytes Saved a byte thanks to [newbie](https://codegolf.stackexchange.com/users/89856/newbie)!!! ``` lambda a,b:math.comb(*sorted(map(abs,[a,b,a-b]))[2::-2]) import math ``` [Try it online!](https://tio.run/##RVDLisMgFN37FWenDrGkmraZQOZH2i60TWggD1G7GEq/PaNJZgYucjwvLtd@h8c0qtK6ua0vc68Hc9fQmakGHR672zQY9uEnF5o7G7Rl2vjsHOVMC3Pl/CyrSsgrJ91gowkpNIfGB19TSglypAH2BPIfHgCVUE5QIM2vIbFQS0yurJAbPBJR/DWIA8TWIPaIs7IKUVh789WQeovNcEgN4jNy8khwQupTKnrLSCVDSeICS0zmJK3vavakl6c8FTeaYYV7RTlpJ5dulDXoRix36caQ9Ttv@y4wzpEMfRKXW@x8cJ1lfNPpZaScVwQeNVqmMxhOYF3sYC196Uq@8TLpFV94@UrFrzv7um6ub8rn@Qc "Python 3.8 (pre-release) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~13~~ 12 bytes *1 byte saved thanks to @ngn!* ``` (⌊/!⌈/)∘|,,- ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNRz1d@oqPejr0NR91zKjR0dH9/99AIU1BwYDLCEKZgihjLhMQZQIRNOYCKzHiOrTeCMYwgag@tB6k/tB6YyDLEMwyBLKMwSxTsDaQnAlcBsKy5DIH0yZcFiBjDLkgGowB "APL (Dyalog Unicode) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes Seems rather long. ``` .cF_tSa0+aF ``` **[Test suite](http://pythtemp.herokuapp.com/?code=.cF_tSa0%2BaF&test_suite=1&test_suite_input=%5B0%2C0%5D%0A%5B2%2C0%5D%0A%5B5%2C3%5D%0A%5B4%2C4%5D%0A%5B2%2C3%5D%0A%5B0%2C2%5D%0A%5B-2%2C2%5D%0A%5B-4%2C0%5D%0A%5B-5%2C-3%5D%0A%5B-1%2C-1%5D%0A%5B-3%2C-5%5D%0A%5B0%2C-3%5D%0A%5B4%2C-1%5D%0A%5B-4%2C-9%5D%0A%5B7%2C-4%5D%0A%5B8%2C1%5D%0A%5B3%2C-3%5D&debug=0)** ### Explanation Uses xnor's description. ``` .cF_tSa0+aF Full program. Input: a 2-element list [a,b]. +aF Add |a-b| to the list of inputs. Produces [|a-b|,a,b] a0 Absolute difference with 0 (i.e. absolute value). Vectorizes. tS Sort the list of absolute values and remove the first element. .cF_ Reverse the above and apply nCr to its elements. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~92~~ 82 bytes ``` g(n,k){k=k<0?n=-n,-k:k;n=n<0?k-n:n;k^=n<k?n^=k^=n:0;n=n---k&&k?g(n,k-1)+g(n,k):1;} ``` [Try it online!](https://tio.run/##JUzbSsQwEH3PVxwWWlLMQNO0qI2xPyIL3XatJTqKij4s@@11pg7MMOc60TJN27ZYdrm65JQf6oETsaPc58iJBWfinmM@CsgDH5N@fa0iEeWyzMMeJ1/d/Pf0Pl63lb/xNq5sf97XuTLARRbKjg6naBT9vqyvZ9gGKeFrGvnZHooZxXxwKMVVnioNynx8SlDVILJsekTRzU8sRm1zWOzoxB3Fft1QA7VBs98OCAYt0O6M/KI2hpr9tuqhDhQMeZA3FECdemhPKSP33uAWJA13gDcIqv4B "C (gcc) – Try It Online") *10 bytes shorter thanks to ceilingcat!* This is longer than most of the other entries, but I think it's respectable since C doesn't have a built-in for binomial coefficients. The code uses the fact that the four Eisenstein integers $$n+k\omega,$$ $$-n-k\omega,$$ $$k-n+k\omega,$$ and $$n-k-k\omega$$ are symmetrically located about the origin. Since the original triangular lattice is symmetrical about the origin, all four of those points will have the same number of paths to the origin. Because of this, we can replace the input point with a point with non-negative Eisenstein coordinates which has the same number of paths to the origin, and that simplifies the computation. Here's how it works: 1. If `k < 0`, replace `n` by `-n`, and `k` by `-k`. So now `k` is non-negative, but the output will be the same as for the original values of `n` and `k`. 2. If `n < 0`, replace `n` by `k-n`. Now `n` is also non-negative, but again the output will be the same. 3. If `k > n`, swap `n` and `k`, so that `n` is the larger of the two (or they're equal). 4. Compute the binomial coefficient \$\binom{n}{k}\$ using the recursive formula for it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ⊞υN⊞υ±N⊞υΣυ≔…⌊↔υ⌈↔υθI∨¬θ÷Π⊕θΠ⊕Eθκ ``` [Try it online!](https://tio.run/##bY5BDoIwEEX3noLlNIGdiQtWRDcuQKInKGUCjbSFdoZ4@1piTDQ6y/f@n3w1Sq@cnGJsOYzAeXa2M1PDpkMPQpS7N29wkITwrT/8jQ3wBqoQ9GDhKu2AUGurTTJVF9zEqZ8ieVbLxw9NeNneeW0JjjIQXDw0jmAR2yg66VX3CK13PStKO5RHg5awT4kU@SdqOcOSZ3fxujLGw67Yx2Kdng "Charcoal – Try It Online") Link is to verbose version of code. Uses @xnor's formula. Explanation: ``` ⊞υN ``` Input `a` and push it to the list. ``` ⊞υ±N ``` Input `b` and push `-b` to the list. ``` ⊞υΣυ ``` Take the sum of the list, `a-b`, and push that to the list. ``` ≔…⌊↔υ⌈↔υθ ``` Take the minimum and maximum of the list and form a range between the two. ``` I∨¬θ ``` If the range is empty then just output `1` (unfortunately in Charcoal the product of an empty list isn't `1`)... ``` ÷Π⊕θΠ⊕Eθκ ``` ... otherwise output the quotient of the products of the ranges `min+1..max` and `1..max-min`. [Answer] # JavaScript (ES6), 83 bytes Takes input as `(a)(b)`. Uses @xnor's formula. ``` with(Math)f=a=>g=(b,k=min(...a=[a,b,a-b].map(abs),n=max(...a)))=>k?n--*g(0,k-1)/k:1 ``` [Try it online!](https://tio.run/##fZBNbsIwFIT3nMJLv8rP8U9oKZLpCXqCqosXCiENcRCJ2t4@tfsLhsTSrD7PeMav9Ebd@lgdevTty2YY3qt@xx@p38HWkVuVjheidk3luZSS3BOJQhAWz7KhA6eiA@FdQx9fFADcqn7wiDclV6JGDVm91MO69V2738h9W/ItZwqigGUZC0fPEmym8Txg@4u1SnEOUZPhf25mZ1eqmVE3mjN8m@J8sjmG5jjePHxW1KjbQkwY3a1Owy9352fh8yvN8f4Ha5MOY3cQr3xjay/eXoTd/@GLFNvTakYNnw "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¥«ÄZscà ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/203406/52210), so make sure to upvote him as well!! [Try it online](https://tio.run/##yy9OTMpM/f//0NJDqw@3RBUnH17w/3@0romOrmUsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/0NLD60@3BJVnHx4wX@d/9HRBjoGsTrRRmDSVMcYSJromIBFQGwDHSMgqWsEoUzAqnRNdXRBcrqGOrqGINpYR9cUrFYXoh0iCqQtgbS5ji7IOAsdkKAxSEksAA). **Explanation:** ``` ¥ # Get deltas / forward-difference of the (implicit) input-pair « # Merge it to the (implicit) input-pair Ä # Take the absolute value of each Z # Push the maximum of this list (without popping) s # Swap so the list is at the top of the stack again c # Choose; get the binomial coefficient of each value with this maximum à # And pop and push the maximum of those result # (after which it is output implicitly) ``` [Answer] # [Io](http://iolanguage.org/), 79 bytes Port of most answers. ``` method(a,b,list(2,0)map(i,list(a,b,a-b)map(abs)sort at(i))reduce(combinations)) ``` [Try it online!](https://tio.run/##JcwxCoAwDEDRq3RMoAXRTfAmLmktGLBNaeL5K@r43/BZRiM71a2b20fJdsoB5KO/WA1mP2GhBvzn6xTiRxQVVbo5MmDEno87ZUhSIlcylqqI/xoWHxZ0rXO1q44H "Io – Try It Online") ]
[Question] [ **Edit**: *I haven't played D&D before so when I initially made this question I didn't properly research it. I apologize for this, and I'm making a few edits that might invalidate answers to stay as true as possible to the dnd 5e rules. Sorry.* --- A D&D fan from a recent [Hot Network Question](https://rpg.stackexchange.com/questions/131928/is-there-an-easy-way-to-validate-a-high-level-sorcerers-spell-list) seems to have some trouble working out whether a sorcerer's chosen spells line up with the possibilities - and I think we should help! ### Introduction *(all of this is already described in the previously mentioned question)* A sorcerer knows two level 1 spells from start (level 1): `[1, 1]` * Every time a sorcerer gains a level (except for levels 12, 14, 16, 18, 19 and 20) they learn a **new** spell (mandatory). * Additionally, when leveling up one can choose (optional) to **replace** one of the spells with another. The spells learned and replaced must be a valid spell slot level which is half your sorcerer's level rounded up. See this table: ``` Sorcerer level Highest spell level possible 1 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 8 16 8 17 9 18 9 19 9 20 9 ``` This means at level 3 one can have the spell levels `[1, 1, 2, 2]` like this: ``` Level 1: [1, 1] (initial) Level 2: [1, 1, 1 (new)] Level 3: [1, 1, 2 (replaced), 2 (new)] ``` It is not required to pick the highest level spells you have access to. The spell levels `[1, 1, 1, 1]` are perfectly valid for a level 3. Lastly, remember that replacing a spell is an optional option *for every level*. This means that some levels could skip the replace, while others make use of it. ### The challenge Make a program or function that takes an integer (level) between 1 and 20. It should also take an array of integers (spell levels) with values ranging from 1 to 9 in any order (9 is the maximum spell level). The output of the program should be a truthy/falsy value validating if the chosen spell levels are valid for a sorcerer of the given level. ### Test cases ``` Level: 1 Spells: [1, 1] Output: true Level: 8 Spells: [1, 1, 2, 3, 3, 5] Ouput: false Reason: A level 8 can't ever have access to a level 5 spell. Level: 5 Spells: [1, 1, 1, 2, 2, 2, 3] Output: false Reason: A level 5 can't have access to 7 spells Level: 11 Spells: [3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6] Output: false Reason: Too many spell upgrades. The highest valid selection for level 11 is [3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6] ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - fewest bytes wins! [Answer] # [Java (JDK)](http://jdk.java.net/), 99 bytes ``` s->l->{var r=s.length!=l+1-l/12*(l-10)/2-l/19;for(var z:s)r|=z>(++l>30?9:l+(2<<l/25)>>2);return!r;} ``` [Try it online!](https://tio.run/##jVDRbtMwFH3vV9xNqmSvSdp4lNGmCeIFCQk0pD5Oe3BTp7i4TmTfFHVdvr3YzoY2KIKcB@tcn3N8brZ8z@Pt@vtJ7praIGwdT1qUKrnKBn/MqlaXKGvtL0vFrYUvXGo4DgCadqVkCRY5umNfyzXs3B1ZopF6c3cP3GwsDVKAj085C6nx7j76pPGrEWtZchQFVJCfbFyouDjuuQGT20QJvcFvF7kapbEap@yKqDid0DHzbJZVtSFe@jC31DzmDwUZjVRxPXk/m6sRYYuFGrMpLQpGMyOwNfrCZN0pC1W8D4VFYSAHLX7A7WorSiS0bwr9Kl5BXFlQYi9UBKE32EYo9dlPfm3mv@XBxe2SusWkcctjRS6DyD0wZOsIlt5mPbNzGK6G@jJ6zv1gDD/YBOv@t5GXL0RQJbxp1OHVNAnVgp3S7KlDF86up/12vS6Nwo6h/tGRtKP/IfqLbvpaxxzeRNOzib9FnsVZI/u38eackU1eGqfR24CbgHcBs2f09m7QnX4C "Java (JDK) – Try It Online") ## Credits * Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/172599/16236). However, the `l+1-l/12*(l-10)/2-l/19` part is a shortening in Java for `(l<12?l:l>16?14:l+11>>1)+1` which can't be done in JavaScript because it doesn't round to the floor integer. --- Previous answer: # [Java (JDK 10)](http://jdk.java.net/), 191 bytes ``` L->S->{int m[]=new int[9],z=0,Z=0,l=0;for(m[0]++;l++<L;z+=--m[z]<1?1:0)m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2;l=0;for(int s:S){if(--s>Z)l++;Z-=--m[Z>0?Z:0]<1?1:0;}for(int i:m)l|=i;return l==0;} ``` [Try it online!](https://tio.run/##jZHbitswEIbv8xTDQsCuD7VNt9tYlkNvCoWULvjOxheKIy9K5QOSnJKk3ldPZTlZAm2hHgsxmm/@0Yz25EC8/e7HhTV9JxTste8PinH/HVr8cVYPbaVY107BihMp4RthLZwXAP2w5awCqYjS26FjO2h0zMqUYO1LUQIRL9I2KMDXVn25SiXPgu5YRRRNWKuKMk2hBnzZeGnmpWd9BE1R4pb@hCm8Kt0TDtxcL44DVHfCaoqgdBzEHSfZoJODPa8pTmUSrsM4sJsix68efx/pFa5KB/MkjNZRzNPwSQOhw5cRuilNxWSc2WdWW54n09zWoij3jGSeBus8Dq7CaLwlsLix@S/MkKBqEC1wrNXGCzJ9HogARaWiAjBMPXzf7mmlLHseA8xzmgijxemBctc0WoLsKeeb6eRtbNOXHbVc43eD8ns9WVVbDwbSBZbRzoVsSpOTJ2NYbpftg3vT/SwEOUpfdfObWPcVXKh90vf8aBnY9s2l7gkbXe8wmn2c3bm7mQ5duL1TedZOONr/Af2De7zntPPBhcj8f6Wj4B5fuTf7ZOzJ2Edjj3P6uBgvvwE "Java (JDK 10) – Try It Online") * **Input requirement:** the spell list must be ordered from greatest spell levels to the lowest one. ## Explanations ``` L->S->{ // Curried-lambda with 2 parameters: sorcerer-level and spell list int m[]=new int[9], // Declare variables: m is the max level of each spell. z=0, // z is the minimum spell level of the maximized spell list. Z=0, // Z is the maximum spell level for the current level. l=0; // l is first a level counter, then a reused variable for(m[0]++;l++<L;z+=--m[z]<1?1:0) // for each level, compute the maximized known spells. m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2; // // Now m is the row for level L in the table below. l=0; // l now becomes an error indicator for(int s:S){ // This loop checks if the spell-list matches the spells allowed for that level. if(--s>Z)l++; // Spell-levels are 1-based, my array is 0-based so decrease s. Z-=--m[Z>0?Z:0]<1?1:0; // Remove a max level if we've expleted all the spells, avoiding exception. } // for(int i:m)l|=i; // Make sure there are no more values in m. return l==0; // Return true if no miscount were encountered. } ``` **Table 1:** Maximized spell distribution for each sorcerer-level, used from [Axoren's answer on the linked question](https://rpg.stackexchange.com/a/131936/28410). [![enter image description here](https://i.stack.imgur.com/aARZt.png)](https://i.stack.imgur.com/aARZt.png) ## Credits * Saved 14 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes ``` Nθ≔⁺✂⭆”)⊟⊞<⁴H”×IκIιθ⎇‹θ¹²⊕⊗θ⁺⁶⁺θ⊘⁺‹θ¹⁹θ¹0θ¬ΣES›ι§θκ ``` [Try it online!](https://tio.run/##PU/bCsIwDH3fV4w9pTDBbU6QPYmCDlSE@QN1Bi12netF9OtrVsVAyO3k5KS9cd32XHpfq4ezB9edUcPAqmhpjLgqOEpnoJGiRWisFuq65w9IpuWMrCiKMknjk@jQwIobC3eWxiERjFE60BC14voNOzQGqM5y6teq1dihsniBde/OkuIwLoRr818k9JbLJ81C@WdYjMyMhQsZeTJNQqeKjiTQwqG30LgORqXhq69wINBGI7f0oEjjpa3VBV8j4z2Qscr7MsryfFb6yVN@AA "Charcoal – Try It Online") Link is to verbose version of code. Takes spell levels in ascending order as a string. Explanation: ``` Nθ ``` Input the level. ``` ≔⁺✂⭆”)⊟⊞<⁴H”×IκIιθ⎇‹θ¹²⊕⊗θ⁺⁶⁺θ⊘⁺‹θ¹⁹θ¹0θ ``` Perform run-length decoding on the string `0544443335` resulting in the string `11111222233334444555566677788899999`. This string is then sliced starting at the level (1-indexed) and ending at the doubled level (if less than 12) or 6+1.5\*, rounded up, except for level 19, which is rounded down. A `0` is suffixed to ensure that there are not too many spells. ``` ¬ΣES›ι§θκ ``` Compare the spell levels against the substring and prints a `-` if none of them are excessive. [Answer] # [Python 3](https://docs.python.org/3/), 98 bytes ``` v=lambda L,S:(max(S)*2-2<L)&v(L-1,[1]+sorted(S)[:(chr(L*3)in'$*069<')-2])if L>1else(1,1)==tuple(S) ``` [Try it Online!](https://tio.run/##hY7LCoMwEEX3/YpAS01sBBMfraJddpWd3YkLW1MUfBGjtF9vQ8RFQSh3ZjP33JnpP7LsWmeep7jOm0eRA4aTEDb5GybIpBaNGDpOkFkEpyQ7DZ2QvFBWGsJnKSAzHVS1xsG0/SAykEUzVL0AuxJeDxwSTFAcy7GvuYrMvahaCSc1BqlqkiEE9uAuRr5bLW@xqC4XA29hbrla9wMthKNLce4WR20FetjXOmtdtIJVGx/okP8/pE/NXw) Ungolfed: ``` def v(L, S): # recursion base case if L <= 1: return tuple(S) == (1, 1) # if the highest level skill is not valid for the level, then return False. if max(S)*2 - 2 < L: return False # hacky way to determine if the level gets a new skill has_new_skill = chr(L*3) in '$*069<' sorted_skills = sorted(S) # this step removes the highest skill and adds a level 1 skill (replacement) # if there is a new skill, then it removes the second highest skill as well new_skills = [1] + sorted_skills[:has_new_skill - 2] return v(L-1, new_skills) ``` *edit: corrected solution to use correct D&D rules* [Answer] # JavaScript (ES6), ~~79~~ 78 bytes Takes input as `(level)(array)`. Returns \$0\$ or \$1\$. ``` l=>a=>!a.some(x=>x>(j--,++l>30?9:l+(2<<l/25)>>2),j=l<12?l:l>16?14:l+11>>1)&!~j ``` [Try it online!](https://tio.run/##jY9BDoIwEEX3nqJuTBsKOIUSNXQ4iHHRKBjJSA2gceXVEcQYdWFM3vL9l5nSXmyzrQ@n1q/cLu8K05FBa3Bqg8Ydc341eEVe@r70PMJoni1X5HGVphQqLRCVkKWhFFRGK0JIMoh7AQARxGx6K7utqxpHeUBuzwsOgq9BMtgIwcKQtfU5n3wai6chmZIseqCfdmGp@db1Sx8XI9GPBQw39NX4Df1J0vNH4UfkrTD82N0B "JavaScript (Node.js) – Try It Online") ## Test code Below is a link to some test code that takes the sorcerer level as input and returns an array of maximum spell levels, using the same logic as the above function. [Try it online!](https://tio.run/##LY7NCsIwEITvfYq5NUs0NvEH1Lbi3ZtHEQnaiiUmJZaCT1@36mF3Z2eWj21sb1/X@Gi7qQ@3ahhqFBBugoanQw5tsGOx4SqhV7zoxXeT0Bole4SiTICTUmofo32LZszozJ562lZcfjkg5ciYZ8xY/xHCIM9ZzWCWNNIMX1KS1CEKzx/oLTzyAiZjISVxeg3@FVylXLiL9FD1lUM6kjy3dJOSau3t2NnYiTlNUAtPNAwf "JavaScript (Node.js) – Try It Online") ## How? ### Reference table ``` Sorcerer level | # of spells | Maximum spell levels ----------------+-------------+------------------------------- 1 | 2 | 1,1 2 | 3 | 1,1,1 3 | 4 | 1,1,2,2 4 | 5 | 1,2,2,2,2 5 | 6 | 2,2,2,2,3,3 6 | 7 | 2,2,2,3,3,3,3 7 | 8 | 2,2,3,3,3,3,4,4 8 | 9 | 2,3,3,3,3,4,4,4,4 9 | 10 | 3,3,3,3,4,4,4,4,5,5 10 | 11 | 3,3,3,4,4,4,4,5,5,5,5 11 | 12 | 3,3,4,4,4,4,5,5,5,5,6,6 12 | 12 | 3,4,4,4,4,5,5,5,5,6,6,6 13 | 13 | 4,4,4,4,5,5,5,5,6,6,6,7,7 14 | 13 | 4,4,4,5,5,5,5,6,6,6,7,7,7 15 | 14 | 4,4,5,5,5,5,6,6,6,7,7,7,8,8 16 | 14 | 4,5,5,5,5,6,6,6,7,7,7,8,8,8 17 | 15 | 5,5,5,5,6,6,6,7,7,7,8,8,8,9,9 18 | 15 | 5,5,5,6,6,6,7,7,7,8,8,8,9,9,9 19 | 15 | 5,5,6,6,6,7,7,7,8,8,8,9,9,9,9 20 | 15 | 5,6,6,6,7,7,7,8,8,8,9,9,9,9,9 ``` ### Number of spells For a sorcerer of level \$L\$, the number of spells \$N\_L\$ is given by: $$N\_L=\begin{cases} L+1&\text{if }L<12\\ \lfloor(L+13)/2\rfloor&\text{if }12\le L\le 16\\ 15&\text{if }L>16 \end{cases}$$ In the code, the variable \$j\$ is initialized to \$N\_L-1\$ and decremented at each iteration while walking through the input array. Therefore, we expect it to be equal to \$-1\$ at the end of the process. ### Maximum spell levels Given a sorcerer level \$L\$ and a spell index \$1\le i \le N\_L\$, the maximum level \$M\_{L,i}\$ of the \$i\$-th spell is given by: $$M\_{L,i}=\begin{cases} \lfloor(L+i+2)/4\rfloor&\text{if }L+i<25\\ \lfloor(L+i+4)/4\rfloor&\text{if }25\le L+i\le 30\\ 9&\text{if }L+i>30 \end{cases}$$ Each value \$x\$ of the input array \$a\$ is compared with this upper bound. [Answer] # [Groovy](http://groovy-lang.org/), 155 bytes ``` def f(int[]a, int b){l=[1] b.times{n->l[0]=++n%2?n/2+1:n/2 if(n<18&(n<12|n%2>0))l.add(l[0]) l.sort()} for(i=0;i<a.size();)if(a[i]>l[i++])return false true} ``` Generates the best possible spellbook, then checks that the spellbook passed into the method is not better. Ungolfed, with implicit types made explicit: ``` boolean spellChecker(int[] a, int b) { // l will be our best possible spellbook List<BigDecimal> l = [1] b.times { n -> n++ // iterate from 1 to b, not 0 to b-1 l[0] = n % 2 != 0 ? n / 2 + 1 : n / 2 // update the lowest value to the best permitted if (n < 18 & (n < 12 | n % 2 > 0)) l.add(l[0]) // if permitted, add another best spell l.sort() // ensure 0th position is always worst, ready for updating next loop } for (int i = 0; i < a.size(); i++) if (a[i] > l[i]) // if the submitted spell is of a higher level return false // also rejects when l[i] is undefined. (too many spells) return true } ``` [Try it online!](https://tio.run/##rVPLcoIwFN3nK66LtmSgKFjU1ken/9AdwyJKsMzE4CSRjrV@uw0PLdjouOjcM2Eg555z8mApsizfHg4xTSCxUq7CiDignzDHOzYNvQjNXZWuqNzxxxkLe9HUtvmd/8q7vu296BGlicUn3ui@GP1vPTfrYcxcEsdWwceIuTITysJ7lGTCSqe9cTohrky/qIXHWLeTMI20dmrbERZUbQSHhDBJkRIbuj@gMhbINWVMwhRCz9GxiJRUKB26@u6AhxFqcqCAgefjNs3XONE6l3nn1F9m/y/zgvc5s1/CaN83LaeKcOx7ciAwtY4wdLvwBozmlMEIFoQ/KNAvAj5IToEsFlRKUBmQmhNUu@tesSxcTWZByyyozc58hvXpNfWrBZwQtDHQMNl5Xun3nmWwInxb6cJmvRQkptK90WBwZtDQ982HeQXGmH4Zk2fA6WcdkihgOdNTzZCBMyhrWNaorOdjmW5vD9/a3ejvtASKZKq1gbKh@T@KpyNBqPqlDz8 "Groovy – Try It Online") ]
[Question] [ # CHALLENGE Given a set of grouped letters, arrange them onto the board so that they cover the area entirely. ## Board Representation (a.k.a. the SHIP DECK) * The board is a 6x6 grid. * There will always be 36 total squares. * Columns are marked A-F. * Rows are marked 1-6. Example: ``` A B C D E F +---+---+---+---+---+---+ 1 : : : : : : : +---+---+---+---+---+---+ 2 : : : : : : : +---+---+---+---+---+---+ 3 : : : : : : : +---+---+---+---+---+---+ 4 : : : : : : : +---+---+---+---+---+---+ 5 : : : : : : : +---+---+---+---+---+---+ 6 : : : : : : : +---+---+---+---+---+---+ ``` # INPUT (a.k.a. the CRATES) * A multiline string containing the set of grouped letters. * Crates are made from the groups of identical letters. * The crates are IMMUTABLE, meaning they can't be rotated or flipped. * The starting point for each crate is on the top left (should be taken into account when moving a crate onto the deck). * From the top left point of a crate, the following identical squares can only be to the right or below. * Any letter can be used to represent a crate. The crates always start at letter `[a]` and move up the alphabet. * Crates are labeled by their letter (i.e. crate A, crate B, etc.) * The number of crates can vary (it isn't always 10, despite the examples given). * There are 24 characters separating each block of crates per line. (start of [a] to start of [b] separated by 24 characters, etc.) Example: ``` [a][a][a] [b] [c][c] [a] [b][b][b] [c] [a] [b][b] [d] [e] [f][f][f][f][f] [d][d] [e] [d][d] [e] [e] [e][e] [g] [h] [i] [g] [i] [i] ``` # OUTPUT It is required that you print out a series of commands that place the crates in positions on the deck so that it is covered completely (no empty spaces). The command format is like so: `HAUL <crate> TO <column> <row>` i.e. HAUL E TO A 1 For clarification, there will always be a solution for the input given. # [TEST CASES](https://pastebin.com/raw/B9ZNWCwa) <-- Click for more. ## Input ``` [a][a][a] [b] [c][c][c] [a][a] [b] [a] [b][b] [b][b] [d] [e] [f] [d] [f] [d] [f] [d] [d] [g][g] [h] [i] [i][i] [i] [i][i] [j][j][j] ``` ## Output ``` HAUL I TO A 1 HAUL B TO A 3 HAUL A TO B 1 HAUL J TO D 6 HAUL D TO F 1 HAUL F TO E 1 HAUL C TO C 5 HAUL G TO D 4 HAUL E TO D 3 HAUL H TO C 6 ``` Result: ``` A B C D E F +---+---+---+---+---+---+ 1 : i : a : a : a : f : d : +---+---+---+---+---+---+ 2 : i : i : a : a : f : d : +---+---+---+---+---+---+ 3 : b : i : a : e : f : d : +---+---+---+---+---+---+ 4 : b : i : i : g : g : d : +---+---+---+---+---+---+ 5 : b : b : c : c : c : d : +---+---+---+---+---+---+ 6 : b : b : h : j : j : j : +---+---+---+---+---+---+ ``` # SCORING This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in characters wins. [Answer] # Python 3.6, ~~435~~ ~~437~~ ~~385~~ 331 bytes Call `F()` with the crate string. ``` def R(b,d,i=0): if not d:return 1 (k,x),*d=d while x: if x&b<1and R(b|x,d):print(f'HAUL {k.upper()} TO {i%7+65:c} {i//7+1}');return 1 i+=1;x>>=1 def F(t,d={},e={}): r=c=0 for a in t: if'`'<a<'{':e[a]=x,y=e.get(a,(r,c));d[a]=d.get(a,0)+(1<<(48-(r-x)*7-(c-y)//3)) elif'\n'==a:r+=1;c=-1 c+=1 R(4432676798719,d.items()) ``` Managed to golf it a lot more: 1. Parse the crate string directly instead of using the `re` library. 2. Used setdefault to save the first coordinate of a set of crates, so that the bitmask can be created when parsing the crate string. Eliminating a for loop. Prior version ``` import re def R(b,d,i=0): if not d:return 1 (k,x),*d=d while x: if not x&b and R(b|x,d):print(f'HAUL {k.upper()} TO {i%7+65:c} {i//7+1}');return 1 i+=1;x>>=1 def F(t,d={},n=0): for r in t.split('\n'): for m in re.finditer(r'(.)]',r):d[m[1]]=d.get(m[1],[])+[(n,m.start())] n+=1 R(4432676798719,[(k,sum(1<<(48-(r-v[0][0])*7-(c-v[0][1])//3)for r,c in v))for k,v in d.items()]) ``` Restructured the code to remove redundant loops. 1. Previous code built a list of all positions of a crate in `F()` and then iterated over the list in `R()`. New code creates one position of a crate in `F()` and `R()` tries all possible positions. 2. In previous code, `R()` collected a possible solution in `a` and `F()` then iterated over the returned solution. In new code, `R()` prints the HAUL commands directly Previous version ``` import re def R(b,d,a=[]): if not d:yield a for x in d[0]: if not x&b:yield from R(b|x,d[1:],a+[x]) def F(t,d={},n=0): for r in t.split('\n'): for m in re.finditer(r'(.)]',r):d[m[1]]=d.get(m[1],[])+[(n,m.start())] n+=1 for k,j in enumerate(next(R(4432676798719,[[sum(1<<(48-(r-v[0][0])*7-(c-v[0][1])//3)for r,c in v)>>i for i in range(48)]for k,v in d.items()]))):x=51-len(bin(j));print(f'HAUL {k+65:c} TO {x%7+65:c} {x//7+1}') ``` ### Explanation The basic idea is to represent the ship's deck and the crates as bit maps. By using bitmaps, moving a crate becomes a shift of its bitmap and checking for overlap between crates becomes a bit-wise AND and test for zero. Ungolfed code: ``` import re def F(crate_string): # 3 coords = {} row_no = 0 for row in crate_string.split('\n'): # 7 for match_obj in re.finditer('(.)]', row): # 9 crate_name = match_obj[1] # 11 col_no = match_obj.start() # 12 coords[crate_name] = coords.get(crate_name, []) + [(row_no, col_no)] # 13 row_no += 1 normed = {k:[(r-v[0][0], (c-v[0][1])//3) for r,c in v] for k,v in coords.items()} # 17 bitmaps = [(k,sum(1<<(48 - r*7 - c) for r,c in v)) for k,v in normed.items()] # 18 R(4432676798719, bitmaps) # 20 def R(used, bitmaps): # 22 if not bitmaps: # 23 return True # 24 shift = 0 # 25 (crate_name, crate_bitmap),*bitmaps = bitmaps # 26 while crate_bitmap: # 28 if not used & crate_bitmap: # 29 if R(used | crate_bitmap, bitmaps): # 30 print(f'HAUL {crate_name.upper()} TO {shift%7 + 65:c} {shift//7 + 1}') # 31 return True # 32 shift += 1 # 34 crate_bitmap >>= 1 # 35 return False # 37 ``` `F()` parses the crate definition string and builds the bit maps. A regex searches (line 9) each line of the crate definition string for crates (a letter followed by a ']'). When a match is found, the corresponding (row,col) is added to a dictionary keyed by the letter (lines 11-13). For the example crate definition string given in the problem: ``` coords = {'a': [(0, 5), (0, 8), (0, 11), (1, 5), (1, 8), (1, 11)], 'b': [(0, 29), (1, 29), (2, 29)], ... } ``` The coordinates of each crate are normalized (line 17), so that each crate starts at (0,0) and each block is one unit wide (instead of 3 a la '[a]'). ``` normed = {'a': [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)], 'b': [(0, 0), (1, 0), (2, 0)], ... } ``` A bitmap is then created for each crate based on the normalized coordinates (line 18). The deck is treated as a 7 x 7 grid. Column 'G' and row 7 are used to detect when a shape extends off the board. A bitmap has a 1 if the crates would occupy the corresponding square on the deck. Bits 48 to bit to 42 correspond to squares A1 to A7, bits 41 to 35 correspond to squares B1 to B7, and so on. ``` bitmaps = [('a', 0b1110000_1110000_0000000_0000000_0000000_0000000_0000000), ('b', 0b1000000_1000000_1000000_0000000_0000000_0000000_0000000), ... ] ``` `R(used, bitmaps)` then uses the bitmaps to recursively search for crate placements that don't try to put two crates in the same square. `used` is a bitmask indicating which squares can't be used because they are already occupied by a crate or because they are off the board (i.e., column G and row 7). `bitmaps` is a list of crates that still need to be placed. The base case for the recursion is when there are no more crates left to place, i.e., `bitmaps` is empty (line 23). In this case True is returned to indicate a solution has been found. Otherwise, a crate name and its bitmap are popped off the list of bitmaps (line 26). While the crate bitmap is not empty (line 28), check if the current crate placement, represented by the crate bitmap, conflicts with any previously placed crates. At line 29, `not used & crate_bitmap` is False if `used` and `crate_bitmap` both have a 1 in the same bit position, indicating a conflict. If there is not a conflict, `R()` is called recursively (line 30) to try and place the remaining crates. If the recursive call to `R()` returns True, it means that a solution has been found and that the current placement of the crates is part of that solution. So the corresponding command to move the crates is printed and True is propagated up the recursive calls (lines 31-32). When created in `F()`, each crate bitmap represents the deck squares that would be occupied by the crates if they are placed at position A1. Shifting a bitmap one bit to the right corresponds to moving the crates to position A2. A seven bit right shift corresponds to moving the crates to B1, etc. For example, the following bitmaps represent crates 'a' at various positions: ``` 0b1110000_1110000_0000000_0000000_0000000_0000000_0000000 represent crates 'a' at A1 0b0111000_0111000_0000000_0000000_0000000_0000000_0000000 represent crates 'a' at A2 0b0011100_0011100_0000000_0000000_0000000_0000000_0000000 represent crates 'a' at A3 ... 0b0000000_1110000_1110000_0000000_0000000_0000000_0000000 represent crates 'a' at B1 ... ``` If a possible placement of crates doesn't work because it conflicts with a previously placed crate (line 30) or because there is not a valid placement of the remaining crates (line 31). The crates are moved to a different position by shifting the bitmask right one bit (line 35). `Shift` keeps track of how many places the bit map has been shifted, which corresponds to the current position of the crates. If the bitmap is empty (zero), it indicates that all possible placement have been tried. False is returned (line 37) to indicate failure so that a call to `R()` earlier in the recursion will try another placement for its crates. To ensure that the crates don't extend off the side of the deck, bits corresponding to column G and row 7 are set in `used` for the initial call to `R()` (line 20). `4432676798719` is the empty deck corresponding to `0b0000001000000100000010000001000000100000011111111` [Answer] # [Python 2](https://docs.python.org/2/), 864 bytes * Thanks to [Stephen](https://codegolf.stackexchange.com/users/65836/stephen) for finding a bug. * The string parsing could be golfed significantly, as the input format is stricter than what it can handle. ``` def V(C,S=0,D=-1,J=0,H=[],E=enumerate,R=range,r=str.replace,s=str.split,e="!"): if[]<C*0: J=0;N=[J]*26;K=[] for c in s(r(r(r(C,"[",""),"]","")," ","*"),2*"\n"): c=[list(_)for _ in s(c,"\n")] for x,_ in E(c[0]): if all(c[y][x]<">"for y,_ in E(c)): for y,_ in E(c):c[y][x]=e for j,y in E(c): y="".join(y) while"!!"in y:y=r(y,2*e,e) c[j]=s(y,e) K+=[],[],[],[];J+=4 for y in c: while""in y:y.remove("") for j,x in E(y):K[j+J-4]+=x, for k in K: if all(k)and k:N[ord(k[0][0])-97]=[[x>"*"for x in y]for y in k] while 0in N:N.remove(0) C=N if[]>S:S=[0]*36 if-~D>0: Y=J/6;j=0 for y in C[D]: X=J%6 for x in y: if x: if X>5or Y>5or S[X+Y*6]:return S[X+Y*6]=x X+=1 Y+=1 if~-len(C)==D: if 0in S:return for h in H[1:]+[J]:print"HAUL %c TO %c %d"%(65+j,65+h%6,h/6+1);j+=1 j/0 for j in R(36):V(C,S[:],-~D,j,H*(D>=0)+[J]) ``` [Try it online!](https://tio.run/##3Zphb9o4GMdfN5/C9QkpgdACbdktnZEmQKroiUllN7WXsyoWTAnQgJJ0I2/21Xt2ktIVbIiJ2dprI0hs5xfz5Pnbj59kHoWjmVd7fByQIfiiN80eqpgtVK6aHbpzgWxsthHxHu6J3w@JeYX8vndHTB8FoX/kk/m07xAziI@C@dQNTYLgITQsDbhDG39oFiuWdkBR511kd3CxVj@/pEztYDjzgQNcDwS6H/83TWhDE0LDhDj9BgDQvSLdrRXhvx6jHgAH2VM3CPVbgyFuE4RjxvWUC1jpwozL27pjVzA768Adgv50So8jbC/wB9iArF20bGfErcBKoZW2RyQFj81oWUfbRwjCo/HM9fTIoIffR@6UwMNDSJtEVoR8PaI9JyZhlY49xiigJewIXJaYZZ@2804JnaaXiC/gWEtcCqO2vp99Izo1DK1K@rJI@hIZ1qU9LnXKp7iEFmZi2wmru2QGS3/6xOh7AzCxuvbMH@gTahhmm/L7dxjZ9qJBzRxbjp0W4WVHJtSkcT9AhR51re5TPyq0G03UTW5zo2f1EMUVT@qsoPyj1WC3/QZ1juvnY1RJuhQDm3YLs15do06h/nS74oumt2kR3wi6c904o3U38WfPvi7dFOvY8kn44HusxVMRWtCj6xKqUtgN@6Ln/ihPiac3DYRalEZZrPO95cnsmiN2zQu7auES9Utr7rteCC8@/v0XKDjg8yf2WRjAgl4/K41N@jEq1M3Rcb1UNc7H8cXGxxUt8QlGutJP6oYV68e2sEktYI7Ni6LeaqCKwa5gPDavPn5u926rVYAAhFCz@zjZwMs/@@tqSVru4GT7uVBjFTIU7l9K4VzzK84O0kQVchTNHggMQATlQ065kCLs5Cui8A2jhqLZd5hunK6PBOZ1scS9FhrGxesgbYcfoIyyAqKGGeNky2VfKm06qpSrWNNSxVeeBS@Sh0jwPC@QpAh86Q1QZP1aybAhdBiCRSBpSkbQRqly1Zp49YpvpxQRK7t9lciD9VIJJQEplurLuTn7TLY@MW8ZlyQozLG5vr3BsZNtdfaQoohvnxKKlFTF8uBj9j2TKZsPV6WqibRhT6RGVIFU5Sjr8qgpncmktLELZbltp6TyWPftzSLbn2PvNu6/9ALxuC9SyLp7bxzERhJBfe5Bf5Nj5x33T25392zOkK0mohFNQuriIm4sIreEkYtoXtNCSN1ySiQOrlz504dsaKaMwh83FCzKtPxy36fiT7cLfkOMtpqF2UzJuBx6zgjlkf1OCyFhvLg@Lb6VSO@VZRsyy4PGaNnDNEUiW5fHWa4kpWC5tj@KhMhElNeWbdgjZa8iy59qeKbkn5w3iiyjztTNZHuRav23hq5CSv7oVaFUZfMn/HAxf8SoCRdlanIWogWi5OSshCK/QBRJlV8@lTKMmLIOkqZImjdnFuadUsHvkIVRQOEmYnahSAqeq3npXI58Dp@bghHlchRIVRlFQQDMp0gLPqs8/vwl8tg8H66w9v1MW3plt4NjZ6VI/a5tqU5u@oSTsthyT0ZZtfqKAr19hYvvtz/ieqPj/gaKxPpwl3wpZ/ZQEy6Knkqoy1GqCTr3SJEOXX855X84bKjM3aofwqqVTMnbdd0L36iRWmPKPYf8HZRdnmbyOyOiiOJo8SpeQMn6/EnaMEOsLsclF25kpfzk2Ow90pC9Rxq/Xa1Xa@z14vidVADbC@I8hK53B0IShMDpBwT8URgcQVAAoXYQ@pEFCG0D4Bc9FUhhYKS1ZOGQeQj@If6s5X5zA3fmtX1/5lsgpc8@wWWrbv@ePNX2gyDtweN/ "Python 2 – Try It Online") # Explanation A lot of bytes are used to parse the two-dimensional crates inputted through a single string. Crates are represented as a nested list of boolean values. After the crates are parsed, the function considers all possible positions of all crates. To do so, it iteratively calls itself. When it finds an impossible position (if the crate would be placed outside the deck or on top of another crate), it kills the current recursion tree branch to improve performance. When it sees that a certain combination of placements resulted in a completely covered deck, it prints the recorded crate placement history and globally exits by attempting a hopeless division. The printed haul instructions are even sorted alphabetically. --- # [Python 2](https://docs.python.org/2/), 812 bytes ``` def f(C,M=[],d=0,R=range,E=enumerate,L=len): if C*0=="": N=[0]*26;K=[];J=0 r=str.replace for c in r(r(r(C,"[",""),"]","")," ","*").split("\n\n"): c=[list(_)for _ in c.split("\n")] for x in R(L(c[0])): if all(c[y][x]=="*"for y in R(L(c))): for y in R(L(c)):c[y][x]="!" for j,y in E(c): y="".join(y) while"!!"in y:y=r(y,"!!","!") c[j]=y.split("!") for _ in"_"*L(c):K+=[], for y in c: for j,x in E(y):K[j+J]+=x, J+=L(c) for k in K: if all(k)and k:N[ord(k[0][0])-97]=[[x!="*"for x in y]for y in k] while 0in N:N.remove(0) C=N if d==L(C): j=0;S=[j]*36 for c,k in E(C): Y=M[c]/6 for y in k: X=M[c]%6 for x in y: if X<6>Y:S[X+Y*6]|=x X+=1 Y+=1 if 0in S:return for m in M:print"HAUL %c TO %c %d"%(65+j,65+m%6,1+m/6);j+=1 j/0 for j in R(36):f(C,M*(d>=0)+[j],d+1) ``` [Try it online!](https://tio.run/##rVRrb9owFP1MfoWxhGQnLoRWy7QwV6oQ00RbKkErgVwL0SSseRBQSDci7b@ze2NoO7Z9WxLZuT7nvo6dbKryeZ2f77/cPYzn/fHV/WAiKaWWWuiThxCiQg2PhW/G/hMzxsn15vdPzFJPdZSn39xVgKZlgL9jBvhPmLksEEB1/bOu3ofRkixZX9xKpUUoXTGWxSL/FomBjPKXVVQsykjcyCzKuW@ReEn6titBQN9qjKRytX3u9a7BtzeUrtUo5LYs2kW0yRZBZDWW64IEJM5JwfDuC6qooJQLqg8zFANvNuXt7SaLS0Yf88ecQqoGCaTK4m3J5hzDzDFM8MaiXAMHkR0iY3bDAiiHo2sDylxkGSxUWu00lGtTZFavTG545HTVP7rQJj2ET0RNGACMLhX03k7Wcc4qDuaP5ziLaLNJgVL5lSxYJdCEgSIeqETL6lh2vUaO7dA5tTGrf@2g@Na7cgJMZbLvTPYKaCpxhtqRO6QOHYm@RuMUOdco2qHzlC/ykKT@SK2LkKUgDGpz9umjlkrtmkdB6tiVfk2bgqZ1R8QFa@SPYCtX6@8RcyFRX47qAxBKyNxHMRLp9iYSOrQvvMNmi9SUW@NkJm/hMHa8962l2Nq0BlreoUtTR70jkGD62buc@RM1dWa2p3/KHa5PHdmFeVZPQMICJ34RlS9FbnKvMMitvynivKRfrx5uSCsg93c4tkLaYt4HJxEwrFqe6Dqrjsd7SR0t6biW2WpzEi487tefhM3CS@lyBzoUodPl@yV79xfh@18 "Python 2 – Try It Online") # Explanation The crate string is parsed and transformed into a listed nest of booleans representing each crate. An iterative function generates all possible lists of length equal to the amount of crates given containing the integers `0 <= x < 36` (all possible ship deck positions). Every list is interpreted as an instruction to position all crates and tested. If the tested instruction list results in a deck with no empty spaces, the instruction list has to be valid and gets printed. Being extremely inefficient, I did not test it on the provided test case, though on scenarios with fewer crates (see the TIO link). Because the algorithm searches through *every* possible arrangement, it tries to look at `36**10 = 3.656e15` of them. Yet *in theory* it should still work. [Answer] # JavaScript, 366 ``` k=>(x=y=0,C={},B=[...k].map((c,p)=>(c<' '?(x=0,++y):c<'a'?++x:(c=C[c=parseInt(c,36)]||(C[c]=[[],x,y]))[0].push((y-c[2])*7+(x++-c[1])/3),p<8|p>48|p%7<1)),S=[],R=i=>!C[i]||B.some((v,p)=>v?0:C[i][0].every(q=>B[q+=p]?0:B[q]=i)&&R(i+1,S[i-10]=p)||!C[i][0].map(q=>B[q+=p]==i?B[q]=0:0)),R(10),S.map((v,c)=>`HAUL ${(c+10).toString(36)} TO ${(v%7+9).toString(36)} ${v/7|0}`)) ``` Note: this function can parse a more compact input, as it does not care about spacing by 24 chars, and holes in crates are allowed. I think it could be golfed a little more, but now it's short and not too much slow, so I like it as is *Less golfed* ``` k=>( // input parsing var x = 0, y = 0, // current position C = []; // crates [...k].forEach( c => c < ' ' ? (x = 0, ++y) // found a newline, increment y, reset x : c < 'a' ? ++x // not a letter, increment x : ( // found a letter, update the crate c = parseInt(c,36), // letter to number (10..35) c = C[c], // current crate in c c || (C[c]=[[], x, y]), // if new crate, initialize it setting base position c[0].push((y - c[2])*7 + (x-c[1])/3) // add current position ++x // increment x also ) ); var B = [...Array(7*8)] // empty board. in golfed code I reuse k to build B. k is big enough B = B.map( (_, p) => // set borders p < 8 | p > 48 | p%7<1 ) var S = [] // output steps // recursive function to fill board var R = i => ! C[i] // if crate at position i exists (else, we have found a solution and return true) || B.some( (v,p) => // try to put crate at each position in B v // current cell is used already ? ? 0 // used, return false : C[i][0].every( q => // try this position, must place every part B[q+=p] // current position in B is used ? ? 0 // used, stop, return false : B[q]=i // mark as used ) && R(i+1,S[i-10]=p) // ok for current crate, try next, mark step || // else, fail for current crate, clear position marked !C[i][0].map(q => B[q+=p]==i ? B[q]=0:0 // clear if it was set to 'i' ) ), R(10) // start recursive fill at position 10 (that is 'a') // it returns true if ok, but we don't care as we are assured a solution exists // now just format output return S.map((v,c)=>`HAUL ${(c+10).toString(36)} TO ${(v%7+9).toString(36)} ${v/7|0}`) ) ``` **Test cases** lots of them ``` var F= k=>(x=y=0,C={},B=[...k].map((c,p)=>(c<' '?(x=0,++y):c<'a'?++x:(c=C[c=parseInt(c,36)]||(C[c]=[[],x,y]))[0].push((y-c[2])*7+(x++-c[1])/3),p<8|p>48|p%7<1)),S=[],R=i=>!C[i]||B.some((v,p)=>v?0:C[i][0].every(q=>B[q+=p]?0:B[q]=i)&&R(i+1,S[i-10]=p)||!C[i][0].map(q=>B[q+=p]==i?B[q]=0:0)),R(10), // Just for debug: return the fill in addition to the steps [B.slice(7,50).map((c,i)=>i%7?c.toString(36):'\n'), S.map((v,c)=>`HAUL ${(c+10).toString(36)} TO ${(v%7+9).toString(36)} ${v/7|0}`)]) var Test = [ "[a][a][a] [b] [c][c]\n [a] [b][b][b] [c]\n [a] [b][b]\n\n[d] [e] [f][f][f][f][f]\n[d][d] [e]\n[d][d] [e]\n [e]\n [e][e]\n\n[g] [h] [i]\n[g] [i]\n [i]" ,"[a][a][a] [b] [c][c][c]\n [a][a] [b]\n [a] [b][b]\n [b][b]\n\n[d] [e] [f]\n[d] [f]\n[d] [f]\n[d]\n[d]\n\n[g][g] [h] [i]\n [i][i]\n [i]\n [i][i]\n\n[j][j][j]" ,"[a] [b][b][b] [c]\n[a] [b]\n[d] [e] [f][f]\n[d] [e]\n[d][d][d]\n[g] [h] [i]\n[g] [h][h][h] [i]\n [h] [i][i]\n [h] [i]\n [i]\n[j] [k][k][k]\n[j]\n[j]" ,"[a][a][a][a] [b][b][b] [c]\n [b] [c]\n [b] [c][c]\n [c][c]\n[d] [e] [f]\n[d] [f][f][f]\n[g] [h] [i][i]\n [h][h][h] [i][i]\n [h][h]\n[j]\n[j]\n[j]" ,"[a] [b] [c][c]\n[a] [b]\n[a]\n[d][d] [e] [f][f][f]\n[d][d][d]\n[g] [h] [i]\n [h]\n [h]\n [h][h]\n [h]\n[j] [k][k][k]\n[j][j] [k][k]\n[j][j][j] [k]" ,"[a] [b][b][b] [c]\n[a] [c]\n [c]\n[d][d] [e] [f]\n[d][d][d][d] [e] [f]\n [e][e][e][e] [f]\n[g] [h][h][h] [i][i][i]\n [h] [i][i][i]\n[j][j]" ,"[a] [b] [c][c][c]\n [b]\n[d] [e][e] [f][f]\n[d][d][d] [f][f]\n[d][d]\n[g] [h][h][h] [i]\n[g] [h] [i][i]\n[g] [h] [i][i]\n[g]\n[g]\n[j]\n[j]\n[j]" ,"[a][a] [b] [c]\n [a][a] [b][b] [c]\n [b][b][b] [c]\n[d] [e][e][e] [f][f][f]\n[d] [e][e][e]\n[g][g] [h] [i]\n [i]\n [i][i]\n[j][j]\n [j]\n [j]\n [j]" ,"[a][a] [b] [c]\n[a][a] [b][b] [c]\n [b][b][b]\n[d][d] [e] [f][f][f]\n[g] [h] [i][i]\n[g] [h] [i]\n[g] [h]\n[g]\n[g][g]\n[j]\n[j]\n[j]\n[j][j]\n [j]" ,"[a] [b] [c][c][c][c][c]\n [b]\n [b][b][b]\n [b]\n[d] [e] [f][f][f]\n [e]\n [e]\n [e][e][e]\n[g] [h] [i]\n[g] [h]\n[g] [h]\n [h]\n[j][j] [k]\n[j][j] [k]" ,"[a] [b] [c]\n [c]\n [c]\n[d][d][d] [e] [f]\n [e][e][e] [f]\n [f][f][f]\n [f]\n[g][g][g] [h][h] [i]\n[g][g][g] [i][i]\n [i][i]\n[j] [k]\n[j] [k]\n[j]" ,"[a][a] [b] [c]\n [b] [c][c][c]\n [b] [c]\n [b][b] [c]\n [b]\n[d] [e] [f]\n[d]\n[g] [h] [i]\n[g][g][g] [h] [i]\n [h][h][h] [i]\n [h]\n[j][j][j] [k][k]" ,"[a][a] [b][b][b] [c]\n [b][b][b]\n[d] [e] [f]\n[d] [e] [f]\n [e] [f]\n [e][e]\n [e]\n[g][g][g] [h][h] [i]\n [h][h] [i]\n [h][h] [i][i]\n [i]\n [i]\n[j]" ,"[a][a][a] [b][b] [c][c]\n [b][b] [c][c]\n [b][b] [c][c]\n[d][d] [e] [f][f]\n [d] [e]\n [e]\n [e]\n [e]\n[g] [h] [i][i]\n[g] [i][i]\n[g]\n[g]\n[g][g]" ,"[a][a][a] [b] [c]\n [a] [c]\n [a]\n[d] [e][e][e] [f][f]\n[d]\n[g] [h][h] [i]\n[g][g][g] [h][h] [i]\n [g][g] [i]\n[j] [k]\n[j] [k]\n[j][j]\n [j]\n [j]" ,"[a][a] [b] [c][c]\n [b][b]\n [b][b][b]\n[d] [e][e][e] [f][f]\n [e][e][e] [f][f][f]\n[g] [h] [i][i]\n[g] [h] [i][i]\n[g] [i][i]\n[j][j][j]" ,"[a][a] [b][b][b] [c]\n [a] [b][b]\n [a][a][a]\n[d][d] [e] [f]\n[d][d] [e][e] [f][f][f]\n [e][e]\n [e]\n[g][g][g] [h] [i]\n [i]\n [i]\n [i]\n[j][j]" ,"[a] [b][b] [c]\n[a] [c]\n[a]\n[a][a][a]\n[d] [e][e][e][e] [f]\n[d] [f]\n [f]\n[g] [h] [i]\n[g] [h][h]\n[g] [h][h][h]\n[g]\n[g][g]\n[j] [k][k]\n [k]" ,"[a] [b][b] [c]\n[a] [b][b][b] [c]\n[a][a][a][a] [c]\n[d][d][d] [e] [f]\n [d][d] [e]\n[g] [h] [i]\n [h] [i]\n [h]\n [h]\n [h][h]\n[j][j][j][j][j]" ,"[a][a] [b][b] [c]\n [a][a][a]\n [a]\n[d] [e][e][e] [f][f]\n[d]\n[g] [h][h] [i]\n[g] [h][h]\n[g] [h][h]\n[g]\n[j] [k]\n[j][j] [k][k]\n [k][k]\n [k]" ,"[a][a][a] [b] [c]\n [c]\n [c][c][c][c]\n[d] [e][e][e] [f][f][f]\n[d] [e][e][e] [f][f][f]\n[d]\n[g] [h][h] [i][i]\n[g] [i][i]\n[j]\n[j]\n[j]" ,"[a] [b] [c][c]\n [b] [c][c]\n [b]\n[d][d][d] [e] [f]\n [d] [f]\n [f]\n[g] [h] [i]\n[g] [h][h][h] [i][i]\n [h][h] [i][i][i]\n[j] [k] [l][l][l][l]" ,"[a] [b] [c]\n[a][a] [b]\n[a][a]\n[d] [e] [f]\n[d] [e]\n[d] [e][e][e]\n[d] [e]\n[g] [h][h][h] [i][i]\n[g][g]\n[j][j][j] [k]\n[j][j][j] [k]\n [k]" ,"[a] [b] [c][c]\n[a][a][a] [b] [c][c]\n [a][a] [b]\n [b]\n [b][b]\n[d] [e] [f]\n[d] [e]\n[d]\n[g] [h][h][h][h] [i]\n[j][j] [k]\n [k]\n [k][k]\n [k]\n [k]" ,"[a] [b][b][b] [c]\n[a] [b][b][b] [c][c][c]\n[a]\n[d] [e] [f][f][f][f]\n [e]\n [e]\n [e]\n [e]\n[g] [h] [i]\n [h][h] [i]\n [h][h] [i][i][i]\n [i]\n[j]" ,"[a][a][a] [b] [c]\n [b] [c]\n [b][b][b]\n [b]\n[d][d][d] [e][e] [f]\n [e][e] [f]\n [f]\n [f][f][f]\n[g] [h] [i]\n[g] [i]\n[g] [i]\n [i]\n [i][i]\n[j][j]" ,"[a] [b] [c]\n[a] [b]\n[a][a] [b]\n[d] [e][e][e] [f]\n[d] [e] [f]\n [e] [f]\n [e] [f][f]\n [f]\n[g][g] [h] [i]\n [i]\n[j][j][j] [k]\n [k][k][k]\n [k][k]" ,"[a][a][a] [b][b] [c]\n [b] [c]\n[d] [e][e] [f]\n[d] [f]\n[d][d]\n [d][d]\n[g] [h] [i]\n [h]\n [h]\n[j][j] [k] [l]\n[j][j][j] [k] [l][l][l]\n [j] [k]" ,"[a][a] [b] [c][c][c]\n[d] [e][e] [f][f]\n[d] [e][e] [f][f]\n[d]\n[d]\n[g] [h][h][h] [i]\n[g] [i]\n[g]\n[g][g][g]\n[j] [k]\n[j]\n[j][j][j][j]" ,"[a][a][a] [b][b] [c]\n[d] [e] [f]\n[d][d][d] [f][f][f][f]\n[d][d] [f]\n[g][g] [h][h][h] [i]\n [i]\n [i]\n[j] [k] [l]\n[j] [l]\n [l][l]\n [l][l]" ,"[a][a][a] [b] [c]\n [b] [c]\n [c]\n[d][d] [e][e] [f]\n [d]\n [d]\n [d]\n[g] [h] [i][i]\n[g][g] [h] [i][i][i]\n [h][h][h] [i]\n [h]\n[j][j] [k]\n[j][j]" ,"[a] [b][b][b] [c]\n[a] [b] [c]\n[a][a] [b] [c]\n [a][a]\n[d] [e][e][e] [f][f]\n[d][d][d] [f][f]\n [d][d]\n[g] [h] [i][i]\n[j] [k]\n[j] [k][k]" ,"[a] [b] [c]\n [c]\n [c][c]\n [c][c]\n[d][d][d][d][d] [e] [f][f]\n [f][f]\n[g] [h] [i][i]\n[g] [h][h] [i][i]\n[g] [i][i]\n[g]\n[g]\n[j][j]\n[j][j]" ,"[a] [b][b] [c][c]\n [b] [c][c]\n [b]\n[d][d] [e][e] [f]\n[d][d][d] [e][e][e]\n[g] [h] [i]\n[g] [h]\n[g][g][g][g] [h]\n [h]\n [h]\n[j][j][j][j]" ,"[a] [b][b][b] [c][c][c]\n[a] [b][b]\n[a]\n[a][a]\n [a]\n[d] [e] [f]\n[d] [f]\n[d] [f]\n[g] [h] [i][i]\n[g][g] [h] [i][i]\n[g][g][g]\n[j] [k][k]" ,"[a] [b][b] [c]\n[a] [b][b]\n [b][b]\n[d] [e] [f][f][f]\n[d][d][d]\n[d][d]\n[g] [h] [i][i]\n[g] [h]\n[g]\n[j][j][j] [k]\n [j] [k]\n [k]\n [k][k]\n [k]" ,"[a][a][a] [b] [c]\n [a][a]\n[d][d][d] [e] [f][f]\n [e]\n[g] [h] [i]\n[g][g] [h] [i]\n[g][g][g] [h] [i]\n[j] [k][k]\n[j][j] [k][k][k]\n[j][j]" ,"[a][a][a] [b] [c][c][c][c][c]\n [a][a] [b]\n [a] [b]\n [b]\n[d] [e] [f]\n[d][d] [f]\n[d][d][d] [f]\n[g] [h][h] [i][i][i]\n [h][h] [i][i][i]" ,"[a][a] [b] [c]\n [b]\n [b]\n[d][d][d] [e] [f]\n [f]\n [f]\n [f]\n[g][g][g] [h][h] [i]\n[g][g][g] [h][h] [i][i]\n [i][i][i]\n[j][j][j]\n [j][j]\n [j]" ,"[a] [b] [c]\n[a] [c]\n[a] [c]\n[a] [c][c][c]\n[a][a]\n[d] [e] [f]\n [e]\n [e]\n[g][g] [h][h] [i][i][i]\n[g][g]\n[g][g]\n[j] [k][k][k]\n[j]\n[j]\n[j]" ,"[a][a][a] [b] [c]\n [a][a] [b][b] [c]\n [a] [b][b][b] [c]\n [c]\n[d] [e][e][e] [f]\n[d][d][d]\n[d][d]\n[g] [h] [i][i]\n [i][i]\n[j] [k][k]\n[j]" ,"[a] [b][b] [c]\n [c]\n [c][c]\n [c][c]\n[d] [e][e][e] [f][f]\n[d][d][d] [f][f]\n [f]\n[g] [h] [i]\n [i][i]\n [i][i]\n [i]\n[j] [k] [l][l]\n[j]\n[j]\n[j]" ,"[a] [b] [c][c][c]\n[a] [b] [c][c]\n[a] [b]\n[a]\n[a][a]\n[d] [e] [f][f]\n [e][e]\n [e][e]\n [e]\n[g] [h] [i][i]\n [i][i]\n [i][i]\n[j] [k][k][k]\n[j]" ,"[a][a][a] [b] [c]\n [c]\n [c]\n [c][c]\n [c]\n[d][d][d] [e] [f]\n [d] [f]\n [f]\n[g][g] [h] [i]\n [h] [i][i][i]\n [i][i]\n[j][j] [k]\n[j][j] [k]\n[j][j]" ,"[a][a] [b][b] [c][c]\n [b][b]\n [b]\n[d] [e][e][e] [f]\n[d] [e][e][e] [f]\n[d][d]\n [d][d]\n[g][g][g] [h] [i]\n [h] [i][i]\n [h]\n[j] [k]\n [k]\n [k]" ,"[a][a][a] [b][b] [c]\n [a] [c][c][c]\n [c][c]\n[d] [e] [f]\n [f]\n [f]\n [f]\n[g] [h][h] [i][i][i]\n[g] [h][h]\n[g] [h][h]\n[g][g][g]\n[j][j][j]" ,"[a][a] [b][b] [c][c][c][c][c]\n[a][a][a] [b]\n[d] [e][e][e] [f]\n[d] [e][e][e] [f]\n[d][d][d][d] [f]\n [f]\n [f]\n[g] [h]\n [h]\n [h]\n [h]\n [h]" ,"[a] [b][b] [c]\n[a] [c]\n[a] [c]\n[a] [c]\n[a]\n[d] [e] [f]\n[g] [h][h][h][h] [i][i][i]\n[g] [i][i][i]\n[g][g][g][g]\n[j][j]\n[j][j][j][j]" ,"[a] [b] [c]\n [b][b]\n [b][b][b]\n[d][d][d] [e] [f][f]\n [d][d] [e] [f][f]\n [d] [e]\n [e]\n[g][g] [h] [i][i][i]\n [h] [i][i][i]\n [h]\n[j][j][j]" ,"[a][a] [b][b] [c]\n [c]\n [c]\n [c]\n [c][c]\n[d] [e] [f][f][f]\n [e]\n [e]\n [e][e][e]\n[g][g] [h] [i]\n [h][h][h] [i]\n [h][h] [i]\n[j] [k]\n [k]\n [k]\n [k]" ,"[a] [b] [c][c][c][c][c]\n[a]\n[a][a][a][a]\n[d][d] [e] [f]\n[d][d]\n[g] [h][h] [i]\n[g] [h][h][h] [i]\n[j] [k]\n[j] [k]\n[j] [k]\n [k][k]\n [k]" ,"[a] [b] [c]\n[a][a] [b]\n [b]\n [b][b]\n [b]\n[d] [e] [f][f][f]\n[d] [e] [f][f][f]\n [e]\n[g] [h] [i]\n [h] [i]\n [h] [i][i][i]\n [i]\n[j][j][j][j][j]" ,"[a] [b] [c][c]\n [b] [c][c]\n [b]\n [b]\n[d][d] [e][e][e] [f][f]\n[d][d]\n[g] [h][h] [i][i]\n [h][h] [i][i]\n [h][h]\n[j] [k]\n [k]\n [k][k][k]\n [k]" ,"[a][a] [b][b] [c]\n [a][a] [b] [c]\n [a] [b] [c]\n [b] [c]\n[d] [e] [f]\n [f][f]\n [f][f][f]\n[g][g] [h][h][h] [i]\n[j][j] [k][k]\n [k][k][k][k]" ,"[a] [b] [c]\n [c]\n [c]\n [c][c]\n [c]\n[d] [e][e] [f][f]\n [e][e][e]\n [e]\n[g] [h] [i][i][i]\n [h]\n [h]\n [h]\n [h]\n[j][j] [k] [l]\n [k] [l]\n [l][l]\n [l][l]" ,"[a][a] [b] [c]\n [a] [c][c]\n [a] [c]\n [a] [c]\n [a] [c]\n[d] [e] [f]\n[d] [f]\n[d][d] [f]\n [d] [f]\n [d]\n[g][g][g] [h][h] [i]\n [i]\n [i]\n [i]\n [i][i]\n[j]" ,"[a] [b] [c][c]\n [b]\n [b]\n[d] [e][e] [f]\n[d][d][d] [e] [f][f]\n[d][d] [f][f][f]\n[g][g][g] [h][h][h] [i][i]\n [h][h] [i][i]\n[j] [k]\n[j]" ,"[a][a][a] [b][b] [c]\n [b] [c][c][c]\n [c][c]\n[d] [e][e] [f][f]\n[d] [f][f]\n[g] [h] [i][i][i][i]\n[g][g] [h] [i][i]\n[g][g][g] [h]\n[j]" ,"[a][a][a] [b] [c]\n [c]\n [c][c]\n [c][c]\n[d] [e] [f]\n[d][d][d] [e] [f]\n [f][f]\n [f][f]\n[g] [h] [i][i]\n[g] [h]\n[g] [h]\n[j][j][j]\n[j][j]\n [j]" ,"[a] [b] [c]\n [b] [c][c][c][c]\n [b] [c]\n[d][d] [e][e][e] [f]\n[d][d][d][d]\n[g] [h] [i][i][i]\n[g] [h]\n[g]\n[j][j] [k]\n [k]\n [k][k][k]\n [k]" ,"[a] [b] [c]\n[a] [c]\n[a] [c]\n[a][a]\n [a]\n[d] [e][e] [f][f]\n[g][g] [h][h][h] [i]\n[g][g] [i]\n [g]\n[j] [k] [l]\n[j] [k] [l]\n[j][j] [k]\n [j][j]" ,"[a] [b] [c][c]\n [b] [c][c]\n [b] [c][c]\n [b]\n [b][b]\n[d][d][d][d] [e] [f]\n [e][e]\n [e][e]\n [e]\n[g] [h] [i]\n [h]\n [h]\n [h]\n[j] [k] [l][l]\n [l][l]" ,"[a] [b][b][b] [c]\n[a][a] [b] [c]\n[a][a] [b] [c]\n [c][c][c]\n[d][d] [e] [f]\n [e] [f][f][f]\n [f][f]\n[g] [h][h][h] [i]\n[g]\n[g]\n[j][j][j]" ,"[a][a] [b][b][b] [c]\n [b] [c]\n[d] [e] [f][f][f][f]\n[d][d][d][d][d]\n[g] [h] [i]\n[g] [h][h][h] [i]\n[g][g][g] [h][h] [i]\n [g]\n[j] [k]" ,"[a] [b][b][b][b] [c]\n[a][a][a] [c]\n [a][a] [c]\n[d] [e] [f]\n[d] [f]\n[g][g][g] [h] [i][i]\n [g] [i][i]\n[j] [k]\n[j] [k]\n[j][j] [k]\n [j]\n [j]" ,"[a][a][a] [b] [c][c][c]\n [a][a] [b] [c][c][c]\n [a] [b]\n[d] [e][e][e][e] [f]\n[d]\n[d]\n[d][d]\n [d]\n[g] [h] [i]\n[g]\n[j]\n[j][j]\n[j][j][j]" ,"[a][a][a] [b] [c]\n [b]\n [b]\n[d] [e] [f]\n[d] [e] [f][f]\n[d]\n[d][d][d]\n[g] [h] [i][i][i][i]\n[j] [k][k]\n[j][j] [k][k]\n[j][j][j] [k]\n [k]" ,"[a][a] [b][b][b] [c]\n[a][a] [c][c]\n [c][c][c]\n[d] [e][e] [f]\n [f]\n [f]\n [f]\n[g] [h] [i][i]\n[g][g] [h] [i]\n [h]\n[j][j] [k]\n [j][j]\n [j]\n [j]" ,"[a] [b] [c][c][c][c][c]\n[a] [b]\n[a]\n[d][d][d] [e] [f]\n[d][d][d] [e] [f]\n [e][e] [f]\n [e][e] [f]\n [f][f]\n[g] [h] [i][i]\n [i][i]\n [i][i]" ,"[a] [b] [c]\n[a] [b]\n[a] [b][b]\n[a] [b][b]\n[d][d][d][d] [e] [f][f]\n [f][f]\n[g][g] [h] [i][i]\n[g][g] [h][h][h] [i][i]\n [g][g] [i]\n[j]" ,"[a] [b][b][b] [c]\n[a][a][a] [b]\n[a][a] [b]\n[d][d][d] [e] [f]\n [e][e][e]\n [e][e]\n[g][g] [h] [i]\n [h] [i]\n [h]\n[j] [k][k]\n[j] [k][k]\n[j]" ,"[a][a] [b][b][b][b] [c]\n [a][a] [c]\n [a][a]\n[d] [e] [f]\n[d]\n[d][d]\n [d]\n [d]\n[g][g] [h] [i]\n[g][g] [i]\n[j] [k]\n[j] [k][k]\n[j] [k]\n [k]\n [k]" ,"[a][a] [b] [c]\n [b] [c]\n [b]\n[d][d][d] [e] [f]\n[d][d][d] [e] [f][f]\n [e] [f][f][f]\n[g] [h] [i]\n [h] [i]\n [i][i]\n [i]\n [i]\n[j] [k] [l][l][l]" ,"[a] [b] [c]\n [c]\n [c]\n[d] [e][e][e] [f]\n [f]\n [f]\n [f][f][f]\n[g] [h][h][h][h] [i]\n[g] [i][i]\n [i][i][i]\n[j][j] [k][k]\n[j][j] [k][k]\n [k]" ,"[a][a][a] [b] [c]\n [b][b][b][b] [c]\n [b] [c]\n[d] [e][e][e] [f][f]\n[d] [e][e][e]\n[d][d][d][d]\n[g][g] [h] [i]\n[g][g] [h]\n[j][j][j]" ,"[a] [b][b][b] [c]\n[a] [b] [c]\n[a] [c][c][c]\n [c]\n[d][d] [e][e][e][e] [f]\n[d][d]\n[g] [h] [i]\n [h][h][h] [i]\n [h][h]\n[j] [k][k]\n [k][k]" ,"[a][a][a] [b] [c][c][c]\n [c]\n[d] [e] [f]\n[d] [f][f][f]\n[d] [f][f]\n[g] [h][h] [i]\n [h][h] [i]\n [i]\n[j] [k] [l][l]\n[j] [k][k][k]\n [k][k]" ,"[a] [b] [c]\n[a] [b][b]\n[a] [b][b][b]\n[a]\n[d] [e] [f][f][f]\n[d][d] [e] [f][f]\n[d][d] [e]\n [d] [e]\n[g][g] [h] [i]\n[j] [k][k][k]\n[j][j]" ,"[a][a][a][a][a] [b] [c][c]\n [c][c]\n[d][d][d] [e] [f][f]\n[d][d][d] [f]\n [f]\n[g] [h][h] [i]\n[g] [h][h][h] [i]\n[g][g][g][g] [i]\n [i]" ,"[a][a] [b] [c][c][c]\n [b]\n [b]\n [b][b]\n [b]\n[d] [e][e] [f]\n[d]\n[d]\n[d]\n[g][g] [h] [i]\n [g] [i]\n [g] [i][i]\n [i]\n [i]\n[j] [k]\n [k][k]\n [k]\n [k][k]" ,"[a][a] [b] [c][c]\n[a][a][a] [b][b]\n [a]\n[d] [e] [f]\n[d] [e] [f]\n[d][d][d] [e]\n [d]\n[g] [h][h][h] [i][i][i]\n [i][i][i]\n[j][j]\n [j]\n [j]" ,"[a][a][a][a] [b] [c]\n [c][c]\n [c][c][c]\n[d][d][d] [e][e][e] [f]\n [e][e] [f]\n [f]\n[g] [h] [i]\n[g] [h] [i]\n [h] [i]\n [h] [i][i][i]\n [h]\n[j]" ,"[a] [b] [c][c][c]\n[a] [b]\n[a][a] [b][b]\n [b][b]\n[d][d] [e] [f]\n [d][d] [e][e]\n [d] [e]\n [d] [e]\n [e]\n[g][g] [h] [i]\n [h]\n [h]\n [h]\n [h]\n[j][j]" ,"[a] [b][b][b][b] [c]\n[a]\n[a][a][a][a]\n[d] [e] [f]\n[d] [e] [f]\n [e] [f]\n[g][g][g] [h][h][h] [i][i]\n[g][g][g] [h][h][h] [i][i]\n[j]" ,"[a] [b][b][b][b] [c]\n[a][a] [b][b]\n[a][a][a]\n[d] [e][e] [f][f]\n[d] [e][e] [f]\n[d]\n[d]\n[g][g][g] [h] [i]\n [h][h][h]\n [h][h]\n[j][j]" ,"[a][a] [b] [c][c][c][c][c]\n[a][a][a]\n[d][d][d] [e] [f][f]\n [d]\n [d]\n[g] [h] [i]\n[g][g][g] [h] [i]\n [g][g] [i]\n[j]\n[j]\n[j][j]\n[j][j]" ,"[a][a][a] [b] [c]\n [b][b][b] [c]\n [b][b] [c]\n [c]\n [c]\n[d][d] [e] [f][f]\n [f][f]\n[g][g][g] [h] [i]\n [g] [i][i]\n [g][g] [i][i][i]\n[j]\n[j]" ,"[a] [b][b] [c]\n[d] [e] [f]\n[d]\n[g][g] [h][h] [i]\n[g][g][g] [i]\n [g] [i][i]\n [i][i]\n[j][j][j] [k] [l]\n [k] [l]\n [k] [l]\n [l][l]\n [l]\n[m]\n[m]" ,"[a] [b] [c]\n [b] [c]\n [b][b]\n [b][b]\n[d][d][d][d][d] [e] [f][f][f]\n [f][f][f]\n[g] [h] [i][i]\n[g] [h][h] [i][i]\n[g] [i][i]\n[j]\n[j]\n[j]" ,"[a] [b][b][b] [c]\n[a][a] [b] [c]\n[a][a][a] [b][b] [c]\n[d][d] [e] [f]\n [f][f][f]\n [f][f]\n[g][g][g] [h] [i]\n [h] [i]\n[j][j] [k]\n[j][j]" ,"[a][a][a] [b][b][b] [c]\n [a] [b][b][b] [c]\n [a]\n[d] [e] [f]\n[d] [e][e][e] [f]\n[d] [e][e]\n[g] [h] [i][i][i]\n[g]\n[g][g]\n [g]\n [g]\n[j][j]" ,"[a] [b] [c][c][c][c]\n[a][a] [b]\n [a] [b]\n [a][a]\n[d] [e] [f]\n [e]\n [e][e]\n [e]\n [e]\n[g][g] [h] [i]\n [h] [i]\n[j] [k] [l][l]\n [k] [l][l]\n [l][l]" ,"[a] [b] [c]\n[d] [e] [f]\n[d][d] [e] [f]\n [d][d] [e][e] [f]\n [d] [e][e]\n[g] [h] [i][i][i][i]\n[g] [h]\n[j][j][j] [k]\n [j][j] [k][k][k]\n [j]" ,"[a] [b] [c]\n[a]\n[a]\n[a]\n[d] [e][e][e][e] [f][f]\n [f][f]\n[g][g][g] [h] [i][i][i]\n [h] [i][i][i]\n [h][h][h][h]\n[j]\n[j]\n[j]\n[j][j][j]" ,"[a][a] [b] [c]\n[a][a]\n[d][d][d][d][d] [e] [f]\n [e][e][e] [f]\n [e][e] [f]\n [f]\n [f]\n[g] [h] [i]\n[g] [h][h]\n[g][g]\n [g][g]\n[j][j][j]\n [j]" ,"[a] [b][b][b] [c]\n[a] [b] [c]\n[a][a][a] [b] [c]\n [b]\n[d] [e][e] [f][f]\n [f][f]\n[g] [h] [i]\n[g] [h][h][h] [i]\n [h][h] [i]\n[j] [k][k][k]" ,"[a] [b] [c]\n [b] [c]\n [b][b]\n [b][b]\n[d] [e] [f]\n[d] [e]\n[d] [e]\n[d]\n[d][d]\n[g] [h] [i][i]\n[g][g] [h][h] [i]\n [h][h]\n [h]\n[j] [k][k][k][k]" ,"[a][a] [b] [c][c][c][c][c]\n [b]\n [b]\n[d] [e] [f][f][f]\n [e] [f][f][f]\n[g] [h][h] [i]\n [h] [i]\n [h] [i][i]\n [i][i]\n[j]\n[j]\n[j]\n[j]\n[j][j]" ,"[a][a][a] [b][b] [c][c]\n [b][b]\n[d] [e] [f][f]\n[d] [e] [f][f]\n[d]\n[g] [h] [i]\n [h] [i][i]\n [h] [i][i][i]\n [h]\n [h]\n[j][j][j]\n [j][j]\n [j]" ,"[a][a] [b][b] [c]\n[a][a] [c][c]\n[a][a] [c]\n [c]\n [c]\n[d] [e][e][e] [f]\n [f]\n [f]\n[g] [h][h][h] [i]\n[g] [h][h] [i]\n[j]\n[j]\n[j][j]\n [j]\n [j]" ,"[a][a] [b] [c]\n[a][a] [b] [c]\n [b][b][b] [c]\n [b] [c][c][c]\n[d] [e] [f][f]\n[d]\n[g][g][g] [h][h][h] [i]\n [i]\n [i]\n[j]\n[j]\n[j]\n[j]\n[j][j]" ] to=0 function update() { var nt=+I.value var test = Test[nt-1] if (test) { O.textContent = test clearTimeout(to) to = setTimeout(_=>{ I.disabled = true var t = + new Date() var [d,r]=F(test) O.textContent = 'Time '+(new Date-t)/1000+' sec'+d+r.join`\n`+'\n'+test I.disabled = false }, 800) } } update() ``` ``` Test # <input id=I value=1 type=number oninput='update()' max=101 min=1> (1 to 101, be patient: some testcase is slow to solve) <pre id=O></pre> ``` ]
[Question] [ To "shift" over a number `n` places, do the following: * Remove the last `n` digits * Add `n` copies of the first digit to the beginning of the number For example, to shift the number `31415` three places, take out the last three digits to get `31`, and then add three more copies of the first digit, `3`, to the end, giving `33331`. If the number is negative, digits should be taken from the left instead, and the first digit should be "filled in" from the right. For example, the string `31415` shifted over -3 places gives `15555`. If the number is 0, no change should be made. If the shift is more than the length of the program, then digits that were filled in might start to be removed. This means that if the number given is more than the length of the string, no further changes will be made after the entire string becomes a single digit. ## The challenge Given two numbers, `n` and `s`, return `n` shifted over `s` places. ## Test cases ``` n, s -> result 7243, 1 -> 7724 452, -1 -> 522 12, 1 -> 11 153, 4 -> 111 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (measured in bytes) wins. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 32 bytes Anonymous function which takes the sift as left argument and the number (as a string) as right argument. ``` {a←|⍺⋄(≢⍵)↑(a-⍺)↓(a⍴⊃⍵),⍵,a⍴⊃⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzgjM63kUduE6kQgUfOod9ej7haNR52LHvVu1XzUNlEjURcoBmRN1kh81LvlUVczSEIHSOjA@D17gbza//8NFcBmKaibG5kYq3NxHVoPFzExNQIKwLmGIJ4JnGdqrA4A "APL (Dyalog Unicode) – Try It Online") `{` anonymous function where *⍺* and *⍵* are left and right arguments  `|⍺` the absolute value of the shift  `a←` store in *a*  `⋄` then  `⌽⍵` reverse the number  `⊃` pick the first (i.e. last) digit  `a⍴` **r**eshape it to length *a*  `⍵,` prepend the number  `(`…`),` prepend the following:   `⊃⍵` the first digit   `a⍴` **r**eshape it to length *a*  `(`…`)↓` drop the following number of characters:   `a-⍺` *a* minus the shift  `(`…`)↑` take the following number of characters:   `≢⍵` the length of the original number [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` lambda n,s:(n[0]*s+n+n[-1]*-s)[-s*(s<0):][:len(n)] ``` [Try it online!](https://tio.run/##BcFLCoAgFADAq7jzD2pBIHUSc2GUFNhLem46vc3Ur50PuJ6XtZd0b3sioNAzCCYKlCAhaBuFRh40Coaz4T4GXw5gwGOv7wWNZEan0Q1UWd5/ "Python 2 – Try It Online") [Answer] ## Haskell, 69 bytes ``` s#n|l<-[1..abs n]=take(length s)$drop(-2*n)$(s!!0<$l)++s++(last s<$l) ``` Takes the number as a string. [Try it online!](https://tio.run/##LYlLDoIwEECvMhQWUwvEVogbOIInIMRUJUIoI@mUhYl3r5@4e5/R8jw4FyOn9HJN0emytBcG6ttg5wHdQPcwAsvs5h8rFmZHMkNOkn2TOakUK4XOcgD@elzsRNDCYtfTGXD1E4Vyo@vm/RNTKaFDcTTVQeRa5iiq2oi8@KE2/6brz61kD/EN "Haskell – Try It Online") How it works: ``` s#n -- s: input number as a string -- n: shift amount (s!!0<$l)++s++(last s<$l) -- make a string: -- n times the first digit, the whole number, n times the last digit -- e.g. "567" 2 -> 5556777 drop(-2*n) -- drop the first (-2 * n) chars, i.e. 0 if n>0 take(length s) -- take as may chars as there are in s ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` tn:i-yn1&Xl) ``` Inputs are: number to be shifted as a string; amount of shifting as a number. [Try it online!](https://tio.run/##y00syfn/vyTPKlO3Ms9QLSJH8/9/dRNTI3UuXUMA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L8kzypTtzLPUC0iR/O/S8h/dXMjE2N1LkMudRNTI3UuXSDD0AjMNzQFipsAAA). Consisder inputs `'452` and `'-1'`. ``` t % Implicitly input string. Duplicate % STACK: '452', '452' n % Number of elements % STACK: '452', 3 : % Range % STACK: '452', [1 2 3] i % Input number % STACK: '452', [1 2 3], -1 - % Subtract, element-wise % STACK: '452', [2 3 4] y % Duplicate from below % STACK: '452', [2 3 4], '452' n % Number of elements % STACK: '452', [2 3 4], 3 1 % Push 1 % STACK: '452', [2 3 4], 3, 1 &Xl % Clamp, with three inputs. Applies min function, then max % STACK: '452', [2 3 3] ) % Reference indexing. Implicitly display % STACK: '522' ``` [Answer] # J, 37 bytes This was one of those situations in J where an explicit verb seemed like the right (the only?) choice, but I would love to know if there's a tacit rewrite of this: ``` 4 :'(-x)(|.!.((x>0)&{({:,{.)":y))":y' ``` J's built in shift verb allows you to configure the "fill" character: ``` |.!.f NB. f is the fill character ``` The logic to determine whether to use the first or last char as the fill character is straightforward ``` (x>0)&{ ({: , {.) ``` [Try it online!](https://tio.run/##y/r/P81WT8FEwUpdQ7dCU6NGT1FPQ6PCzkBTrVqj2kqnWk9TyapSE0SoK3ClJmfkKygYKqQpGBmbmEK48ahcQwMo9/9/AA "J – Try It Online") [Answer] # [J](http://jsoftware.com/), 23 bytes ``` (_&(]{.,],{:)~|)}.~_2*] ``` Input *n* and the output are strings containing the numbers. [Try it online!](https://tio.run/##y/r/P03B1kpBI15NI7ZaTydWp9pKs65Gs1avLt5IK5aLKzU5I19B3dzIxFhdIU1BwRAioKBuYmoEEoiHCSioGxqhqjA0hWgx@f8fAA "J – Try It Online") ## Explanation ``` (_&(]{.,],{:)~|)}.~_2*] Input: 'integer n' as a string (LHS), integer s (RHS) ( ) Extend 'n' by copying its head and tail 's' times | Abs(s) _&(] )~ Nest 'Abs(s)' times on 'n' {: Tail ], Append the tail to itself {. Head , Prepend the head to the previous _2*] Multiply 's' by -2 }.~ Drop abs(-2*s) from the head if 's' < 0 else from the tail ``` [Answer] # [Retina](https://github.com/m-ender/retina), 61 bytes ``` \d+¶ $*1¶ +`(?<!-).¶(.)(.*). ¶$1$1$2 - +`.¶.(.*)(.)$ ¶$1$2$2 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkX70DYuFS1DIKmdoGFvo6irqXdom4aepoaelqYe16FtKoZAaMSlywWUB8rogcSB0ioQKSMVo///dQ25TEyNAA "Retina – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` 0‹©iR}¹ÄF¨¬ì}®iR ``` [Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//zDigLnCqWlSfcK5w4RGwqjCrMOsfcKuaVL//y0xCjQ1Mg "05AB1E – Try It Online") **Explanation** ``` 0‹ # input_1 is negative © # store a copy in register iR} # if true (input_1 is negative), reverse input_2 ¹ÄF # abs(input_1) times do ¨ # remove the last element ¬ì # prepend the head } # end loop ®iR # if input_1 was negative, reverse result ``` [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes ``` f=lambda n,s:s<0and f(n[::-1],-s)[::-1]or n[0]*min(len(n),s)+n[:[0,len(n)-s][len(n)>s]] ``` [Try it online!](https://tio.run/##JcpBCoMwEEbhq2TnTDuBKO0m1F4kzCLFhgr6K46bnj4tZPc9ePv3/GwYai3jktfXlB3Eoj1CxuQKIcXoexVv3LQdDinoZZ1ByxsEFuPrf0tBWnvT1PQ01bofM04q1N3uQye@Z64/ "Python 2 – Try It Online") Takes the number as a string, and the shift as an integer. Returns a string. I tried embedding the reversal inside the function rather than making a recursive call, but I couldn't seem to get it right. [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` f=lambda s,i:(f(s+1,i[1:]+i[-1])if s<0else f(s-1,i[0]+i[:-1]))if s else i ``` [Try it online!](https://tio.run/##HcwxCoAgFADQq/xNRQWlWqROIg1GSR/KJF06vanzgxe/fD5hKMUvl7u33UESaKiniWuBVpuVo5V6Zeghzeq40gEVZUPVzDTsCh2xxBdDrsMogOhpIIyVHw "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 108 bytes Oh well, this went worse than I thought.. ``` n#s=print$show n&s r=reverse n&s|s<0=r$r n&abs s|(a:b,c)<-splitAt s n=take(length n)$(a<$[0..s])++b++c|1>0=n ``` [Try it online!](https://tio.run/##Rc3BCoJAFIXh/TzFgSRmUEPNCMIJonVPEBGjDCnpTeZOReC7my2q5cd/4NSGr7Ztx5FmrHvXkA@4vj1BcxZOO/uwjq2YNHCRaBe4qZiSwYM0mzKqVBFz3zZ@58Eg7c3VytbSxdcgFUhTBMdkseCTCsMyDKsh3SaaRm/Z7w1bhhbAEXKd5csIqZoUQearLEL8VZr9S7qaZvkHJyE60xA0OtMfzpB3qu7OvSBnSuF3ML4B "Haskell – Try It Online") ### Ungolfed ``` n # s = print $ show n & s n & s | s < 0 = reverse (reverse n & abs s) | (a:b,c)<-splitAt s n = take (length n) (replicate s a ++ b ++ c) | otherwise = n ``` [Answer] ## Clojure, 121 bytes ``` #(let[T(if(pos? %2)reverse vec)](apply str(concat(repeat %2(first %))(T(drop(Math/abs %2)(T %)))(repeat(- %2)(last %))))) ``` Ouch, nasty to deal with negative inputs as well. [Answer] # Pyth, 28 bytes ``` AQ=Y<+*hJ?K<0H`G_`GHJlJ?KY_Y ``` [Try it online](http://pyth.herokuapp.com/?code=AQ%3DY%3C%2B%2ahJ%3FK%3C0H%60G_%60GHJlJ%3FKY_Y&test_suite_input=%5B7243%2C++1%5D%0A%5B+452%2C+-1%5D%0A%5B++12%2C++1%5D%0A%5B+153%2C++4%5D&debug=0) or [test some inputs](http://pyth.herokuapp.com/?code=AQ%3DY%3C%2B%2ahJ%3FK%3C0H%60G_%60GHJlJ%3FKY_Y&test_suite=1&test_suite_input=%5B7243%2C++1%5D%0A%5B+452%2C+-1%5D%0A%5B++12%2C++1%5D%0A%5B+153%2C++4%5D&debug=0) Explanation ``` AQ=Y<+*hJ?K<0H`G_`GHJlJ?KY_Y AQ | Split Q into 2 parts, G and H. J?K<0H`G_`G | If 0 < H, J = str(G). Else, J = reverse(str(G)). Return J h | Find 1st element * H | Repeat H times + J | Concatenate with J < lJ | Find 1st length(J) elements =Y | Assign to Y. ?KY_Y | If K, implicit print Y. Else implicit print reverse(Y). ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 33 bytes ``` ÄF¹0‹©i¨ë¦}}²®i¤ë¬}sg¹Ä‚Ws\×®i«ëì ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cIvboZ0Gjxp2HlqZeWjF4dWHltXWHtp0aF3moSVAzpra4vRDOw@3PGqYFV4cc3g6SHz14dWH19T@/2/MZW5kYgwA "05AB1E – Try It Online") --- 05AB1E is not so hot with conditionals. [Answer] # JavaScript, 80 bytes ``` (n,s,k=n.length,p=s<=0)=>n.slice(p*-s,p?k:-s)[p?"padEnd":"padStart"](k--,n[p*k]) ``` Takes input as a string representation of the number and a numerical "shift" amount. Returns a string. ## Test Snippet ``` let f= (n,s,k=n.length,p=s<=0)=>n.slice(p*-s,p?k:-s)[p?"padEnd":"padStart"](k--,n[p*k]) I.value="31415";J.value="3";D.oninput() ``` ``` <div id=D oninput="O.value=I.value.length&J.value.length?f(I.value,+J.value):''">n: <input id=I size=10> s: <input id=J size=2><br><input id=O disabled> ``` ]
[Question] [ Stewie's Game of Life and Fatigue is quite similar to the more famous [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). --- The universe of the Stewie's Game of Life and Fatigue (GoLF) is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of three possible states, alive, dead or tired. Every cell interacts with its eight neighbors, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur: * Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. * Any live cell with two or three live neighbours lives on to the next generation. * Any live cell with more than three live neighbours dies, as if by overpopulation. * Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. * **Any cell that has been alive for two consecutive generations dies, as if by fatigue.** It can't wake to life again until next generation * **Any cell that is outside the boundary of the input grid are dead, as if it's fallen off a cliff.** --- # Challenge: Your challenge is to take a grid of dimensions **n-by-m** representing the initial state of a GoLF, and an integer **p**, and output the state of the Game after **p** generations. ### Rules: * Input and output formats are optional, but the input/output grids should have the same representation * You may choose any printable symbols to represent live and dead cells (I'll use `1` for live cells and `0` for dead cells). * You may choose if you have 0 or 1-indexed. In the examples, `p=1` means the state after one step. * Shortest code in each language wins * Built-in function for cellular automation are allowed --- ### Test cases: In the examples, I've only included the input grid in the input, not **p**. I've provided outputs for various **p**-values. You shall only output the grid that goes with a given input **p**. ``` Input: 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 --- Output --- p = 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 p = 2 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 p = 3 -> All dead --- Input: 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 --- Output --- p = 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 2 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 3 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 4 -> All dead Input 0 1 1 0 1 1 0 1 1 0 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 1 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 1 1 1 0 0 0 0 1 --- Output --- p = 1 1 1 1 0 0 0 1 1 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 1 1 0 0 1 1 p = 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 p = 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 p = 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 p = 5 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 p = 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 p = 9 -> All dead ``` Yes, I'm aware that all initial seeds won't end in all cells being dead. [Answer] # Golly RuleLoader, 295 bytes ``` @RULE Y @TABLE n_states:3 neighborhood:Moore symmetries:permute var z={1,2} var y=z var x=z var w=z var u=z var a={0,z} var b=a var c=a var d=a var e=a var f=a var g=a var h=a 0,z,y,x,0,0,0,0,0,1 z,a,0,0,0,0,0,0,0,0 z,y,x,w,u,a,b,c,d,0 2,a,b,c,d,e,f,g,h,0 1,a,b,c,d,e,f,g,h,2 @COLORS 2 255 0 0 ``` Input grid should be pasted in, boundaries are in the rulename (eg `5`\*`3` is `Y:P5,3`), press space to advance. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~30~~ 25 bytes *5 bytes removed thanks to a suggestion by [@CalculatorFeline](https://codegolf.stackexchange.com/users/51443/calculatorfeline)!* ``` 0ii:"wy*~wt3Y6QZ+5:7mb*]& ``` [Try it online!](https://tio.run/##y00syfn/3yAz00qpvFKrrrzEONIsMErb1Mo8N0krVu3//2gDBUMghJLWSBwgtAYzDcAQLAtjgtVYQ@WgGqyR5SCyML1AgVguUwA) Inputs are a matrix and a number. The matrix uses `;` as row separator. The matrices for the three test cases are entered as ``` [0 0 0 0 0; 0 0 1 0 0; 0 0 1 0 0; 0 0 1 0 0;0 0 0 0 0] [0 1 0 0 0 0; 0 0 1 0 0 0; 1 1 1 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0] [0 1 1 0 1 1 0; 1 1 0 1 1 1 1; 0 1 0 0 0 1 0; 0 0 0 1 1 0 1; 1 0 0 1 0 1 1; 0 0 1 1 0 1 1; 1 1 0 0 0 0 1] ``` ### Explanation ``` 0 % Push 0. This represents the generation previous to the input one. Actually % This should be an array of zeros, but thanks to broadcasting it is % equivalent (and saves bytes) i % Input: array with starting generation i % Input: number of iterations, p. % STACK (bottom to top): 0, array with initial generation, p :" % Do the following p times % STACK: previous gen, current gen wy % Swap, duplicate from below % STACK: current gen, previous gen, current gen *~ % Multiply element-wise, negate. This creates a mask of cells that do not % die of fatigue (they were 0 in the current or in the previous generation) % STACK: current gen, fatigue mask wt % Swap, duplicate % STACK: Fatigue mask, current gen, current gen 3Y6 % Push predefined literal: 8-neighbourhood: [1 1 1; 1 0 1; 1 1 1] % STACK: Fatigue mask, current gen, current gen, 8-neighbourhood Q % Add 1 element-wise. This gives [2 2 2; 2 1 2; 2 2 2], which will be % used as convolution kernel. Active cells with 2 neighbours will give 5; % inactive cells with 3 neighbours will give 6; and active cells with 3 % neighbours will give 7 % STACK: Fatigue mask, current gen, current gen, convolution kernel Z+ % 2D convolution, keeping size % STACK: Fatigue mask, current gen, convolution result 5:7 % Push array [5 6 7] m % Ismember, element-wise. Cells that give true will survive, unless fatigued % STACK: Fatigue mask, current gen, cells that can survive b % Bubble up % STACK: Current gen, cells that can survive, fatigue mask * % Multiply element-wise. This tells which cells survive considering fatigue. % The result is the new generation % STACK: "Current" gen which now becomes old, "new" gen which now becomes % current ] % End & % Specify that implicit display will show only top of the stack ``` [Answer] # [APL (Dyalog Classic 16.0)](https://www.dyalog.com/), 59 bytes ``` ⌊{((3∊⌊{⍵,⍵-c}+/,⍵)∧.1>1|c)×(.1×c)+1⌈c←2 2⌷⍵}⎕U233A 3 3⍣⎕⊢⎕ ``` [Try it online!](https://tio.run/##tVXdThNBFL7vU5zEi@6m3drdKv4kkBAx3mBiojzAMjstY6azZWeh1lIv1GCprNEYgzfegImN8U4JCYk35U3mRfDM7LbgChEUupvuzDc/3/k/fos7QcfnYcMh3JeSkUOVfIKYLkE95DxsM9EAJsEXMPtgHpphQDmuRLBKI8lCAe5UpVqUIGgb1JsPC16tNgthi0Z@HEYF1V83iFp/24VL@xUALJXs49utI1M6BPX6JVi1ijeNYgmiBs/LxXrRniniWlH1B4iSCJGeSr7Z2WlzLDud7Pa655EAtPosRP7q6fu0ac02QDNSEfhAZXw@FktC09Zarr9HpTfcskqGKvmKKuxY3oza2FbJDxQeX1sNttPRhFuypxRdGaAfV2mTivg8zG2JtBYySOR/l9JcvCcBhNZus9882EPV2tJ55q3JCyd5rEkGL1T/Y6V8FYNDJZ@royEadTS0mgdbKvk@GgpbL5cQ1jM5NiITASNUQkSXV1hEA4hDkOhOEgP1yRIQyvmpvMQoN/CMctJx4TIs2NGOasuSd7BFtK8sByck9dpuLhz9qLFiIqHlBwEq02Yxpj7jXJ4l5JP92@bWLH2@HUsftbnX6Y2Gj//MAMpZQIHTeqzZgdXHp3SdgaAuTIhqIAjRziKMISRkJULLA4sNcaDzDIPE0s4SjmuX0Ja2UfMCbGooWpriGXppNNRMxEFsHBnkD52uaPuhZiarJGBhjJcyHf9Otfwb1SBwdE5v/hwNx3zBGfki1liK/87HkK@sw3rHcqcnJcOe5EMLFy1LODrZR8OWXTLfZawxP1BCG1eX/8mkGCoMTqy1JwfLf3mwl9a@tAheUuPpYYd7dS@cO0SvdS2rpvsKjpAQy/KuQ3qlq2Vj2f6XijvjrhH7YMuquDotS64OKnSEBx5qr/vNuFtCDWroG2wUWvg3Hw6RJO3K6OKjrsyZwOyIVyKh3S@wJkHAZIv7nUIqnk3CVgekz@MM6Pao8Bc5fTg7/2gCIcHDu5WFO/fniovhE30x3ubUhZzWXxl3OJ1u@k@KhexEI2KB6T/vrCpkjw1m7J5hnO7P7kLTFfR9hWoecPOAlwdqJ8njGi7zj3xHM3wMv5tJ4B6TJ9tl9o@lHe8/duPkvuzUReowAa7lget5YCoP3MgDN/PArV8 "APL (Dyalog Classic) – Try It Online") (emulated on Classic 15.0) --- # [APL (Dyalog Unicode 16.0)](https://www.dyalog.com/), 85 bytes ``` ⌊{((3∊⌊{⍵,⍵-c}+/,⍵)∧.1>1|c)×(.1×c)+1⌈c←2 2⌷⍵}⌺3 3⍣⎕⊢⎕ ``` [Try it online!](https://tio.run/##tVXdTtswFL7vUxxpF03UpjTpxn4kkNCYdsOkSd0eICRuMUqdEqeUrisX28RK16ChCbGb3cCkVRN3AyEh7aa8iV@EHTtpYQEEbNBEjf3ZPt/5t133DLdle371RETfICQLUPE9z29SVgXKwWYw83IOar5LPFwJYJkEnPoMzMlCMcuBkSaI/hH4dRLYoR9kymLtcxvu7JcB0ER0hG@7gkzxEMSnD6CVCtaU2Nhijui9y2crWX06i2tZ0e0h6gSIdES0pyen1bHkdHTQad9EAwCUSH3kL16@T7pTbQN0HWGuDYSHN2PRONR0aeXaFzR63cyLaCCin2jCrmZNi/UdEe2j8vjqorcTj8bcnL4hGD4XY7dMaoSFN2FucqTVkIEj/2ZMc/uRBGDSun63dnyIpjW5sWq95bdOsihJeu9F92shP4HJIaLvxeEAnTocaLXjbRH9Gg6YLpdzCMsZHzmRMpc6hENAlho0IC6EPnAMpxMCsZ0FcIjnXcrrKON6ljKOGybchQdbMlBNnrOOtx0ZK83AiRNH7SCVjnZQbahMqNuui8Y0aYjlTj2PXyflo6MnSmpSPntnykf0D1ud4WDxfAUQj7oEPFIJJTvQyuiU7C3gVphKUQm4PvqZ@SH4jtMI0PNAQ0XsyjrDJNFksJhh6jn0pa7MvAWfKoq6pFjFKA0HkskxEBtlhnPOpnvSf2iZqioO2AzDhcTGq6mW/qLquYas6f7v4WDE516TL6DVhfBqPop8eZnWu5o5NW4Z@rge6rioacyQxT4c1PWc@i5hj9lHDXVcXfonl2KqULiw116cLP8VwU7c@@ImeEcXTycjuh@f@7MnGLW2ppXkvYIjJMS2fGA4ndxEXnm2@6NgTptvHf14WyuYsixzpkwqDIQFFlov75sylKCEQcEbQmq9sXWC0uMrGGN7egV7lGFZhI2AybgzbEbgUl737FYm1kt3/HoLuO2FCdDuEGbPe6Q8M/dqDCFB@Vnh9dMXs9l5f0UKRmlGhfEp@eVhyyNTNXslm0lOVAPqqotnUytC8uigxuY1xvH@RBb6LCPlZYppwEwDVhooXaSPqbjUP/KdzvBR/GaigXlGn2SX2j/SdrT/jMSxvOTUbdowBu6ngQdpYDINPEwDj9LA4z8 "APL (Dyalog Unicode) – Try It Online") (emulated on Unicode 15.0) --- Prompts for grid and then for **p**. Prints the new grid after **p** generations. Note that this uses the new `⌺` (Stencil) primitive which is not included in the Classic character set, hence a shorter version and a less-bytes version. Explanation to follow… [Answer] # Java 8, 333 bytes ``` int[][]G(int p,int[][]s){for(int h=s.length,w=s[0].length,y,x,n,a,b,t[][]=new int[h][w],i=0;i++<2*p;)for(y=0;y<h;++y)for(x=0;x<w;++x)if(i%2>0){for(n=0,a=y-2;++a<y+2;)for(b=x-2;++b<x+2;)n+=a>=0&a<h&b>=0&b<w&(a!=y|b!=x)&&s[a][b]>0?1:0;t[y][x]=s[y][x]<1?n==3?1:0:n<2|n>3|s[y][x]>1?0:2;}else s[y][x]=i==2*p&t[y][x]>1?1:t[y][x];return s;} ``` Explanation: ``` int[][]G(int p,int[][]s){ for(int h=s.length,w=s[0].length,y,x,n,a,b,t[][]=new int[h][w], //height, width, vars, temp array i=0;i++<2*p;) //for 2*generations: 1. calculate in temporary t, 2. copying to s for(y=0;y<h;++y) //for each row for(x=0;x<w;++x) //for each column if(i%2>0){ //1. calculate for(n=0,a=y-2;++a<y+2;) //n = number of alive cells around [y][x]. row above, at and below y for(b=y-2;++b<y+2;) //column left, at and right of x n+=a>=0&a<h&b>=0&b<w&(a!=y|b!=x)&&s[a][b]>0?1:0; //if within bounds and not the cell itself, add 1 if alive. t[y][x]=s[y][x]<1?n==3?1:0:n<2|n>3|s[y][x]>1?0:2; //save next state in temporary, depending on rules. alive cells become 2. } else //2. copy temporary t to s s[y][x]=i==2*p&t[y][x]>1?1:t[y][x]; //if last generation, replace 2 by 1 return s; } ``` ]
[Question] [ As we all know, modern operating systems have thread schedulers that can pick different orders to schedule your threads based on internal logic which your code is not privy to. Normally you architect your multithreaded code to ensure that this nondeterminism imposed on you does not meaningfully affect your output. The goal here is the opposite. Produce a program which prints the integers in the interval [0,99] but in an order which will vary from run to run due to the OS thread scheduler. You must achieve "enough nondeterminism", defined as: > > In 10 sequential sets of 10 trials your program must produce at least 9 unique permutations within each trial. You may have a reasonable number of failed sets of trials on either side of the consecutive 10 which succeed. > > > Or, to put it another way, you need 100 runs of your program where each block of 10 runs has at most two runs which output the same thing. > > > So, occasionally swapping 98 and 99 won't cut it. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer which uses the fewest bytes wins. ## Minutiae * Write your output to stdout, one entry per line * If you mangle the format by having two threads interleave character writes to stdout (even occasionally) resulting in things like three digit numbers or empty lines, your result is invalid * The only exception to the above rule is that you may emit a single empty line after printing the last required number (you're welcome) * If you ever miss or duplicate any required values your result is invalid * Your program does **not** need to be nondeterministic on a single core processor (though kudos if it is) * Your program may use green threads/fibers which are not actually managed by the OS kernel iff it still meets the other requirements of the challenge and the threading system is part of your language or the standard library for your language * Runtime for your program must be reliably under 5 seconds on a modern processor * You do not get to specify changes to the environment which happen outside of your program such as waits or settings changes; your program should pass whether run 100ish times back to back or with an hour between each run or 100ish times in parallel (that would probably help actually...) * You may use a coprocessor such as a GPU or Xeon Phi and its own internal scheduling mechanism for tasks. The rules apply to this the same way they apply to green threads. * Feel free to provoke the scheduler with all manner of sleeps, yields, and other tricks as long as you obey the rules specified in this post ## Banned Operations The only source of nondeterminism you are allowed to draw on is when the scheduler schedules your threads to run. The following list is not exhaustive, intended only to provides examples of things you are not allowed to do as they admit other sources of nondeterminism. * Directly or indirectly accessing any sort of PRNG or hardware RNG capability (unless it is as an inherent part of the scheduler). * Reading in any kind of input (system time, filesystem, network, etc.) * Reading thread IDs or Process IDs * Customizing the OS scheduler; you must use a standard OS scheduler from a mainstream OS * Customizing your green thread/fiber scheduler is also prohibited. This means that if you write a language for this challenge you **must** use OS threads. ## Answer Validation Preferably an answer would work across all common OSes and modern processors, with kudos awarded proportional to the breadth of support. However, this is not a requirement of the challenge. At a minimum an answer must support one modern SMP processor and modern OS. I'll test leading answers to the extent of my hardware availability. * If your entry will not produce the required output on an i7 5960x running Windows 10 v1607 x64, specify the environment required * If it's something I can easily reproduce with VMWare Workstation, provide the exact OS and VM specs * If it can't be produced in under either of those conditions, record a simultaneous screen capture of the test as described in the header section and a handheld video recording of your screen with your mouse and keyboard interaction (or whatever control scheme your nonstandard computation device uses) clearly visible and post both videos along with your answer and include an explanation of why it works * Alternately, get a reputable long-standing user (who is not you) with matching hardware to reproduce the result and vouch for you * If your entry is in an exotic programming language that a typical developer won't be set up to compile/jit/interpret, provide setup instructions * If you entry depends on a specific version of the JVM/Python interpreter/other, specify which * If it takes more than 10 minutes of back-to-back runs to get your 10 successful sequential sets of trials in my testing you fail (so don't let the success condition be a freak occurrence, especially if you're near the upper runtime bound) [Answer] # [Perl 6](http://perl6.org/), 27 bytes ``` await map {start .say},^100 ``` Explanation: ``` map { },^100 # Iterate over the range 0..99, and for each of number: start # Send the following task to a thread pool of OS threads: .say # Print the number, followed by a newline. await # Wait until all tasks have completed. ``` I hope this satisfies the task. (If not, please let me know). ### Testing: The shell script I used to test sufficient nondeterminism: ``` #!/usr/bin/bash for i in {1..10}; do set="" for j in {1..10}; do set="${set}$(perl6 nondet.p6 | tr '\n' ',')\n" done permutations="$(echo -e "$set" | head -n -1 | sort | uniq | wc -l)" echo -n "$permutations " done ``` For me, this outputs: ``` 10 10 10 10 10 10 10 10 10 10 ``` ### Setup instructions: I ran the test with an up-to-date Rakudo Perl 6 on 64bit Linux, though I guess it'll work on other platforms. The [Rakudo download page](http://rakudo.org/how-to-get-rakudo/) has setup instructions. I compiled mine from git like this: ``` git clone [[email protected]](/cdn-cgi/l/email-protection):rakudo/rakudo.git cd rakudo perl Configure.pl --gen-moar --make-install export PATH="$(pwd)/install/bin/:$PATH" ``` ### Try it online: Or just test it online, using this [Try It Online](https://tio.run/nexus/perl6#@59YnphZopCbWKBQXVySWFSioFecWFmrE2doYPD/PwA) link provided by @b2gills. I checked a few runs and got a different order each time, but haven't had the patience to run it 100 times through that online interface. [Answer] ## bash, ~~32~~ 28 bytes ``` for i in {0..99};{ echo $i&} ``` I ran this 100 times and got 100 different results. Edit: Saved 4 bytes thanks to @DigitalTrauma. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~54~~ ~~46~~ ~~44~~ 39 bytes ``` workflow p{foreach -p($i in 0..99){$i}} ``` PowerShell Workflows are not supported in TIO, so you can't try it there. Should work great on your Windows 10 machine though :) Defines a function `p` which will output the list of numbers when invoked. ### Timing A single run reliably runs in about 600ms on my machine. The 100 tests defined below finish in under 2 minutes. ### Testing Here's complete code to test it: ``` workflow p{foreach -p($i in 0..99){$i}} #workflow p{foreach($i in 0..99){$i}} # uncomment above to prove testing methodology does detect duplicates 1..10 | % { $set = $_ Write-Host "Set $set of 10" 1..10 | % -b { $runs = @() } -p { $run = $_ Write-Host "-- Run $run of 10 in set $set" $runs += "$(p)" } -e { Write-Host "-- There were $(10-($runs|Get-Unique).Count) duplicate runs in set $set" } } ``` ### Output on my machine: > > > ``` > Set 1 of 10 > -- Run 1 of 10 in set 1 > -- Run 2 of 10 in set 1 > -- Run 3 of 10 in set 1 > -- Run 4 of 10 in set 1 > -- Run 5 of 10 in set 1 > -- Run 6 of 10 in set 1 > -- Run 7 of 10 in set 1 > -- Run 8 of 10 in set 1 > -- Run 9 of 10 in set 1 > -- Run 10 of 10 in set 1 > -- There were 0 duplicate runs in set 1 > Set 2 of 10 > -- Run 1 of 10 in set 2 > -- Run 2 of 10 in set 2 > -- Run 3 of 10 in set 2 > -- Run 4 of 10 in set 2 > -- Run 5 of 10 in set 2 > -- Run 6 of 10 in set 2 > -- Run 7 of 10 in set 2 > -- Run 8 of 10 in set 2 > -- Run 9 of 10 in set 2 > -- Run 10 of 10 in set 2 > -- There were 0 duplicate runs in set 2 > Set 3 of 10 > -- Run 1 of 10 in set 3 > -- Run 2 of 10 in set 3 > -- Run 3 of 10 in set 3 > -- Run 4 of 10 in set 3 > -- Run 5 of 10 in set 3 > -- Run 6 of 10 in set 3 > -- Run 7 of 10 in set 3 > -- Run 8 of 10 in set 3 > -- Run 9 of 10 in set 3 > -- Run 10 of 10 in set 3 > -- There were 0 duplicate runs in set 3 > Set 4 of 10 > -- Run 1 of 10 in set 4 > -- Run 2 of 10 in set 4 > -- Run 3 of 10 in set 4 > -- Run 4 of 10 in set 4 > -- Run 5 of 10 in set 4 > -- Run 6 of 10 in set 4 > -- Run 7 of 10 in set 4 > -- Run 8 of 10 in set 4 > -- Run 9 of 10 in set 4 > -- Run 10 of 10 in set 4 > -- There were 0 duplicate runs in set 4 > Set 5 of 10 > -- Run 1 of 10 in set 5 > -- Run 2 of 10 in set 5 > -- Run 3 of 10 in set 5 > -- Run 4 of 10 in set 5 > -- Run 5 of 10 in set 5 > -- Run 6 of 10 in set 5 > -- Run 7 of 10 in set 5 > -- Run 8 of 10 in set 5 > -- Run 9 of 10 in set 5 > -- Run 10 of 10 in set 5 > -- There were 0 duplicate runs in set 5 > Set 6 of 10 > -- Run 1 of 10 in set 6 > -- Run 2 of 10 in set 6 > -- Run 3 of 10 in set 6 > -- Run 4 of 10 in set 6 > -- Run 5 of 10 in set 6 > -- Run 6 of 10 in set 6 > -- Run 7 of 10 in set 6 > -- Run 8 of 10 in set 6 > -- Run 9 of 10 in set 6 > -- Run 10 of 10 in set 6 > -- There were 0 duplicate runs in set 6 > Set 7 of 10 > -- Run 1 of 10 in set 7 > -- Run 2 of 10 in set 7 > -- Run 3 of 10 in set 7 > -- Run 4 of 10 in set 7 > -- Run 5 of 10 in set 7 > -- Run 6 of 10 in set 7 > -- Run 7 of 10 in set 7 > -- Run 8 of 10 in set 7 > -- Run 9 of 10 in set 7 > -- Run 10 of 10 in set 7 > -- There were 0 duplicate runs in set 7 > Set 8 of 10 > -- Run 1 of 10 in set 8 > -- Run 2 of 10 in set 8 > -- Run 3 of 10 in set 8 > -- Run 4 of 10 in set 8 > -- Run 5 of 10 in set 8 > -- Run 6 of 10 in set 8 > -- Run 7 of 10 in set 8 > -- Run 8 of 10 in set 8 > -- Run 9 of 10 in set 8 > -- Run 10 of 10 in set 8 > -- There were 0 duplicate runs in set 8 > Set 9 of 10 > -- Run 1 of 10 in set 9 > -- Run 2 of 10 in set 9 > -- Run 3 of 10 in set 9 > -- Run 4 of 10 in set 9 > -- Run 5 of 10 in set 9 > -- Run 6 of 10 in set 9 > -- Run 7 of 10 in set 9 > -- Run 8 of 10 in set 9 > -- Run 9 of 10 in set 9 > -- Run 10 of 10 in set 9 > -- There were 0 duplicate runs in set 9 > Set 10 of 10 > -- Run 1 of 10 in set 10 > -- Run 2 of 10 in set 10 > -- Run 3 of 10 in set 10 > -- Run 4 of 10 in set 10 > -- Run 5 of 10 in set 10 > -- Run 6 of 10 in set 10 > -- Run 7 of 10 in set 10 > -- Run 8 of 10 in set 10 > -- Run 9 of 10 in set 10 > -- Run 10 of 10 in set 10 > -- There were 0 duplicate runs in set 10 > > ``` > > [Answer] # GCC on Linux, 47 bytes ``` main(i){for(i=99;fork()?i--:!printf("%d\n",i););} ``` This gave me different results pretty much every time, having been compiled with `gcc` (no flags) version 4.9.2. Specifically, I was on 64-bit Debian 8.6 (kernel version 3.16.31). ## Explanation If the `fork()` returns zero (child process), the value of `i` is printed, and the loop condition is false, because `printf` will return a value greater than zero. In the parent process, the loop condition is just `i--`. ]
[Question] [ Take the vector of unknowns [![enter image description here](https://i.stack.imgur.com/9HBDy.png)](https://i.stack.imgur.com/9HBDy.png), and apply some generic differentiable function [![enter image description here](https://i.stack.imgur.com/mQLwp.png)](https://i.stack.imgur.com/mQLwp.png). The [Jacobian](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) is then given by a matrix [![enter image description here](https://i.stack.imgur.com/e3ku6.png)](https://i.stack.imgur.com/e3ku6.png) such that: [![enter image description here](https://i.stack.imgur.com/cAAUY.png)](https://i.stack.imgur.com/cAAUY.png) For example, suppose `m=3` and `n=2`. Then (using 0-based indexing) [![enter image description here](https://i.stack.imgur.com/1CtL5.png)](https://i.stack.imgur.com/1CtL5.png) [![enter image description here](https://i.stack.imgur.com/dcXq6.png)](https://i.stack.imgur.com/dcXq6.png) The Jacobian of `f` is then [![enter image description here](https://i.stack.imgur.com/IIPzw.png)](https://i.stack.imgur.com/IIPzw.png) The goal of this challenge is to print this Jacobian matrix. # Input Your program/function should take as input two positive integers `m` and `n`, which represent the number of components of `f` and `u` respectively. The input may come from any source desired (stdio, function parameter, etc.). You may dictate the order in which these are received, and this must be consistent for any input to your answer (please specify in your answer). # Output Something which represents the Jacobian matrix. This representation must explicitly spell out all elements of the Jacobian matrix, but the exact form of each term is implementation defined so long as is unambiguous what is being differentiated and with respect to what, and every entry is outputted in a logical order. Example acceptable forms for representing a matrix: 1. A list of lists where each entry of the outer list corresponds to a row of the Jacobian, and each entry of the inner list corresponds to a column of the Jacobian. 2. A string or textual output where each line is a row of the Jacobian, and each delimiter separated entry in a line corresponds to a column of the jacobian. 3. Some graphical/visual representation of a matrix. Example: what is shown by Mathematica when using the `MatrixForm` command 4. Some other dense matrix object where every entry is already stored in memory and can be queried (i.e. you can't use a generator object). Example would be how Mathematica internally represents a Matrix object Example entry formats: 1. A string of the form `d f_i/d u_j`, where `i` and `j` are integers. Ex: `d f_1/d u_2`. Note that these spaces between `d` and `f_1` or `x_2` are optional. Additionally, the underscores are also optional. 2. A string of the form `d f_i(u_1,...,u_n)/d u_j` or `d f_i(u)/d u_j`. That is, the input parameters of the function component `f_i` are optional, and can either be explicitly spelled out or left in compact form. 3. A formatted graphical output. Ex.: what Mathematica prints when you evaluate the expression `D[f_1[u_,u_2,...,u_n],u_1]` You may choose what the starting index for `u` and `f` are (please specify in your answer). The output may be to any sink desired (stdio, return value, output parameter, etc.). # Test cases The following test cases use the convention `m,n`. Indexes are shown 0-based. ``` 1,1 [[d f0/d u0]] 2,1 [[d f0/d u0], [d f1/d u0]] 2 2 [[d f0/d u0, d f0/d u1], [d f1/d u0, d f1/d u1]] 1,2 [[d f0/d u0, d f0/d u1]] 3,3 [[d f0/d u0, d f0/d u1, d f0/d u2], [d f1/d u0, d f1/d u1, d f1/d u2], [d f2/d u0, d f2/d u1, d f2/d u2]] ``` # Scoring This is code golf; shortest code in bytes wins. Standard loopholes are forbidden. You are allowed to use any built-ins desired. [Answer] ## Python, 63 bytes ``` lambda m,n:["df%d/du%%d "%i*n%tuple(range(n))for i in range(m)] ``` For `m=3,n=2`, outputs ``` ['df0/du0 df0/du1 ', 'df1/du0 df1/du1 ', 'df2/du0 df2/du1 '] ``` The string formatting is 1 byte shorter than the more obvious ``` lambda m,n:[["df%d/du"%i+`j`for j in range(n)]for i in range(m)] ``` [Answer] # R, ~~93~~ 78 bytes ``` function(M,N){v=vector();for(i in 1:N){v=cbind(v,paste0("df",1:M,"/du",i))};v} ``` The numbering is 1-based. **-15 bytes** thanks to @AlexA. remaks ! [Answer] # Maxima, 68 bytes It's too bad I don't know Maxima like I know my dear C and Matlab. But I'll try nontheless. ``` f(m,n):=(x:makelist(x[i],i,m),g:makelist(g[i](x),i,n),jacobian(g,x)) ``` Example session using TeXmacs as a Maxima interpreter, mostly for neat math rendering: [![Maxima session in TeXmacs](https://i.stack.imgur.com/TWkyl.png)](https://i.stack.imgur.com/TWkyl.png) There may very well be better ways doing lists and such in Maxima (I would especially like to make the functions appear without the list markers, []), but I don't know the language well enough. [Answer] # Ruby, 53 bytes `f` is 0-indexed, `u` is 1-indexed. [Try it online!](https://repl.it/CjLZ) ``` ->m,n{m.times{|i|p (1..n).map{|j|"d f#{i}/d u#{j}"}}} ``` Each row occupies one line as an array representation as seen below. If it isn't compliant to spec, please let me know and I will fix it. ``` ["d f0/d u1", "d f0/d u2", "d f0/d u3"] ["d f1/d u1", "d f1/d u2", "d f1/d u3"] ``` [Answer] # [Cheddar](https://github.com/cheddar-lang/Cheddar), ~~79~~ 49 bytes ``` m->n->(|>m).map(i->(|>n).map(j->"df%d/du%d"%i%j)) ``` Apparently a fork of [this answer](https://codegolf.stackexchange.com/a/87538/48934). For `3,2` returns: ``` [["df0/du0", "df0/du1", "df0/du2"], ["df1/du0", "df1/du1", "df1/du2"]] ``` [Answer] # Jelly, 18 bytes ``` ps⁴’“ df“/du”ż$€€G ``` [Try it out!](http://jelly.tryitonline.net/#code=cHPigbTigJnigJwgZGbigJwvZHXigJ3FvCTigqzigqxH&input=&args=Mw+Mg) Given **(m, n) = (3, 2)**, prints (with spaces marked as `·`:) ``` ·df0/du0·df0/du1 ·df1/du0·df1/du1 ·df2/du0·df2/du1 ``` [Answer] # C, 125 bytes: ``` main(w,y,b,q){scanf("%d %d",&w,&y);for(b=0;b<w;b++){for(q=0;q<y;q++)printf("d f%d/du u%d%s",b,q,q<y-1?", ":"");printf("\n");}} ``` Takes input as 2 space separated integers, `b y`, and outputs the Jacobian Matrix as `y` comma separated strings on `b` lines. [C It Online! (Ideone)](http://ideone.com/EK8jQl) or [Test Suite (Ideone)](http://ideone.com/QpXYHa) ]
[Question] [ ### Back to basics... As a teacher at the local primary (grade?) school, you need a way to teach your class their times tables. At your disposal, you have hundred squares and a load of red pens. You need to also be able to show your class the correct answers quickly. Now, you're clever enough to write a program that can do times tables, but can you draw them on a hundred square? # The challenge Output a hundred square to stdout or equivalent using [ansi-escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) to shade in numbers which are multiples of the input. * Output a 10x10 grid containing the numbers 1-100. + It doesn't matter the alignment of 2 digit numbers in each box as long as it's consistant + For 1 digit numbers, you may pad to 2 digits and use the same formatting as 2 digit numbers or centered in the middle of the box. * If the number in the box is a multiple of the input, colour the entire box red. + This means the whole box, not just the number part For example, given the input `3`, print the given hundred square [![hundred square 3](https://i.stack.imgur.com/TbcJh.png)](https://i.stack.imgur.com/TbcJh.png) **This is code golf so the shortest answer in bytes wins!** [Answer] # Python 2, 166 bytes ``` R=range;n=input() for y in R(21):print''.join('♥[%dm%s♥[m'%(any(5>x-k%10*4>-1<y-k/10*2<3for k in R(n-1,100,n))*41,('+---|%2d '%(x/4+y*5-4))[y%2*4+x%4])for x in R(41)) ``` Replace `♥` by octal `033` (the ANSI escape character). [![enter image description here](https://i.stack.imgur.com/kvJML.png)](https://i.stack.imgur.com/kvJML.png) ## Explanation We treat the output as a `41×21` grid, and directly compute the character and color at each point. That is, the structure of the code is: ``` n = input() for y in range(21): print ''.join(F(x, y) for x in range(41)) ``` for some function `F`. The result of `F` is always of the following form: > > * An ANSI [*Control Sequence Introducer*](https://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements) (`\33[`). > * An [SGR code](https://en.wikipedia.org/wiki/ANSI_escape_code#graphics): `0m` for reset, or `41m` for red background. > * A single character. (`+`, `-`, `|`, space, or digit) > * An SGR reset sequence (`\33[m`). > > > We use the format string `'\33[%dm%s\33[m'`, where the first `%d` is either 0 or 41, and the `%s` is the character we wish to print. --- For the **color**, we have the following formula: ``` any(5>x-k%10*4>-1<y-k/10*2<3for k in R(n-1,100,n))*41 ``` I’m not going to fully explain this, but it basically loops over all rectangles that should be colored red, and checks if `(x, y)` is inside any of them. Note the use of operator chaining: I rewrote `-1<A<5 and -1<B<3` into `5>A>-1<B<3`. --- For the **character**, we have the following formula: ``` ('+---|%2d '%(x/4+y*5-4))[y%2*4+x%4] ``` If `y % 2 == 0` then for `x = 0, 1, …` this will generate `+---+---+---…` If `y % 2 == 1` then for `x = 0, 1, …` this will generate `| p |p+1|p+2…` [Answer] # Julia, ~~219~~ ~~182~~ ~~169~~ 167 bytes ``` !n=(~j=j%n<1;k(v=j->"---",c=+,s="$c\e[m";l=~)=println([(l(j)?"\e[;;41m$c":s)v(j)for j=10i+(1:10)]...,s);i=0;k();for i=0:9 k(j->lpad(j,3),|);k(l=j->~j|~(j+10(i<9)))end) ``` Used like this: `!7` Ungolfed: ``` function !(n::Integer) for j=(1:10) #This loop generates the top of the box if (j%n==0) print("\e[;;41m+---") #"\e[;;41m" is the ANSI escape code #for red background colour in Julia else print("+\e[m---") #"\e[m" resets to original colours end end println("+\e[m") for i=0:9 for j=10i+(1:10) #This loop generates the rows with the numbers if (j%n==0) print("\e[;;41m|",lpad(j,3)) else print("|\e[m",lpad(j,3)) end end println("|\e[m") for j=10i+(1:10) #This loop generates the other rows if (j%n==0)||((j+10)%n==0&&i<9) print("\e[;;41m+---") else print("+\e[m---") end end println("+\e[m") end end ``` Note that this is *very* ungolfed, for maximal readability. [Answer] ### HTML + Javascript, 379 HTML: ``` <input id=a value=3><pre id=z> ``` Javascript: ``` for(i=0,s=`\n|`,o='+';i++<109;x=i<10?` ${i} `:i-100?' '+i:i,s+=x+'|',o+=x='---+',i%10||(o+=s+'\n+',s=`\n|`));z.innerHTML=[...o+x].map((x,i)=>`<span id=i${i}>${x}</span>`).join``;f=m=>window['i'+m].style.background='red';for(j=k=+a.value;j<=100;j+=k){p=(j/10|0)*84+((m=j%10)?(m-1)*4:-48);'000102030442434445468485868788'.match(/../g).map(x=>f(+x+p))} ``` [jsfiddle.](https://jsfiddle.net/jhzusj3j/3/) ]
[Question] [ You may have seen puzzles like this: > > Find the `0`: > > `OOOOOOOOOOOOOOOOOOOO0OOOOOOOOOOOOOOOOOO` > > > The challenge is to write a program that finds the index of the different letter given an image. ### Input Input will be an `Image`. The image will consist of *one line* of *black* text in the *Helvetica 24 pt.* font on a *white* background. The text will consist from a selection of two characters: one character that is repeated, and one character that appears only once. For instance: [![Sample Input](https://i.stack.imgur.com/MUnTf.png)](https://i.stack.imgur.com/MUnTf.png) ### Output Output will be an `Integer`, the index of the different character. In the example above, the output will be `4`. (Note that indices of a string start at `0`) ### Program Specifications As per usual for code golf, the shortest program wins. --- ## Test Cases [![ ](https://i.stack.imgur.com/G9dhL.png)](https://i.stack.imgur.com/G9dhL.png) `=> 10` [![ ](https://i.stack.imgur.com/UQyS4.png)](https://i.stack.imgur.com/UQyS4.png) `=> 11` [![ ](https://i.stack.imgur.com/V0aAl.png)](https://i.stack.imgur.com/V0aAl.png) `=> 5` [![ ](https://i.stack.imgur.com/Uhaax.png)](https://i.stack.imgur.com/Uhaax.png) `=> 16` [![ ](https://i.stack.imgur.com/QPZpv.png)](https://i.stack.imgur.com/QPZpv.png) `=> 10` [![ ](https://i.stack.imgur.com/wsSul.png)](https://i.stack.imgur.com/wsSul.png) `=> 21` [![ ](https://i.stack.imgur.com/YBXfJ.png)](https://i.stack.imgur.com/YBXfJ.png) `=> 20` [![ ](https://i.stack.imgur.com/siVcv.png)](https://i.stack.imgur.com/siVcv.png) `=> 13` [![ ](https://i.stack.imgur.com/1DMtT.png)](https://i.stack.imgur.com/1DMtT.png) `=> 11` [![ ](https://i.stack.imgur.com/tXIbB.png)](https://i.stack.imgur.com/tXIbB.png) `=> 4` [![ ](https://i.stack.imgur.com/DsZNE.png)](https://i.stack.imgur.com/DsZNE.png) `=> 7` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~31~~ 32 bytes ``` {1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵} ``` `⎕IO←0` to get indices starting with 0 (per OP), and which is anyway default in many APL systems. `1,⍵` prepend a column of white pixels (to ensure margin) `∧⌿` boolean for each column if all-white (vertical AND-reduction) `2>/` boolean at each character's left edge (pair-wise greater-than) `⍵⊂⍨` split into blocks beginning at each TRUE. `{`…`}¨` for each block `∧⌿⍵` boolean for each column if all-white (vertical AND-reduction) `⍵/⍨~` columns that are not [all-white] `∘.≡⍨` match each element to all elements `+⌿` number of blocks identical to each block (vertical plus-reduction) `1⍳⍨` index of first one (i.e. unique element) Assumes the image is black (0) and white (1) pixels in the matrix `I`, and that there is at least one all-white pixel column between characters. ``` f←{1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵} ``` "!I!!": ``` ⊢I←6 12⍴(13/1),(22⍴0 1 1),(5/1),0,(8/1),(10⍴0 1 1),13/1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 f I 1 ``` "mmnmm": ``` ⊢I←7 31⍴(94/1),0 0,(∊0 1⌽¨2/⊂12⍴6↑1 0 1 1),0 1,(62⍴1 1 1,(⊢,⌽)(14⍴0 1)),33/1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 f I 2 ``` [Answer] # Mathematica, 125 bytes ``` StringCases[#,x:Except[StringCases[#~StringTake~3,x_~~___~~x_:>x][[1]]]:>Position[Characters@#,x]][[1,1,1]]-1&@*TextRecognize ``` Ahh, Mathemeatica builtins. So amazing. (And so long...) Blows up on |/! :/; ,/. `/' and blows up differently on m/n. [Answer] # Mathematica, 46 bytes ``` Length@First@Split@Characters@TextRecognize@#& ``` Same failures as the other mathematica solution as it relies on the same `TextRecognize` function. ]
[Question] [ Suppose you have 2 languages, `A` and `B`. A string `s` is a semiquine in `A` and `B` if it satisfies the following conditions: 1. `s` is a quine in language `A`. 2. `s` is a polyglot in `A` and `B`. 3. The output of running `s` as a `B` program is a different string `s'`, which is a quine in `B`. The goal of this challenge is to write a semiquine in two distinct languages. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins, with earliest answer used as a tiebreaker. ### Rules for Quines Only *true* quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, **without**: * reading your source code, directly or indirectly. * relying on a REPL environment which just simply evaluates and prints every expression you feed it. * relying on language features which just print out the source in certain cases. * using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.) Furthermore, your source code must not consist purely of literals (whether they be string literals, numeric literals, etc.) and/or NOPs. For example, ``12` is a polyglot in Jelly and Pyth, but in Jelly it is a NOP and a numeric literal, so it is not valid. Any non-suppressible output (such as copyright notices, startup/shutdown messages, or a trailing line feed) may be ignored in the output for the sake of the validity of the quine. ### Rules for Polyglots The two languages used must be distinctly different. In particular: * They must not be different versions of the same language (e.g. Python 2 vs. Python 3). * They must not be different dialects of the same language (e.g. Pascal vs. Delphi). * One language may not be a subset of the other one (e.g. C vs. C++1). * One language may not be a trivial derivative of the other (e.g. Matlab vs. Octave2, brainfuck vs boolfuck vs TinyBF vs ShadyAsFuck vs all the other trivial brainfuck derivatives). ### Miscellaneous Rules * You may not accept input from STDIN (or any other source). If your chosen language *must* take input, then either the input must be empty (empty string, piped from `/dev/null`, etc.), or the output of the program must not depend on the input. * For this challenge, you must write a complete program. Requiring additional code to run the solution is not allowed (such as assigning and calling a lambda function defined in the solution). 1: Yes I know that C is not really a subset of C++. It's close enough to be considered one for the purpose of polyglots, though, so I'm counting it for this challenge. 2: Like point 1 above, though Octave is technically not 100% compatible with Matlab, it was designed to be compatible, and is close enough that allowing a Matlab/Octave polyglot would trivialize the challenge. [Answer] ## GolfScript + [Fission](https://github.com/C0deH4cker/Fission), ~~19~~ 18 bytes ``` {".~ '!+OR" 2<}.~ ``` The trailing linefeed is necessary. This is a true quine in GolfScript. [Try it online!](http://golfscript.tryitonline.net/#code=eyIufgonIStPUiIKMjx9Ln4K&input=) In Fission it prints ``` '!+OR" ``` which [is a true quine in Fission](https://codegolf.stackexchange.com/a/50968/8478). [Try it online!](http://fission.tryitonline.net/#code=eyIufgonIStPUiIKMjx9Ln4K&input=) ### Explanation In GolfScript, anything of the form ``` {...}.~ ``` is a quine as long as `...` leaves a string with `".~"` on the stack. The `.` duplicates the block, such that there's one copy that gets printed at the end, and the `~` executes it, so we can use its contents to print the `.~` itself. In this case, the block pushes the string ``` ".~ '!+OR" ``` and then truncates it to the first two characters with `2<`. The Fission program really works exactly the same [as the quine itself](https://codegolf.stackexchange.com/a/50968/8478), since the first and third line are entirely ignored by the program. [Answer] # Ruby + (JavaScript *or* Python 3), 76 bytes This is another challenge that can be solved using my new favourite language, the almost-common subset of Ruby, JavaScript, and Python 3; and given that we don't have any answers in exoteric languages yet, and many people like to see non-golfing-language solutions, I thought I'd contribute one. Even better, the same answer solves the challenge in a variety of ways at the same time. Here's `s`: ``` s="'";d='"';n='print("s="+d+s+d+";d="+s+d+s+";n="+s+n+s+";eval(n)")';eval(n) ``` This is a quine in Ruby. It isn't a quine in JavaScript or Python 3; if you run it in either of those languages, its output `s'` has a trailing newline, and thus is different: ``` s="'";d='"';n='print("s="+d+s+d+";d="+s+d+s+";n="+s+n+s+";eval(n)")';eval(n) ``` However, `s'` is a polyglot quine in JavaScript and Python 3! (As usual for me, I'm using the Rhino implementation of JavaScript, both for convenience (as it runs from the command line rather than needing a browser), and because it has a weird standard library in which `print` writes to standard output.) Both languages produce `s'` as a result of running either program. As a bonus, this program also solves the problem in reverse. If you decide to run `s'` in Ruby, it'll print the original program `s` again. As such, `s'` is a valid (but slightly longer, at 77 bytes) answer to the question. At this point, I'm almost starting to think "differences in whether or not the output ends with a newline being sufficient to count two programs as different" should be considered a standard loophole, given that this seems to be a second set of languages (beyond the well known GolfScript/CJam) in which it's possible to pull the trick off. [Answer] # Vitsy (safe mode) and Y, 9 bytes, noncompeting. ``` ' Ugrd3*Z ``` In Vitsy, this is a quine. In Y, this prints `Ugrd3*Z'`; when run, this prints `Ugrd3*Z'`, which is a quine in Y. Y postdates the question, however. What Vitsy sees: ``` ' Ugrd3*Z ' Heyyyy a string! Let's do this! ........ Capturing a string! Oh, not done? Hm, let's go back to the start. ' There we go. (space) ... U (no op) g use count, disabled in safe mode r reverse stack d3* push a ' Z print it all! ``` What Y sees: ``` ' Ugrd3*Z ' Push a space. U Wrap around and capture. g Print that. (Nothing else is printed.) ``` [Answer] # CJam + GolfScript, 9 bytes ``` "0$p" 0$p ``` This is a quine in CJam. In GolfScript, it outputs itself with a trailing newline, which is a quine in GolfScript. I'm not sure whether CJam should be considered a trivial derivative of GolfScript. But I think they are quite different and at least not trivial. ]
[Question] [ The best solution I've found so far for a golf code puzzle I'm working on includes two *rather fat-looking* invocations of `range`. I'm very new at code golf, especially in Python, so I could use a few tips. The relevant fragment is this ``` [x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))] ``` The upper limit of the first `range` is not a sharp one. It should be at least 98690, and *all else being equal* (golf-wise, that is), the smaller the difference between this upper limit and 98690 the better, performance-wise1. I'm using 76 (=117649) because `7**6` is the shortest Python expression I can come up with that fits the bill. In contrast, the lower limit in the first `range`, as well as both limits in the second one, are firm. IOW, the program (in its current form) will produce incorrect results if those limits are changed. Is there a way to shorten one or both of the expressions ``` range(n+1,7**6) range(2,x) ``` ? BTW, in this case, aliasing `range` to, say, `r` gains nothing: ``` r=range;rr rangerange ``` EDIT: FWIW, the full program is this: ``` p=lambda n:[x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))][0] ``` `p(n)` should be the smallest palindromic prime greater than `n`. Also, `p` should not be recursive. Warning: It is already obscenely slow! --- 1Yes, I know: performance is irrelevant in code golf, but that's why I wrote "all else being equal (golf-wise, that is)". For example, my choice of `7**6`, and not the more immediately obvious, but poorer-performing, "golf-equivalent" alternative `9**9`. I like to actually *run* my code golf attempts, which means not letting the performance degrade to the point that it would take years to run the code. If I can help it, of course. [Answer] ## Make it a single loop As is, you have two loops: one iterating over `x` that might be palindromic primes, another iterating over `i` to check if `x` is prime by trial division. As you noticed, loops is Python take many characters, often to write `range`, but also to write `while _:` or `for x in _`. So, a golfed Python solution should take pains to use as few loops as possible. feersum's comment "The best-golfed programs often make surprising connections between different part of the programs" is very applicable here. The prime-checking might seem like a separate subroutine for which `all(x%i for i in range(2,x))` is the classic expression. But we'll do it another way. The idea is to use [Wilson's Theorem](http://en.wikipedia.org/wiki/Wilson%27s_theorem). For each potential prime `k`, we keep a running product of `(k-1)!`, and check is it's a multiple of `k`. We can keep track of `(k-1)!` while we test potential `k` to be prime palindromes by keeping a running product `P`. Actually, we'll use the stronger version of Wilson's Theorem that `(k-1)! % k` equals 0 for composite `k` and only for composite numbers, except `k=4` gives `2`, and so `(k-1)!**2 % k` equals `0` exactly for composite numbers. We'll update `P` to equal `k!**2` via the update `P*=k*k`. (See [this answer](https://codegolf.stackexchange.com/a/27022/20260) for this method used to find primes in Python.) Putting it all together: ``` def p(n): k=P=1 while(`k`!=`k`[::-1])+(k<=n)+(P%k==0):P*=k*k;k+=1 return k ``` This isn't yet fully golfed -- the condition in particular is written inefficiently. We can compress the condition to check that `k` is a palindrome while at the time enforcing the other conditions via a chained inequality. ``` def p(n): k=P=1 while`k`*(P%k>0>n-k)!=`k`[::-1]:P*=k*k;k+=1 return k ``` [Answer] ## AFAIK, not really. Range is commonly used in python golfs because it is the shortest way to generate lists of increasing/decreasing numbers. That said, it appears to be slightly (7 bytes) shorter to avoid using range and instead call a wrapped while loop: ``` def p(n): n+=1 while`n`*all(n%i for i in range(2,n))!=`n`[::-1]:n+=1 return n ``` Thanks to @xnor (as always) for improving the while condition's logic :) [Answer] When using iterative algorithms such as Newton method or calculating fractals, where you usually need to **perform iterations without actually caring about the index** you can save some characters by iterating over short strings instead. ``` for i in range(4):x=f(x) for i in'asdf':x=f(x) ``` At seven iterations this breaks even with `range`. For more iterations use backtics and large numbers ``` for i in`9**9**5`:pass ``` This runs 56349 times which should be enough for all practical purposes. Playing around with numbers and operators lets you hardcode a wide range of numbers this way. ]
[Question] [ ## Background [Manufactoria](http://pleasingfungus.com/Manufactoria/) has been marketed as a game, but we code-golfers can see it for what it really is: a two-dimensional programming language. The Manufactoria programming language is based around a single [queue](http://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29), which contains a series of colorful markers. The instruction pointer moves around the game board using conveyor belts, and it encounters a series of writers and branches which read from and write to the queue. The language is very easy to understand, so the quickest way to learn it is to play the first few levels of the game (linked above). # Challenge Your challenge is to create a program that can divide one number by another number in the least amount of time. The input to the program will be a string of X blue markers followed by Y red markers. The required output will be a string of red markers with a length of X/Y. The game board to be used is found in this official contest level: <http://pleasingfungus.com/Manufactoria/?ctm=Divide_and_Conquer;Input_will_be_X_blues_followed_by_Y_reds,_output_X/Y_reds;bbbbbbrr:rrr|bbbrrr:r|bbbbr:rrrr|r:|bbbbbbbbbbbbrrrr:rrr|bbbbbbbbbbbbrrr:rrrr|bbbbbbbbbrrr:rrr|bbbbbbbbbbrr:rrrrr;13;3;0> It is 13x13 (the maximum size) and it is pre-equipped with the correct tests (see the scoring section). # Scoring The score of your program is the total amount of time that it takes for the program to pass all of the tests in the official contest level. The total time is given on the level-complete screen. While running the tests, you will most likely have to use the 50x accelerate slider in the bottom left in order to receive the results quickly (time acceleration does not affect the score). Here is a list of division problems that are involved in the tests: ``` 6/2 = 3 3/3 = 1 4/1 = 4 0/1 = 0 12/4 = 3 12/3 = 4 9/3 = 3 10/2 = 5 ``` # Example I/O ``` 12/3=4 in: BBBBBBBBBBBBRRR out: RRRR 10/2=5 in: BBBBBBBBBBRR out: RRRRR 9/3=3 in: BBBBBBBBBRRR out: RRR 0/1=0 in: R out: ``` [Answer] ## Score 3:29 Might as well special case dividing by 1,2,3,4. Makes it a *lot* faster. ![enter image description here](https://i.stack.imgur.com/OJspC.png) <http://pleasingfungus.com/Manufactoria/?lvl=34&code=c9:13f2;c10:13f2;c11:13f2;p12:2f7;y13:2f0;p11:2f0;c11:4f3;c10:3f0;p11:5f0;c10:5f0;c9:5f0;c11:6f3;p11:7f0;c10:7f0;p11:3f0;r10:6f1;q8:5f4;q8:6f1;q9:6f1;c7:5f3;c7:6f3;q10:2f0;r10:1f3;r10:4f1;q9:3f4;q9:4f1;c9:2f3;c8:3f3;c8:4f3;r10:8f1;q10:9f6;q9:9f1;q9:8f4;q9:7f4;c8:8f3;c8:9f3;c8:10f3;c8:11f3;c8:12f3;c8:13f2;c7:7f2;c8:7f3;r11:9f3;r11:10f0;r10:10f0;r9:10f3;r9:11f2;p11:11f6;r11:12f1;g11:8f3;b10:11f2;c16:10f2;q17:10f6;q17:11f3;g18:11f0;c12:11f1;c12:10f2;c13:10f2;c14:10f2;c15:10f2;c17:12f0;p16:12f4;c16:11f3;c16:13f1;q15:12f0;r15:13f1;c14:12f3;c14:13f0;c13:13f0;q17:7f6;q17:9f1;q18:9f6;q18:8f5;q17:6f1;g16:6f2;y18:6f0;p17:5f5;r18:5f0;c16:5f0;p15:5f0;r15:6f3;b15:7f2;p16:7f6;r16:8f1;q14:5f0;y14:4f3;g14:6f1;p13:5f0;p13:6f0;p13:7f0;p13:8f0;p13:9f1;g12:9f0;c17:8f1;&ctm=Divide_and_Conquer;Input_will_be_X_blues_followed_by_Y_reds,_output_X/Y_reds;bbbbbbrr:rrr|bbbrrr:r|bbbbr:rrrr|r:|bbbbbbbbbbbbrrrr:rrr|bbbbbbbbbbbbrrr:rrrr|bbbbbbbbbrrr:rrr|bbbbbbbbbbrr:rrrrr;13;3;0>; [Answer] ## Score: 15:51 ![enter image description here](https://i.stack.imgur.com/sQ46l.png) Does division by repeated subtraction. Uses a Y amongst the R to keep track of how much divisor we've subtracted so far. Uses Gs to count the quotient. For instance, the state at the start of each outer loop (right after the initial G writer) for 12/4 is: ``` BBBBBBBBBBBB RRRR G BBBBBBBB RRRR GG BBBB RRRR GGG RRRR GGGG ``` When there are no Bs left, the gadget at the bottom left strips Rs and then outputs #G-1 Rs. The inner loop strips one B at a time and uses Y to keep track of position. Starting at the outer loop: ``` BBBBBBBB RRRR GG BBBBBBB RYRRR GG BBBBBB RRYRR GG BBBBB RRRYR GG BBBB RRRR GG ``` The inner loop is the 3x4 box in the lower right. The layout of the rest can probably be improved a bit, but the inner loop is tight. <http://pleasingfungus.com/Manufactoria/?lvl=34&code=c11:13f2;g12:2f3;p12:3f7;c13:3f3;p13:4f3;b12:4f2;r14:4f3;p14:7f7;r13:7f2;q14:8f7;g13:8f2;p14:9f4;r13:10f2;p14:10f7;b15:10f0;q14:11f7;p15:11f3;r16:11f1;p15:8f0;r15:9f1;c16:8f0;c13:2f0;c15:2f0;c16:2f0;c17:2f0;c11:3f3;c11:4f3;c11:6f3;c11:7f3;c11:8f3;c11:9f3;c11:5f3;p11:10f7;q11:11f6;q11:12f7;r10:12f2;c10:10f2;q16:10f5;y14:6f3;q14:5f3;g15:5f1;c15:4f1;c15:3f1;c17:9f1;c17:8f1;c17:7f1;c17:6f1;c17:5f1;c17:4f1;c17:3f1;y16:9f1;g17:10f1;q14:2f4;g14:1f3;&ctm=Divide_and_Conquer;Input_will_be_X_blues_followed_by_Y_reds,_output_X/Y_reds;bbbbbbrr:rrr|bbbrrr:r|bbbbr:rrrr|r:|bbbbbbbbbbbbrrrr:rrr|bbbbbbbbbbbbrrr:rrrr|bbbbbbbbbrrr:rrr|bbbbbbbbbbrr:rrrrr;13;3;0>; [Answer] ### Score 20:35 A completely different approach - less parts but considerably slower. ![div solution](https://i.stack.imgur.com/UlvCd.png) <http://pleasingfungus.com/Manufactoria/?lvl=34&code=p12:2f3;g11:2f3;b11:3f3;c12:4f2;c11:4f2;c13:2f3;c13:3f3;c13:4f3;c12:5f3;c11:5f1;c10:5f2;c9:8f3;c9:9f3;c10:11f2;c11:11f1;c11:9f1;c11:10f1;c11:12f2;c13:8f0;c11:8f0;c13:7f0;c14:7f0;c14:6f3;c12:7f3;y14:5f0;y10:6f1;y11:7f1;g12:6f2;g9:11f2;g10:10f0;q9:10f3;q13:5f7;q13:6f7;b11:6f1;b10:9f1;p10:7f1;r9:7f2;p10:8f4;p12:8f3;q12:12f3;r13:12f0;r8:10f2;c12:9f3;c12:10f3;c12:11f3;&ctm=Divide_and_Conquer;Input_will_be_X_blues_followed_by_Y_reds,_output_X/Y_reds;bbbbbbrr:rrr|bbbrrr:r|bbbbr:rrrr|r:|bbbbbbbbbbbbrrrr:rrr|bbbbbbbbbbbbrrr:rrrr|bbbbbbbbbrrr:rrr|bbbbbbbbbbrr:rrrrr;13;3;0>; ]
[Question] [ Good Afternoon Golfers, Our challenge for today is inspired by XKCD comics [356](http://xkcd.com/356/ "356") and [370](http://xkcd.com/730/ "730"). We're going to write a program to calculate the resistance of a group of resistors. A forewarning that this is nearly tough enough to warrant being a code challenge, however I think that there is a certain art to writing slightly more complex programs in a golfed format. The lowest amount of characters wins. Calculating the resistance relies on the following two formulas: * If the resistors are in series, the resistance is the sum of the each resistor's resistance * If the resistors are in parallel, the resistance is the inverse of the sum of the inverse of the resistance of each resistor So - for example: ![Example of calculating resistance](https://i.stack.imgur.com/kEsUG.png) Your challenge is to, in the least amount of characters possible, calculate the resistance of a group of up to 64 resistors. My apologies for the complexity, particularly of the input rules. I've attempted to define them in such a way that every language will be usable. * Each resistor will be connected to 2 or more other resistors. * The input is guaranteed to be valid, with only one entry and one exit point, which will connect * The network will be series-parallel to prevent requiring more maths then what is presented * Input will be via file, argument or stdin, depending on what is appropriate for your language. * Input will consist of a series of newline or forward slashed separated statements consisting of an integer of the resistance of the resistor, and spaces separating the IDs of the resistors that one side of the resistor is connected to. * The ID of the first resistor will be 1, incrementing by one for each successive resistor * The start will always have an ID of 0 * The final resistor will always have a resistance of 0 ohms, and only have the connections defined in its line For example: ![Example 2](https://i.stack.imgur.com/PndPC.png) Could be represented as ``` 3 0 6 1 1 0 5 0 0 2 3 4 ``` * Output can be to stdout or file. It may be represented in one of the following ways: + A number with a minimum of 2 decimal places, followed by a newline + A fraction consisting of an integer (the numerator), a forward slash and another integer (the denominator), followed by a newline. The fraction does not need to be the to be in its lowest form - 4/4 or 10/8 are, for instance acceptable. The fraction must be accurate within 1/100. There is no bonus for being perfectly accurate - this is provided is a crutch to enable languages without fixed or floating point operations to compete. I hope that covers all the points. Good luck! [Answer] ## Python, 329 chars ``` import sys N=[[1]]+[map(int,x.split())for x in sys.stdin] N[-1][0]=1 n=len(N) S=[set([i])for i in range(2*n)] for x in range(n): C=S[2*x] for y in N[x][1:]:C|=S[2*y+1] for x in C:S[x]|=C V=[0]*(2*n-1)+[1] for k in range(999): for i in range(1,2*n-1):V[i]+=sum((V[j^1]-V[i])/N[j/2][0]for j in S[i])/9./len(S[i]) print 1/V[1]-2 ``` Calculates the resistance by doing a voltage relaxation on the circuit. First it tacks on a 1 ohm resistor to the start and changes the last resistor from 0 ohm to 1 ohm. Then it sets the input voltage to 0 and the output voltage to 1 volt. After simulating current flow through the network, the network resistance is calculated using the voltage drop across the first 1 ohm resistor. Each resistor is given two numbers, the number for its left terminal and the number for its right terminal. Resistor r's left terminal is 2\*r and its right terminal is 2\*r+1. The input is used to calculate `S`, the sets of terminals that are connected together. Each terminal is given a voltage `V[t]` and a relaxation is done by raising the voltage if current is net flowing into a terminal set and lowering the voltage if current is net flowing out. [Answer] ## APL 190 Index origin 1. First loop (s) combines all resistors wired in series, second (p) those wired in parallel and the repeat to first loop to combine any parallel resistors now in series. The specification of the final zero resistor appears to be redundant. ``` r←¯1↓⍎¨(c≠'/')⊂c o←⊃↑¨r r←⊃1↓¨r s:→(0=+/n←1=+/×r)/p n←↑n/i←⍳↑⍴r o[n-1]←+/o[n-0 1] o←(i←n≠i)/o r←i⌿r r←r-r≥n →s p:n←1⍪2≠/r[;1] r←((⍴r),1)⍴r←¯1++\n~0 o←∊1÷¨+/¨1÷¨n⎕penclose o →(1<⍴o)/s 3⍕o ' ' ``` Tested over the examples in the question plus a slightly more complicated one: ``` Input: '5 0/3 1/1 2/0 2' 9.000 Input: '3 0/1 0/5 0/0 1 2 3' 0.652 Input: '3 0/6 1/1 0/5 0/0 2 3 4' 0.763 Input: '2 0/2 1/2 0/2 0/2 4/2 5/2 2 3 6/2 7/2 2 3 6/0 8 9' 2.424 ``` ]
[Question] [ Write two programs: - One which reads a string and a key and encodes the string into a rail-fence cipher using that key. - Similarly, write a program for the reverse function: deciphering a rail fence using a key. For those who don't know what rail fence cipher is, it is basically a method of writing plain text in a way it creates linear pattern in a spiral way. Example - when "FOOBARBAZQUX" rail-fenced using key of 3. ``` F . . . A . . . Z . . . . O . B . R . A . Q . X O . . . B . . . U ``` Reading the above spiral line-by-line, the cipher text becomes "FAZOBRAQXOBU". Read more at - [Rail fence cipher - Wikipedia](http://en.wikipedia.org/wiki/Rail_Fence_Cipher). Code in any language is welcome. Shortest answer in bytes wins. [Answer] ## Python 133 bytes ``` def cipher(t,r): m=r*2-2;o='';j=o.join for i in range(r):s=t[i::m];o+=i%~-r and j(map(j,zip(s,list(t[m-i::m])+[''])))or s return o ``` Sample usage: ``` >>> print cipher('FOOBARBAZQUX', 3) FAZOBRAQXOBU >>> print cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4) AGMSYBFHLNRTXZCEIKOQUWDJPV >>> print cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 5) AIQYBHJPRXZCGKOSWDFLNTVEMU >>> print cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 6) AKUBJLTVCIMSWDHNRXEGOQYFPZ ``` Note: the results from even rail counts are different than for the code you provided, but they seem to be correct. For example, 6 rails: ``` A K U B J L T V C I M S W D H N R X E G O Q Y F P Z ``` corresponds to `AKUBJLTVCIMSWDHNRXEGOQYFPZ`, and not `AKUTBLVJICMSWXRDNHQYEOGZFP` as your code produces. The basic idea is that each rail can be found directly by taking string slices `[i::m]`, where `i` is the rail number (`0`-indexed), and `m` is `(num_rails - 1)*2`. The inner rails additionally need to be interwoven with `[m-i::m]`, achieved by zipping and joining the two sets of characters. Because the second of these can potentially be one character shorter, ~~it is padded with a character assumed not to appear anywhere (`_`), and then that character is stripped off if necessary~~ it is converted to a list, and padded with an empty string. --- A slightly more human readable form: ``` def cipher(text, rails): m = (rails - 1) * 2 out = '' for i in range(rails): if i % (rails - 1) == 0: # outer rail out += text[i::m] else: # inner rail char_pairs = zip(text[i::m], list(text[m-i::m]) + ['']) out += ''.join(map(''.join, char_pairs)) return out ``` [Answer] ## APL ~~52~~ 41 ``` i←⍞⋄n←⍎⍞⋄(,((⍴i)⍴(⌽⍳n),1↓¯1↓⍳n)⊖(n,⍴i)⍴(n×⍴i)↑i)~' ' ``` If the input text string i and the key number n are preinitialised the solution can be shortened by 9 characters. Running the solution against the examples given by primo gives identical answers: ``` FOOBARBAZQUX 3 FAZOBRAQXOBU ABCDEFGHIJKLMNOPQRSTUVWXYZ 4 AGMSYBFHLNRTXZCEIKOQUWDJPV ABCDEFGHIJKLMNOPQRSTUVWXYZ 5 AIQYBHJPRXZCGKOSWDFLNTVEMU ABCDEFGHIJKLMNOPQRSTUVWXYZ 6 AKUBJLTVCIMSWDHNRXEGOQYFPZ ``` On further reflection there appears to be a shorter index based solution: ``` i[⍋+\1,(y-1)⍴((n←⍎⍞)-1)/1 ¯1×1 ¯1+y←⍴i←⍞] ``` [Answer] # [Python 2](https://docs.python.org/2/), 124 + 179 = 303 bytes Encode: ``` lambda t,k:''.join(t[i+j]for r in R(k)for i in R(k-1,len(t)+k,2*k-2)for j in[r-k+1,k+~r][:1+(k-1>r>0)]if i+j<len(t)) R=range ``` [Try it online!](https://tio.run/##jY7LToNAAEX3fAXpZkDA2FpdNLbJDO/nwBQoD1lgLApUaCZs3PjrSK3WbZc3596Te/wc3vtuMVbr5/FQfry8luwgtisAbpu@7rghr4WmqHrKUrbuWMK1/CnUv0Gai4f91OKFVlzctNLihzYTzanUCnOxFb5oka/mwqm7oZs7vqgrdnI@nXc8Q9a07N7245HW3cBWHNAwRpAgmAVRAsR7njkToMEMIwKDBKMIMJc6RLKiarphWrbjetgPyDaM4l2SZkBcXsZQd7cp0gzHI2GSyapp4yDaKZYfX6l6@FeZQYoMyyeTR7fxdqdojhfGqnvtq8c/1QzaEbKcMJZNd9IYHklUHQep5mez8Rs "Python 2 – Try It Online") Decode: ``` lambda t,k:''.join(t[dict((b,a)for a,b in enumerate(i+j for r in R(k)for i in R(k-1,len(t)+k,2*k-2)for j in[r-k+1,k+~r][:1+(k-1>r>0)]if i+j<len(t)))[m]]for m in R(len(t))) R=range ``` [Try it online!](https://tio.run/##TY1Nc4IwFEX3/IrsQkrsFFu7cKozREEUJRIF@SgLqNBGBJ0MXXTTv05B247Ld8@5952/6o9T1W/y0WtzTMp0n4AaF0MI7w8nXsl1tOdvtSynOEH5SYAEp4BXIKs@y0wkdSZz5QA6ILqYycXF4r9HT8XHrB1BSoH7d0Wvf6GHlkaiVygqLpRvEUdDVencsRg/oJjnoN18ufYQiso47krldfIvlthIJNV71pwFr2qQy9DQQkqY5viUuBA/IulKoEEp0RjRQsf1ofSva7PVJiCGubTZ1g8n@tyijrubLtYexE/oxps7ATEXa9ZKM4tudlNjaW89fdU@Gdx6lksWy603ma9ax7SZr8@oExjrEOJn1PwA "Python 2 – Try It Online") [Answer] # MATL, 70 bytes (total) ``` f'(.{'iV'})(.{1,'2GqqV'})'5$h'$1'0'$2'0K$hYX2Get2LZ)P2LZ(!tg)i?&S]1Gw) ``` [Try it on MATL Online](https://matl.suever.net/?code=f%27%28.%7B%27iV%27%7D%29%28.%7B1%2C%272GqqV%27%7D%29%275%24h%27%241%270%27%242%270K%24hYX2Get2LZ%29P2LZ%28%21tg%29i%3F%26S%5D1Gw%29&inputs=%27FAZOBRAQXOBU%27%0A3%0AT&version=20.9.2) [Try multiple test cases](https://tio.run/##hUzbToMwGL7vU9QE/YcxZmzZtVIY51HKsZCYSBbmyIaM0TkT47Mj7AW8@fKdm1Ich3f02i0fGbfxPd6X20OPRYub8lDhWuBrez7gXXvGzeUo6tOxwv1lu636vv4a88/TReC@Ej1i3PoedjB7/oE6hV95JMoTWGbXTQpW0h4kBeYgLWDuSvucW2YlFl4hByPM7sSHXL88RG@2eZUHPR7AoJSoIVELlnBAS2QgMNSCklBlnJJksmIEKtH0tWFatuN6G58GLIziJM14XgBaTRvVZjmxnCDkhWa6NMp0w/PjdL1JpsI/D8r8dhGRMNZYogfpmmaGz81NbnmF7Tq3RvwH "MATL – Try It Online") Takes a flag as third input, `F` to encipher the string, `T` to decipher it (thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/a/167109/8774) for that idea). This started as a Julia answer until I realized strict typing got in the way too much, especially for decipherment. Here's the Julia code I had for encipherment (backported to v0.6 for TIO): ### [Julia 0.6](http://julialang.org/), 191 bytes ``` !M=(M[2:2:end,:]=flipdim(M[2:2:end,:],2);M) s|n=replace(String((!permutedims(reshape([rpad(replace(s,Regex("(.{$n})(.{1,$(n-2)})"),s"\1ø\2ø"),length(s)*n,'ø')...],n,:),(2,1)))[:]),"ø","") ``` [Try it online!](https://tio.run/##VY5PT4NAFMTv/RTtpknfM08S1tgDhgOo9V@RllqtpRyIrBRDNxuWJia234s7HwzXgyaeJjPzm2Q@9mWRjrtuELgQxNzhjpAZOYn7XhYqK3b/QuJ4EWBPH6RbCVWmbwIWdVXIHGCgRLXb18JMNFRCb1MlIK5UmsEvqikSufgEBtbXUB7RiE1DkKccj8iQNNvYbbPhbWNMKWReb0HjiaRR24zQsqyEJDlIwMlGxNhJkJiBiTHslLlRlxLYJAx9L/K99Xy5Yv1D/wx7f53nX15dT25u7@4fpsFjOJtHi6fl88vqdf1DnmP3DQ "Julia 0.6 – Try It Online") ### Explanation: The rail fence operation ``` F . . . A . . . Z . . . . O . B . R . A . Q . X O . . . B . . . U ``` can be seen as reading r = 3 characters of input, then reading r-2 characters and prefixing and suffixing that with dummy values (nulls), then reading r characters again, etc., creating a new column every time: ``` F.A.Z. OBRAQX O.B.U. ``` then reversing every second column (since the *zag* part of zigzag goes up instead of down, which makes a difference when r > 3), then reading this matrix along the rows, and removing the dummy characters. Decipherment didn't seem to have any obvious patterns like this, but when searching around about this I came across [this post](https://web.archive.org/web/20150905104700/http://programmingpraxis.com/2009/03/31/rail-fence-cipher/2/), which told me that (a) this was a well known and (possibly?) published algorithm for rail ciphers, and (b) decipherment was a simple reuse of the same method, giving it the indices of the string and getting the *indices of* those indices after encipherment, and reading the ciphertext at those places. Since decipherment needs to do things by working on indices, this code does encipherment also by sorting the indices of the string, and then in this case just indexing at those rearranged indices. ``` % implicit first input, say 'FOOBARBAZQUX' f % indices of input string (i.e. range 1 to length(input) '(.{'iV'})(.{1,'2GqqV'})'5$h % Take implicit second input, say r = 3 % Create regular expression '(.{$r})(.{1,$(r-2)})' % matches r characters, then 1 to r-2 characters % (to allow for < r-2 characters at end of string) '$1'0'$2'0K$h % Create replacement expression, '$1\0$2\0' YX % Do the regex replacement 2Ge % reshape the result to have r rows (padding 0s if necessary) t2LZ) % extract out the even columns of that P % flip them upside down 2LZ( % assign them back into the matrix ! % transpose tg) % index into the non-zero places (i.e. remove dummy 0s) i? % read third input, check if it's true or false &S] % if it's true, decipherment needed, so get the indices of the % rearranged indices 1Gw) % index the input string at those positions ``` [Answer] # Java 10, ~~459~~ ~~451~~ ~~445~~ ~~439~~ ~~327~~ 325 bytes ``` (s,k,M)->{int l=s.length,i=-1,f=0,r=0,c=0;var a=new char[k][l];for(;++i<l;a[r][c++]=M?s[i]:1,r+=f>0?1:-1)f=r<1?M?f^1:1:r>k-2?M?f^1:0:f;for(c=i=0;i<k*l;i++)if(a[r=i/l][i%l]>0)if(M)System.out.print(a[r][i%l]);else a[r][i%l]=s[c++];if(!M)for(r=c=i=0;i++<l;f=r<1?1:r>k-2?0:f,r+=f>0?1:-1)if(a[r][c]>1)System.out.print(a[r][c++]);} ``` -14 bytes thanks to *@ceilingcat*. -112 bytes combining the two functions with an additional mode-flag as input. The function takes a third input `M`. If this is `true` it will encipher, and if it is `false` it will decipher. [Try it online.](https://tio.run/##tZTbbptAEIbv8xRbpEpQsGvSszG2jM35ZE62sUMlQiDZQHAEJFUU5dndBTtOUpL2qheAlvn3n293RnMZ3oady7N0G2VhWQI9hPn9EQAwr@IiCaMYGPUSgNsNPAMJHl2ExTooKRQHKXW62WRxmIOIYJDo4Qi9yiqsYAQMkAN2i5dUSulEZ3hf6zO27GZxfl5dUJDt0FTC9qgCPRHbY27DAoRsHv8CTYY0WGcBk2wKnCFJOMiYcF0E64gkA1YflWsY9GmqINlk2BvR/Q5NJGwxoEf6KPlJ9@l@MUw7x/tVr580PhELURo4SD9kDCRJAiY48mThxyxYw/dZMOzVv3TCuSur@Kq7uam61wWixpvMtYJg4qyMwWHNlg0Qg7a904k6R8Hus5AkQt4xPdIgjhfEu/zoTMGQfiNp7U4wD1umvtfrm9MM3ev@eptqXKFa4U6FNpyvAxAW5yWxq9WfdlmOY3weweuLuOgDrCkWAPH@D44JpsmNbW68srwlRn3ax@sT1WWD7DED4ICle@iDbq4JPt8@5iZTXhAlWVE13TBnlu243nyx9FcYBfdmryDVkTdxpzFyf057Fh9oxyuTs8fW0uS8J9qn@HjCi7Kqm5bjLXxuKkiKZsxsd75EOMdtNS/rlvdSNxFV01m86i3qjs8JkmbYLtLxsmpa3mKqzOYY9bmtli2fk5SZ/Wg5FTTDnfM64v7SVqsep2jufCLrSCkZ9pIXTcsXZoj7a1ut@5xmIGPVbPLzsuUJku2KDkZ9a6tNzphNdGuq2StedXxBcZei7C0kxP29rba4mT0xnanhIlZBm4vqQlKWK9nHqB9ttcPZ7sTypgjCXAjGUtR9SVvJqoJRdK81GZrWPTTPrn1BSYFmorzRwHhJYgBP4zvAAoxMSYzon1Qn1WNv5N0EL7vVZoJGx7gowjucQHOnKm7iv3dfm@twqv/IlYRojPwT7GH7Gw) ### Explanation: ``` (s,k,M)->{ // Method with character-array, integer, and boolean parameters // and no return-type int l=s.length, // Length of the input char-array i=-1, // Index-integer, starting at -1 f=0, // Flag-integer, starting at 0 r=0,c=0; // Row and column integers, starting both at 0 var a=new char[k][l]; // Create a character-matrix of size `k` by `l` for(;++i<l // Loop `i` in the range (-1, `l`): ; // After every iteration: a[r][c++]= // Set the matrix-cell at `r,c` to: M?s[i++] // If we're enciphering: set it to the current character :1, // If we're deciphering: set it to 1 instead r+=f>0? // If the flag is 1: 1 // Go one row down : // Else (flag is 0): -1) // Go one row up f=r<1? // If we're at the first row: M?f^1 // If we're enciphering: toggle the flag (0→1; 1→0) :1 // If we're deciphering: set the flag to 1 :r>k-2? // Else-if we're at the last row: M?f^1 // If we're enciphering: toggle the flag (0→1; 1→0) :0 // If we're deciphering: set the flag to 0 : // Else (neither first nor last row): f; // Leave the flag unchanged regardless of the mode for(c=i=0; // Reset `c` to 0 i<k*l;i++) // Loop `i` in the range [0, `k*l`): if(a[r=i/l][i%l]>0) // If the current matrix-cell is filled with a character: if(M) // If we're enciphering: System.out.print(a[r][i%l]);} // Print this character else // Else (we're deciphering): a[r][i]=s[c++]; // Fill this cell with the current character if(!M) // If we're deciphering: for(r=c=i=0; // Reset `r` and `c` both to 0 i++<l // Loop `i` in the range [0, `l`) ; // After every iteration: f=r<1? // If we are at the first row: 1 // Set the flag to 1 :r>k-2? // Else-if we are at the last row: 0 // Set the flag to 0 : // Else: f, // Leave the flag the same r+=f>0? // If the flag is now 1: 1 // Go one row up : // Else (flag is 0): -1) // Go one row down if(a[r][c]>1) // If the current matrix-cell is filled with a character: System.out.print(a[r][c++]);} // Print this character ``` ]
[Question] [ You thought regular sudoku was hard, now try [Killer Sudoku](https://en.wikipedia.org/wiki/Killer_sudoku)! In the game of Killer Sudoku, you aren't given any numbers at all. Instead, you're given regions that are said to add up to a certain number. Consider the following example, from Wikipedia: ![killer sudoku puzzle](https://i.stack.imgur.com/I98uv.png) And its solution: ![killer sudoku puzzle solution](https://i.stack.imgur.com/14PDw.png) The program you write will take a format consisting of a sequence of 81 letters representing regions, followed by a sequence of numbers. Then each number in the sequence represents the sum of the numbers in each of the letter regions, starting from "A", "B", etc. It will then output a sequence of 81 digits representing the solution. For example, the example puzzle above would have the following input: ``` AABBBCDEFGGHHCCDEFGGIICJKKFLMMINJKOFLPPQNJOORSPTQNUVVRSTTQWUUXXSYZWWaaXXSYZWbbbcc 3 15 22 4 16 15 25 17 9 8 20 6 14 17 17 13 20 12 27 6 20 6 10 14 8 16 15 13 17 ``` And the resulting output would be: ``` 215647398368952174794381652586274931142593867973816425821739546659428713437165289 ``` You may assume that the input is valid, and that the regions will always appear in order by A, B, ..., Y, Z, a, b, ..., z. (Shortest code that works wins.) [Answer] ## R - 378 characters Assuming ``` x="AABBBCDEFGGHHCCDEFGGIICJKKFLMMINJKOFLPPQNJOORSPTQNUVVRSTTQWUUXXSYZWWaaXXSYZWbbbcc" y="3 15 22 4 16 15 25 17 9 8 20 6 14 17 17 13 20 12 27 6 20 6 10 14 8 16 15 13 17" ``` 378 characters: ``` z=strsplit v=sapply R=rep(1:9,9) C=rep(1:9,e=9) N=1+(R-1)%/%3+3*(C-1)%/%3 G=z(x,"")[[1]] M=as.integer(z(y," ")[[1]])[order(unique(G))] s=c(1,rep(NA,80)) i=1 repeat if({n=function(g)!any(v(split(s,g),function(x)any(duplicated(x,i=NA)))) S=v(split(s,G),sum) n(R)&&n(C)&&n(N)&&n(G)&&all(is.na(S)|S==M)}){if(i==81)break;i=i+1;s[i]=1}else{while(s[i]==9){s[i]=NA i=i-1};s[i]=s[i]+1} s ``` takes about an hour on my modest PC to reach the expected solution, after 2,964,690 iterations. --- De-golfed: ``` ROWS <- rep(1:9, 9) COLS <- rep(1:9, each = 9) NONETS <- 1 + (ROWS - 1) %/% 3 + 3 * (COLS - 1) %/% 3 CAGES <- strsplit(x, "")[[1]] SUMS <- as.integer(strsplit(y, " ")[[1]])[order(unique(CAGES))] is.valid <- function(sol) { has.no.repeats <- function(sol, grouping) {       !any(vapply(split(sol, grouping),                   function(x) any(duplicated(x, incomparables = NA)),                   logical(1))) } has.exp.sum <- function(sol, grouping, exp.sums) { sums <- vapply(split(sol, grouping), sum, integer(1)) all(is.na(sums) | sums == exp.sums) } has.no.repeats(sol, ROWS ) && has.no.repeats(sol, COLS ) && has.no.repeats(sol, NONETS) && has.no.repeats(sol, CAGES ) && has.exp.sum(sol, CAGES, SUMS) } sol <- c(1L, rep(NA, 80)) # start by putting a 1 i <- 1L # in the first cell it <- 0L repeat { it <- it + 1L if (it %% 100L == 0L) print(sol) if(is.valid(sol)) { # if everything looks good if (i == 81L) break # we are either done i <- i + 1L # or we move to the next cell sol[i] <- 1L # and make it a 1 } else { # otherwise while (sol[i] == 9L) { # while 9s are found sol[i] <- NA # replace them with NA i <- i - 1L # and move back to the previous cell } sol[i] <- sol[i] + 1L # when a non-9 is found, increase it } # repeat } sol ``` [Answer] ### GolfScript, 138 characters ``` n%~[~]:N;1/:P.&:L;9..*?{(.[{.9%)\9/}81*;]:§;L{.`{\~@@=*}+[P§]zip%{+}*\L?N==}%§9/..zip+\3/{{3/}%zip{{+}*}%}%{+}*+{.&,9=}%+1-,!{§puts}*.}do; ``` This is a killer sudoku solver in GolfScript. It expects input on STDIN in two rows as given in the example above. Please note: Since the puzzle description does not make any restrictions on execution time I preferred small code size over speed. The code tests all 9^81 grid configurations for a solution which may take some time on a slow computer ;-) [Answer] ### Ruby, 970 characters ``` A,B=gets,gets.split L=[] R=[] U=[] D=[] N=[] C=[] S=[] O=[0]*81 z='A' (0..324).map{|j|U<<j;D<<j;R<<(j+1)%325;L<<(j+324)%325;N<<j;C<<j;S<<0} X=->s,j,c,cf,n{j<81?(z==A[j]?(0..8).map{|i|X[s-1-i,j+1,c+[i],cf+[1+j,1+81+27*i+j/9,1+81+27*i+9+j%9,1+81+27*i+18+j/3%3+j/27*3],n+[i+1]]}:X[s,j+1,c,cf,n+[0]]if s>=0):(h=U.size;cf.uniq.sort.map{|l|N<<n;L<<(L[h]||h);R<<h;U<<U[l];D<<l;C<<l;S[l]+=1;L[R[-1]]=R[L[-1]]=U[D[-1]]=D[U[-1]]=L.size-1}if s==0)} Y=->c{L[R[c]]=L[c];R[L[c]]=R[c];i=D[c];(j=R[i];(U[D[j]]=U[j];D[U[j]]=D[j];S[C[j]]-=1;j=R[j])while j!=i;i=D[i])while i!=c} Z=->c{i=U[c];(j=L[i];(S[C[j]]+=1;U[D[j]]=j;D[U[j]]=j;j=L[j])while j!=i;i=U[i])while i!=c;L[R[c]]=c;R[L[c]]=c} B.map{|k|X[k.to_i,0,[],[],[]];z=z=='Z'?'a':z.next} s=->k{c=R[0];c<1?($><<(O[0,k].map{|s|N[s]}.transpose.map &:max)*""):(g=S[b=c];g=S[b=c]if S[c]<g while 0<c=R[c];Y[b];r=D[b];(O[k]=r;j=R[r];(Y[C[j]];j=R[j])while j!=r;s[k+1];r=O[k];c=C[r];j=L[r];(Z[C[j]];j=L[j])while j!=r;r=D[r])while r!=b;Z[b])} s[0] ``` The above ruby code is opposite to my GolfScript subscription. It is quite long (and not yet fully golfed), but optimized for speed. The killer sudoku given above is solved in well under a second (with my original java version it was only a few milli seconds). The solver itself is a basic implementation of Knuth's DLX algorithm. Input must be given as two lines on STDIN. Example ([online](http://ideone.com/FwlsD4)): ``` > AABBBCDEFGGHHCCDEFGGIICJKKFLMMINJKOFLPPQNJOORSPTQNUVVRSTTQWUUXXSYZWWaaXXSYZWbbbcc 3 15 22 4 16 15 25 17 9 8 20 6 14 17 17 13 20 12 27 6 20 6 10 14 8 16 15 13 17 215647398368952174794381652586274931142593867973816425821739546659428713437165289 ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/4772/edit). Closed 3 years ago. [Improve this question](/posts/4772/edit) Create a function that will output a set of distinct random numbers drawn from a range. The order of the elements in the set is unimportant (they can even be sorted), but it must be possible for the contents of the set to be different each time the function is called. The function will receive 3 parameters in whatever order you want: 1. Count of numbers in output set 2. Lower limit (inclusive) 3. Upper limit (inclusive) Assume all numbers are integers in the range 0 (inclusive) to 231 (exclusive). The output can be passed back any way you want (write to console, as an array, etc.) **Judging** Criteria includes the 3 R's 1. **Run-time** - tested on a quad-core Windows 7 machine with whatever compiler is freely or easily available (provide a link if necessary) 2. **Robustness** - does the function handle corner cases or will it fall into an infinite loop or produce invalid results - an exception or error on invalid input is valid 3. **Randomness** - it should produce random results that are not easily predictable with a random distribution. Using the built in random number generator is fine. But there should be no obvious biases or obvious predictable patterns. Needs to be better than that [random number generator used by the Accounting Department in Dilbert](http://dilbert.com/strips/comic/2001-10-25/) If it is robust and random then it comes down to run-time. Failing to be robust or random greatly hurts its standings. [Answer] ## Python ``` import random def sample(n, lower, upper): result = [] pool = {} for _ in xrange(n): i = random.randint(lower, upper) x = pool.get(i, i) pool[i] = pool.get(lower, lower) lower += 1 result.append(x) return result ``` I probably just re-invented some well-known algorithm, but the idea is to (conceptually) perform a partial Fisher-Yates shuffle of the range `lower..upper` to get the length `n` prefix of a uniformly shuffled range. Of course, storing the whole range would be rather expensive, so I only store the locations where the elements have been swapped. This way, the algorithm should perform well both in the case where you're sampling numbers from a tight range (e.g. 1000 numbers in the range 1..1000), as well as the case where you're sampling numbers from a large range. I'm not sure about the quality of randomness from the built-in generator in Python, but it's relatively simple to swap in any generator that can generate integers uniformly from some range. [Answer] ## python 2.7 ``` import random print(lambda x,y,z:random.sample(xrange(y,z),x))(input(),input(),input()) ``` not sure what your standing is on using builtin random methods, but here you go anyways. nice and short edit: just noticed that range() doesn't like to make big lists. results in a memory error. will see if there is any other way to do this... edit2: range was the wrong function, xrange works. The maximum integer is actually `2**31-1` for python test: ``` python sample.py 10 0 2**31-1 [786475923, 2087214992, 951609341, 1894308203, 173531663, 211170399, 426989602, 1909298419, 1424337410, 2090382873] ``` [Answer] **C** Returns an array containing x unique random ints between min and max. (caller must free) ``` #include <stdlib.h> #include <stdint.h> #define MAX_ALLOC ((uint32_t)0x40000000) //max allocated bytes, fix per platform #define MAX_SAMPLES (MAX_ALLOC/sizeof(uint32_t)) int* randsamp(uint32_t x, uint32_t min, uint32_t max) { uint32_t r,i=x,*a; if (!x||x>MAX_SAMPLES||x>(max-min+1)) return NULL; a=malloc(x*sizeof(uint32_t)); while (i--) { r= (max-min+1-i); a[i]=min+=(r ? rand()%r : 0); min++; } while (x>1) { r=a[i=rand()%x--]; a[i]=a[x]; a[x]=r; } return a; } ``` Works by generating x sequential random integers in the range, then shuffling them. Add a `seed(time)` somewhere in caller if you don't want the same results every run. [Answer] # Ruby >= 1.8.7 ``` def pick(num, min, max) (min..max).to_a.sample(num) end p pick(5, 10, 20) #=>[12, 18, 13, 11, 10] ``` [Answer] ## R ``` s <- function(n, lower, upper) sample(lower:upper,n); s(10,0,2^31-2) ``` [Answer] The question is not correct. Do you need uniform sampling or not? In the case uniform sampling is needed I have the following code in R, which has average complexity *O*(*s* log *s*), where *s* is the sample size. ``` # The Tree growing algorithm for uniform sampling without replacement # by Pavel Ruzankin quicksample = function (n,size) # n - the number of items to choose from # size - the sample size { s=as.integer(size) if (s>n) { stop("Sample size is greater than the number of items to choose from") } # upv=integer(s) #level up edge is pointing to leftv=integer(s) #left edge is poiting to; must be filled with zeros rightv=integer(s) #right edge is pointig to; must be filled with zeros samp=integer(s) #the sample ordn=integer(s) #relative ordinal number ordn[1L]=1L #initial value for the root vertex samp[1L]=sample(n,1L) if (s > 1L) for (j in 2L:s) { curn=sample(n-j+1L,1L) #current number sampled curordn=0L #currend ordinal number v=1L #current vertice from=1L #how have come here: 0 - by left edge, 1 - by right edge repeat { curordn=curordn+ordn[v] if (curn+curordn>samp[v]) { #going down by the right edge if (from == 0L) { ordn[v]=ordn[v]-1L } if (rightv[v]!=0L) { v=rightv[v] from=1L } else { #creating a new vertex samp[j]=curn+curordn ordn[j]=1L # upv[j]=v rightv[v]=j break } } else { #going down by the left edge if (from==1L) { ordn[v]=ordn[v]+1L } if (leftv[v]!=0L) { v=leftv[v] from=0L } else { #creating a new vertex samp[j]=curn+curordn-1L ordn[j]=-1L # upv[j]=v leftv[v]=j break } } } } return(samp) } ``` Of course, one may rewrite it in C for better performance. The complexity of this algorithm is discussed in: Rouzankin, P. S.; Voytishek, A. V. On the cost of algorithms for random selection. Monte Carlo Methods Appl. 5 (1999), no. 1, 39-54. <http://dx.doi.org/10.1515/mcma.1999.5.1.39> You may look through this paper for another algorithm with the same average complexity. But if you do not need uniform sampling, only requiring that all sampled numbers be different, then the situation changes dramatically. It is not hard to write an algorithm that has average complexity *O*(*s*). See also for uniform sampling: P. Gupta, G. P. Bhattacharjee. (1984) An efficient algorithm for random sampling without replacement. International Journal of Computer Mathematics 16:4, pages 201-209. DOI: 10.1080/00207168408803438 Teuhola, J. and Nevalainen, O. 1982. Two efficient algorithms for random sampling without replacement. /IJCM/, 11(2): 127–140. DOI: 10.1080/00207168208803304 In the last paper the authors use hash tables and claim that their algorithms have *O*(*s*) complexity. There is one more fast hash table algorithm, which will soon be implemented in pqR (pretty quick R): <https://stat.ethz.ch/pipermail/r-devel/2017-October/075012.html> [Answer] # APL, 18 22 bytes ``` {⍵[0]+(1↑⍺)?⍵[1]-⍵[0]} ``` Declares an anonymous function that takes two arguments `⍺` and `⍵`. `⍺` is the number of random numbers you want, `⍵` is a vector containing the lower and upper bounds, in that order. `a?b` picks `a` random numbers between 0-`b` without replacement. By taking `⍵[1]-⍵[0]` we get the range size. Then we pick `⍺` numbers (see below) from that range and add the lower bound. In C, this would be ``` lower + rand() * (upper - lower) ``` `⍺` times without replacement. Parentheses not needed because APL operates right-to-left. Assuming I've understood the conditions correctly, this fails the 'robustness' criteria because the function will fail if given improper arguments (e.g. passing a vector instead of a scalar as `⍺`). In the event that `⍺` is a vector rather than a scalar, `1↑⍺` takes the first element of `⍺`. For a scalar, this is the scalar itself. For a vector, it's the first element. This should make the function meet the 'robustness' criteria. Example: ``` Input: 100 {⍵[0]+⍺?⍵[1]-⍵[0]} 0 100 Output: 34 10 85 2 46 56 32 8 36 79 77 24 90 70 99 61 0 21 86 50 83 5 23 27 26 98 88 66 58 54 76 20 91 72 71 65 63 15 33 11 96 60 43 55 30 48 73 75 31 13 19 3 45 44 95 57 97 37 68 78 89 14 51 47 74 9 67 18 12 92 6 49 41 4 80 29 82 16 94 52 59 28 17 87 25 84 35 22 38 1 93 81 42 40 69 53 7 39 64 62 ``` [Answer] ## Scala ``` object RandSet { val random = util.Random def rand (count: Int, lower: Int, upper: Int, sofar: Set[Int] = Set.empty): Set[Int] = if (count == sofar.size) sofar else rand (count, lower, upper, sofar + (random.nextInt (upper-lower) + lower)) } object RandSetRunner { def main (args: Array [String]) : Unit = { if (args.length == 4) (0 until args (0).toInt).foreach { unused => println (RandSet.rand (args (1).toInt, args (2).toInt, args (3).toInt).mkString (" ")) } else Console.err.println ("usage: scala RandSetRunner OUTERCOUNT COUNT MIN MAX") } } ``` ### compile and run: ``` scalac RandSetRunner.scala scala RandSetRunner 200 15 0 100 ``` The second line will run 200 tests with 15 values from 0 to 100, because Scala produces fast bytecode but needs some startup time. So 200 starts with 15 values from 0 to 100 would consume more time. ### Sample on a 2 Ghz Single Core: ``` time scala RandSetRunner 100000 10 0 1000000 > /dev/null real 0m2.728s user 0m2.416s sys 0m0.168s ``` ### Logic: Using the build-in random and recursively picking numbers in the range (max-min), adding min and checking, if the size of the set is the expected size. ### Critique: * It will be fast for small samples of big ranges, but if the task is to pick nearly all elements of a sample (999 numbers out of 1000) it will repeatedly pick numbers, already in the set. * From the question, I'm unsure, whether I have to sanitize against unfulfillable requests like Take 10 distinct numbers from 4 to 8. This will now lead to an endless loop, but can easily be avoided with a prior check which I will append if requested. [Answer] # Scheme Not sure why you need 3 parameters passed nor why i need to assume any range... ``` (import srfi-1) ;; for iota (import srfi-27) ;; randomness (import srfi-43) ;; for vector-swap! (define rand (random-source-make-integers default-random-source)) ;; n: length, i: lower limit (define (random-range n i) (let ([v (list->vector (iota n i))]) (let f ([n n]) (let* ([i (rand n)] [n (- n 1)]) (if (zero? n) v (begin (vector-swap! v n i) (f n))))))) ``` [Answer] ## R ``` random <- function(count, from, to) { rand.range <- to - from vec <- c() for (i in 1:count) { t <- sample(rand.range, 1) + from while(i %in% vec) { t <- sample(rand.range, 1) + from } vec <- c(vec, t) } return(vec) } ``` [Answer] # C++ This code is best when drawing many samples from the range. ``` #include <exception> #include <stdexcept> #include <cstdlib> template<typename OutputIterator> void sample(OutputIterator out, int n, int min, int max) { if (n < 0) throw std::runtime_error("negative sample size"); if (max < min) throw std::runtime_error("invalid range"); if (n > max-min+1) throw std::runtime_error("sample size larger than range"); while (n>0) { double r = std::rand()/(RAND_MAX+1.0); if (r*(max-min+1) < n) { *out++ = min; --n; } ++min; } } ``` [Answer] ## Q (19 characters) ``` f:{(neg x)?y+til z} ``` Then use f[x;y;z] as [count of numbers in output set;starting point;size of range] e.g. f[5;10;10] will output 5 distinct random numbers between 10 and 19 inclusive. ``` q)\ts do[100000;f[100;1;10000]] 2418 131456j ``` Results above show performance at 100,000 iterations of picking 100 random numbers between 1 & 10,000. [Answer] ## R, 31 or 40 bytes (depending on the meaning of the word “range”) If the input has 3 numbers, `a[1], a[2], a[3]`, and by “range” you mean “an integer sequence from a[2] to a[3]”, then you have this: ``` a=scan();sample(a[2]:a[3],a[1]) ``` If you have an array `n` from which you are about to resample, but under the restriction of the lower and upper limits, like “resample values of the given array `n` from the range `a[1]...a[2]`”, then use this: ``` a=scan();sample(n[n>=a[2]&n<=a[3]],a[1]) ``` I am quite surprised why the previous result was not golfed considering the built-in sample with replacement facilities! We create a vector that satisfies the range condition and re-sample it. * Robustness: the corner cases (sequences of the same length as the range to sample from) are handled by default. * Run-time: extremely fast because it is built in. * Randomness: the seed is automatically changed every time the RNG is invoked. [Answer] ## Javascript (using external library) (64 bytes / 104 bytes??) ``` (a,b,n)=>_.Range(0,n).Select(x=>Math.random()*(b-a)+a).ToArray() ``` Link to lib: <https://github.com/mvegh1/Enumerable/> Code explanation: Lambda expression accepts min,max,count as args. Create a collection of size n, and map each element to a random number fitting the min/max criteria. Convert to native JS array and return it. I ran this also on an input of size 5,000,000, and after applying a distinct transform still showed 5,000,000 elements. If it is agreed upon that this isn't safe enough of a guarantee for distinctness I will update the answer I included some statistics in the image below... [![enter image description here](https://i.stack.imgur.com/FFY2R.png)](https://i.stack.imgur.com/FFY2R.png) EDIT: The below image shows code / performance that guarantees every element will be distinct. It's much much slower (6.65 seconds for 50,000 elements) vs the original code above for same args (0.012 seconds) [![enter image description here](https://i.stack.imgur.com/7H7O9.png)](https://i.stack.imgur.com/7H7O9.png) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 14 bytes **Solution:** ``` {y+(-x)?1+z-y} ``` [Try it online!](https://tio.run/##y9bNz/7/v7pSW0O3QtPeULtKt7I22sjU2tDA2tQg9v9/AA "K (oK) – Try It Online") **Example:** ``` > {y+(-x)?1+z-y}. 10 10 20 / note: there are two ways to provide input, dot or 13 20 16 17 19 10 14 12 11 18 > {y+(-x)?1+z-y}[10;10;20] / explicitly with [x;y;z] 12 11 13 19 15 17 18 20 14 10 ``` **Explanation:** Takes 3 implicit inputs per spec: * `x`, count of numbers in output set, * `y`, lower limit (inclusive) * `z`, upper limit (inclusive) --- ``` {y+(-x)?1+z-y} / the solution { } / lambda function with x, y and z as implicit inputs z-y / subtract lower limit from upper limit 1+ / add 1 (-x)? / take x many distinct items from 0..(1+z=y) y+ / add lower limit ``` **Notes:** Also a polyglot in `q/kdb+` with an extra set of brackets: `{y+((-)x)?1+z-y}` (16 bytes). [Answer] # Axiom + its library ``` f(n:PI,a:INT,b:INT):List INT== r:List INT:=[] a>b or n>99999999 =>r d:=1+b-a for i in 1..n repeat r:=concat(r,a+random(d)$INT) r ``` The above f() function return as error the empty list, in the case f(n,a,b) with a>b. In other cases of invalid input, it not run with one error message in Axiom window, because argument will be not of the right type. Examples ``` (6) -> f(1,1,5) (6) [2] Type: List Integer (7) -> f(1,1,1) (7) [1] Type: List Integer (10) -> f(10,1,1) (10) [1,1,1,1,1,1,1,1,1,1] Type: List Integer (11) -> f(10,-20,-1) (11) [- 10,- 4,- 18,- 5,- 5,- 11,- 15,- 1,- 20,- 1] Type: List Integer (12) -> f(10,-20,-1) (12) [- 4,- 5,- 3,- 4,- 18,- 1,- 2,- 14,- 19,- 8] Type: List Integer (13) -> f(10,-20,-1) (13) [- 18,- 12,- 12,- 19,- 19,- 15,- 5,- 17,- 19,- 4] Type: List Integer (14) -> f(10,-20,-1) (14) [- 8,- 11,- 20,- 10,- 4,- 8,- 11,- 3,- 10,- 16] Type: List Integer (15) -> f(10,9,-1) (15) [] Type: List Integer (16) -> f(10,0,100) (16) [72,83,41,35,27,0,33,18,60,38] Type: List Integer ``` ]
[Question] [ In this challenge you will receive as input a list of binary lists. The list represents a game board with each element representing a location on the board. The list at each location represents the tiles on the board, with a `0` being a white tile (□) and a `1` being a black tile (■). Each place can have any number of tiles and the order they appear in the list indicates how they are stacked, with the first element being the tile on the top of the stack and the last being on the bottom of the stack. For example here's a input list and a graphical representation of the game board: ``` [[0,0,1],[],[1,1],[1],[],[1,0]] □ □ ■ ■ ■ ■ ■ □ -+-+-+-+-+- ``` On a turn of this game the player can move by choosing any one place on the board and picking up all the tiles from that place, without disrupting their order. Then the player must choose a direction, either left or right. Then starting from the place they chose to pick from, until they have no tiles left in their hand they repeatedly choose to either: * Drop the tile at the bottom of the held stack at their current place. * Move to the adjacent place in their chosen direction. The player is not permitted drop any tiles out of bounds of the game board. Here's an example turn: ``` □ □ ■ ■ ■ ■ ■ ■ □ □ □ ■ -+-+-+-+-+- ``` Pick up two tiles from the second place from the left and move to the right: ``` □ ■ □ □ ■ ■ ■ ■ ■ □ □ ■ -+-+-+-+-+- ``` Drop 1 tile from the bottom back where it was picked up and move to the right: ``` □ ■ □ ■ ■ ■ ■ ■ □ □ □ ■ -+-+-+-+-+- ``` Drop no tiles and move to the right ``` □ ■ □ ■ ■ ■ ■ ■ □ □ □ ■ -+-+-+-+-+- ``` Drop two tiles and end. ``` □ ■ ■ □ ■ ■ ■ □ □ ■ □ ■ -+-+-+-+-+- ``` With that the goal of this game is simple. Using as few moves as possible arrange the board so that in every place the top tile is black. Here is an example game: ``` □ □ □ □ □ ■ ■ ■ ■ ■ -+-+-+-+- ■ □ □ □ □ □ ■ ■ ■ ■ -+-+-+-+- ■ □ □ □ □ □ ■ ■ ■ ■ -+-+-+-+- ■ □ □ □ □ □ ■ ■ ■ ■ -+-+-+-+- □ □ ■ □ □ □ ■ ■ ■ ■ -+-+-+-+- ■ □ □ □ □ □ ■ ■ ■ ■ -+-+-+-+- ``` Your task is take the starting board as input and determine the number of moves required to win. You can assume that the board is at least 2 places wide (the outer list contains at least two lists) and that there are enough black tiles to cover every space on the board (i.e. it is possible to solve) There are two arbitrary choices I have made. You may swap either, both or neither for the opposite choice: * `0` is white. You may instead assume `0` is black and `1` is white. * The first element is the tile on the top. You may instead assume the first element is the tile on the bottom and the last element is the tile on the top. You may also use suitable substitutions for `0` and `1` such as `True` and `False`, `1` and `-1`, etc. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. Brute force is fine, but I encourage you to try golf faster algorithms. Good golfs under self imposed constraints on time are always worth an upvote. ## Test cases ``` [[0,1],[0,1]] -> 3 [[0,1],[0,1],[0,1]] -> 3 [[1,1,1],[],[]] -> 1 [[1,0],[1],[1,1]] -> 0 [[0,1,0,1,0,1],[],[]] -> 2 ``` [Answer] # [Python 3](https://docs.python.org/3/), 237 bytes ``` g=lambda a,b,i,j:b and[*g(a[:i]+[[b[-1]]+a[i]]+a[i+1:],b[:-1],i,j),*g(a,b,i+j,j)]or[a]if-1<i<len(a)else[] f=lambda*b:+all(min(a)<[1]for a in b)and-~f(*sum([g(a[:i]+[[]]+a[i+1:],c,i,j)for a in b for i,c in enumerate(a)for j in[1,-1]],[])) ``` [Try it online!](https://tio.run/##bY5BjsMgDEX3PQVLCI5UNDuUnsRiYVpoiQip0nTRTa@e4kyljEaRwMLv8/19f823sfwsy/WUafAXEgQeEvTWCyoXbK6S0CanET22xjlNmH6rNtaBR1spGxTwXzbrvnZunJBciq3pUpdDkaRCfgR0h/hNarzVlLMcEosdGhfHSZBIRXhVs9t3lM3jOUjcdviTfF5DN4vgZ4IzN6E8hzDRHOpgxn2FaID3B3RKLfcplVlGiXiEuv5aKz/s8T3VgFkVPv@VY4Wsmb2Z8L2bd/kA "Python 3 – Try It Online") Brute force answer. [Answer] # Python3, 714 bytes: ``` E=enumerate def F(b): for i,a in E(b): for I,j in E(a): if j:yield(i,I,1) if 0==any(a[:I])and a[I]:yield(i,I,0) S=lambda b:sum(i!=[]and i[0]for i in b) def U(b,c,s,x,y,X,q,Q,h,R): B=eval(str(b));B[X]=B[x][:y]+B[X];B[x]=B[x][y:] if 0==h:c+=1;h=(X,y,X-x>=0) elif h[0]!=x or h[1]<y or(X-x>=0)!=h[2]:h=(X,y,X-x>=0);c+=1 else:h=[X,h[1]-y,h[2]] if(R==[]or c<min(R))and(B,c)not in Q: if S(B)>s:q.insert(0,(B,c,h)) else:q.append((B,c,h)) Q.append((B,c)) def f(b): q,Q=[(b,0,0)],[(b,0)] R=[] while q: B,c,h=q.pop(0) if(s:=S(B))==len(B):R+=[c] for x,y,r in F(B): for X,Y in E(B): if x!=X and(Y==[]or Y[0]==0): U(B,c,s,x,y,X,q,Q,h,R) if r:U(B,c,s,x,y+1,X,q,Q,h,R) return min(R) ``` [Try it online!](https://tio.run/##bVJNb@IwEL3zK8zNFlOUdC8r0@khUitxhGqlIMsHA0ZxFUxIQpf8enYmibS0Qkoi5735ePPGVdcWp/jrd1Xfbm/o4@Xoa9f6yd4fxLvcKj0Rh1MtAjgRongbkB5awucAuR4S4SA@dRd8uZcBlpCqEUwQXeykM3pplYt74czS3gUmavKBpTtu905sdXM5yjBFYzkymMT23bnRVvWi/sgt7KCBK3SQwxlWUMCaFWTov1wpm7YmkWqRmdxiZq7W6M7O@G/BfwPUaTsZtRV6N8N0UaDMueLT9RVJkfAl0QX1n@JVkITCpPalo5McQ6ZYmGerv@ctuBYnN54YkwOnPXXAoX1HuUaajertXo4hyrViR2QGOxVPLU@5Yi@p9YfM1Gujz/MQG1@3MgGOgkKxrX3989xVlafsO2J1j6nBsMOwM3IKDXmXkOEW@pMiSWuSMxF/i1B6cebefTE8z6tTJdkIFt1oZD0KsfSRDno9Q7Oz40XgTdSs/Z0p3jqjOWyG6zFiPNR1irnggTejCxsyGMk3LfoQWm72YLkDR/m1vguYpd9Cat9e6igGV29VHWIrD9KYBFIal7@WDHmEP2JTSHuGn59MQiBz6aOaML7/c2//AA) A little longer than it could be, but contains some optimizations. [Answer] # JavaScript (ES6), 198 bytes ``` f=(a,n=0)=>(F=(a,k)=>a.every(v=>v[0])|a.some((b,i,[...B],g)=>(B[i]=[],g=(d,q=b,x=i,A=B)=>q+q?A[x]&&g(d,q,x+d,A)|g(d,c=[...q],x,A.map(v=>x--?v:[c.pop(),...v])):k&&F(A,k-1))(1)|g(-1)))(a,n)?n:f(a,n+1) ``` [Try it online!](https://tio.run/##dY5NboMwEIX3PUVWaCwGx253SA6CRS5heeHwJ0KCIVQWlXJ36olalQW17NEbzfee52q9nctHN34mg6vqdW0UWByUYOoEZ9J9UJbXvn58gVcnr4VhT8tnd68BLtih5pwXBltyFLozSodGQYWTuuCiOsxVEWZTPGW5XkwUtTTDJa4wZ09qSkUZk8EFc363I/2zJEnmU13y0Y3AMMy9YSzto@gMOfaJZAwk2Ukx2pllQ9qQiCVbSzfM7lbzm2uhAa0FSoOvGlIOv@d4PHy8/Y9uDbuoRPnC6P7lBlTuoCJQBMvNEgEVewvgz9tkB/R9/QY "JavaScript (Node.js) – Try It Online") ### Commented ``` // outer recursive function with n = maximum number of moves f = (a, n = 0) => ( // inner recursive function with k = remaining number of moves F = (a, k) => // success if all leading terms are 1 a.every(v => v[0]) | // for each b[] at position i in a[] a.some((b, i, [...B], g) => // let B[] be a copy of a[] with the i-th term set to [] ( B[i] = [], // g is yet another recursive function taking: // a direction d // a vector q[], initially set to b[] // a position x, initially set to i // an array A[], initially set to B[] g = (d, q = b, x = i, A = B) => // if q[] is not empty q + q ? // if A[x] is defined (i.e. we're not out of bounds) A[x] && // do a recursive call where the position is updated g(d, q, x + d, A) | // do a recursive call where the position is unchanged and // the last element of q[] is added at the beginning of A[x] g(d, c = [...q], x, A.map(v => x-- ? v : [ c.pop(), ...v ])) // if q[] is empty : // if k is not equal to 0, process the next move k && F(A, k - 1) ) // invoke g with d = 1 (moving to the right) (1) | // invoke g with d = -1 (moving to the left) g(-1) ) // initial call to F // return n if successful, or try again with n + 1 )(a, n) ? n : f(a, n + 1) ``` ]
[Question] [ # Parenthetical names Your challenge is to build a program that puts parentheses around the 'title' part of names. For example, `Sonic the Hedgehog` is converted to `Sonic (the Hedgehog)`. ### Rules: * **Around every `the` that passes the following rules, an opening parentheses will be added *before* the `the` and a corresponding closing parentheses will be added at the end of the string.** * Inputs will only contain words (uppercase/lowercase letters and spaces). * Trailing `the`s are ignored. * With more than one `the`s in a row, every other `the` is parenthesized. (So `pig the the the hog hog hog` turns into `pig (the the (the hog hog hog))`.) * Remaining `the`s are skipped unless surrounded by spaces. For example, the `the` in `their` would not be parenthesized. #### I know this may seem lacking in detail. However, it's hard to get one set of really specific guidelines working- just follow the above rules and you're good. Inspired by this xkcd comic: <https://xkcd.com/2252/> This is `code-golf`, so least number of bytes wins. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 27 bytes ``` \b(the )+ (the .*) & (\1) ``` [Try it online!](https://tio.run/##KyxNTCn6/z8mSaMkI1VBU5tLAczQ09LkUgOyYww1//8HCRRkpnMBsUJGPoQGiaGxFWDq0PkwNVDx/486FwIA "QuadR – Try It Online") `\b(the )+` replace multiple `the`s with: …`&` themselves `(the .*)` replace a space followed by `the` and everything until the end with: … `(\1)` a space followed by the parenthesised text [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 27 bytes ``` +`(?<!\bthe) (the .+) ($1) ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0HD3kYxJqkkI1VTQQNIKuhpa3IpaKgYav7/D@IWZKZzgWgYG4gVMvIhNEgMja2ArAeZD1MDFQcA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Parenthesises from all `the` s to the end of the line, unless the `the` follows a previous `the`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` ≔⪪S θ≔⌕Aθtheη≔⁻η⁺⊕η⟦⁰⊖Lθ⟧η⪫Eθ⁺×№ηκ(ι ⭆η) ``` [Try it online!](https://tio.run/##RY7BCsIwEETv/YrQ0wYqePdUFKGiUKg38VDakCymSdqk/n7c1GoPSZa82ZnpVDt1ttUxlt6jNNA4jQEq4@bQhAmNBF6wnOV0j/yQraozmr7UGkZiQYlE1UZvaGYPqmC1prcy3SQGYYLoQZHwsS/YSWx/V2FkUDBy/uSrT03BAS4Wyat1KWVxuuMgPBztTJDcX6kZpGzka8n/7rd7WiZhzhOJkZqydBxK9puVXeYs7t76Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪S θ ``` Split the input on spaces. ``` ≔⌕Aθtheη ``` Find all the indices of `the`. ``` ≔⁻η⁺⊕η⟦⁰⊖Lθ⟧η ``` Remove any index that's `1` more than another index, and `0` and the last index (because those `the`s weren't surrounded by spaces). ``` ⪫Eθ⁺×№ηκ(ι ``` Prefix `(` to the remaining indices and join with spaces. ``` ⭆η) ``` Output the matching `)`s at the end. A port of @Steffan's Python answer is also 40 bytes: ``` ⪫⪪⪫⪪S the ¦ (the ¦the (the¦the the×)№KA( ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPI7ggJxOF6ZlXUFoSXAJUka6hqaOgpFCSkaqgBGZpwJkgBogH54DZmtZcEJNDMnNTizWUNJV0FJzzS4ECAamp2Y45OWADgeJAlf//Q7UpFGSmK8DYGflgNtd/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⪫⪪⪫⪪S the ¦ (the ¦the (the¦the the ``` Substitute `the` with `(the` and `the (the` with `the the`. ``` ×)№KA( ``` Output enough `)`s to match the number of `(`s. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „ €€ÀDć'(©«ì:…€€ (8∍D®K:D®¢')׫ ``` Port of [*@Steffan*'s Python answer](https://codegolf.stackexchange.com/a/248426/52210). [Try it online](https://tio.run/##yy9OTMpM/f//UcM8hUdNa4DocIPLkXZ1jUMrD60@vMbqUcMyiLCChsWjjl6XQ@u8rYDEoUXqmoenH1r9/39BZrpCSUaqQkY@hIbyAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0cN8xQeNa0BosMNLkfa1TUOrTy0@vAaq0cNyyDCChoWjzp6XQ6t87YCEocWqWsenn5o9X@d/yUZqQoFmelcQKwAZIPpjHw4H8wG0WjqQOJwMXQ@TA1MP7IemHqoWhR1MDaSGFZ7YWaguQUA). **Explanation:** ``` : # Replace all „ €€À # " the ": „ €€ # Push dictionary string " the" À # Rotate it once towards the right: " the " Dć'(©«ì '# with " (the ": D # Duplicate the " the " ć # Extract the head '( '# Push "(" © # Store it in variable `®` (without popping) « # Append it to the extracted space ì # Merge it in front of the remaining string: " (the " : # Then replace all …€€ (8∍ # "the (the": …€€ ( # Push dictionary string "the (" 8∍ # Extend it to size 8: "the (the" D®K # with "the the": D # Duplicate the "the (the" ®K # Remove the `®` ("("): "the the" D # Duplicate the resulting string ®¢ # Pop the copy, and count the amount of `®` ("(") in it ')× '# Pop and push a string with that many ")" « # Append it at the end of the string # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„ €€` is `" the"` and `…€€ (` is `"the ("`. [Answer] # [Python](https://www.python.org), 93 bytes ``` lambda s,t='the',r=' (',w=' ':(p:=s.replace(w+t+w,r+t+w).replace(t+r+t,t+w+t))+p.count(r)*')' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVFLDoIwEI1bT9HERTu2sjYkvYkuEEFIUJpSQjyLGxKjd9J7uLeET9pSuujnzXvzZqaPt7irrLy1z5QfXrVKd_vPsYiup3OEKqY4VlmCmeQYEcwafeCQiJBXgUxEEcUJaaiiDZPdDhOoqAaYhqgCoCKIy_qmiIQtBtybfFc_IXMNpqSzQCK_YADkrg2aouuJr18oK5f4Y9Tmd1k8moFPhjD4Vcip0FH1F42AqV_QGl1ZUo-zp2bT2VPzCHumOXjOp2mgrqutWXQduszl3FdnsKP977dtf_4B) # [Vyxal](https://github.com/Vyxal/Vyxal), 31 bytes ``` ⌈D‛λλÞIf$L‹o:›Fꜝλ\(p;VṄ:\(O\)*J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIhE4oCbzrvOu8OeSWYkTOKAuW864oC6Ruqcnc67XFwocDtW4bmEOlxcKE9cXCkqSiIsIiIsInRoZSB0aGUgcGlnIHRoZSB0aGUgaG9nIHRoZSJd) Port of Charcoal answer. [Answer] # Python3, 116 bytes: ``` import re f=lambda x,c=0:re.sub(f'(?<{"!="[c]}e) the {["","[^t]"][c]}[\w\W]+',lambda x:f' ({f(x.group()[1:],1)})',x) ``` ]
[Question] [ I want to avoid responding to illegal or spoofed addresses. One type that's easy to detect is an address that should not exist on a packet received by my router: a special-use address. ## Challenge Given an IPv4 32-bit address, identify whether it is valid general-use address. ## Challenge rules * Special-use addresses, as defined by the Internet Engineering Task Force, are considered invalid. * Special-use addresses are listed at <https://en.wikipedia.org/wiki/IPv4#Special-use_addresses>. A copy of the list (omitting explanatory columns) is below. * Input will be a character sequence in the dot-decimal notation, consisting of four positive decimal numbers (called "octets") each in the range 0–255 separated by periods (e.g., 169.254.0.31). Each octet represents an 8-bit segment of the address. * Output must indicate true or false, using any two indicators of your choice for true and false. ## 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: * 192.0.0.254 false * 192.0.1.254 true * 0.255.0.0 false * 128.2.3.82 true * 253.8.22.37 false * 203.0.114.201 true ## Special-use addresses | Address Block | Address Range | | --- | --- | | 0.0.0.0/8 | 0.0.0.0–0.255.255.255 | | 10.0.0.0/8 | 10.0.0.0–10.255.255.255 | | 100.64.0.0/10 | 100.64.0.0–100.127.255.255 | | 127.0.0.0/8 | 127.0.0.0–127.255.255.255 | | 169.254.0.0/16 | 169.254.0.0–169.254.255.255 | | 172.16.0.0/12 | 172.16.0.0–172.31.255.255 | | 192.0.0.0/24 | 192.0.0.0–192.0.0.255 | | 192.0.2.0/24 | 192.0.2.0–192.0.2.255 | | 192.88.99.0/24 | 192.88.99.0–192.88.99.255 | | 192.168.0.0/16 | 192.168.0.0–192.168.255.255 | | 198.18.0.0/15 | 198.18.0.0–198.19.255.255 | | 198.51.100.0/24 | 198.51.100.0–198.51.100.255 | | 203.0.113.0/24 | 203.0.113.0–203.0.113.255 | | 224.0.0.0/4 | 224.0.0.0–239.255.255.255 | | 240.0.0.0/4 | 240.0.0.0–255.255.255.255 | Note on address blocks. This is a shortcut method of listing an address range, called CIDR notation. The notation is four octets followed by a slash and a decimal number. The decimal number is the count of leading 1 bits in the network mask, and indicates how many leading bits in the underlying 32-bit address range are specified as fixed. For example, a mask of 24 indicates that only the last 8 bits of the address range vary. Thus writing 192.0.2.0/24 indicates that only the last octet varies. The range for 192.0.2.0/24 is 192.0.2.0–192.0.2.255. [Answer] # JavaScript (ES6), ~~179~~ 178 bytes *Saved 1 byte thanks to @[StackMeter](https://codegolf.stackexchange.com/users/100887/stackmeter)'s suggestion of merging the last 2 blocks* Expects a string and returns a Boolean value. ``` s=>'00000g0chhqo3h65u64ekjyo5w90qw5yu2vg6nq96o6nq98g6o5rvk6ojr486vb4096vgz2871grvk7romqd'.match(/.{6}/g,[a,b,c]=s.split`.`).every(S=>(x=parseInt(S,36))>>5^(a<<16|b<<8|c)&-(1<<x)) ``` [Try it online!](https://tio.run/##fY6xboMwFEX3fgVTsSVibIMNSMDeOWPVKo5jTBKCg01I0qbfTmGqqlbcJ93h6ejoHsQgnLT7c79qzU6NVTG6ovTxHI1lXXcmqjm78FgdD3fDrhnurux@oYPmbZdxM3equWF2OHJzsHHKh22MMz7oD5omRE//xJpTt/PRSfSyBiH65F@hDl5FsA3kW@GQOzf7foM2EKlB2TtYFyW4FWdhnXppe7AOIg5hWbJ3IPKc8Mc2z9OHhM8rQPL8BuEoTetMo1BjNKiATzKK8HSUxb7nQeiFoVeJxqmnf0HyC@zt5Q83q9isnKhlIU0RRRFKqe8tCSmbGEQnNFleSHE0LyQxopj4P8LxGw "JavaScript (Node.js) – Try It Online") ## How? ### Encoding of address blocks Our data string encodes all blocks of special-use addresses. We can notice that the 4th byte is always \$0\$ and can be ignored. Given a block in CIDR notation `A.B.C.D/M`, what's actually encoded is: ``` A << 21 | B << 13 | C << 5 | (24 - M) ``` This is a 29-bit value which fits in 6 characters in base 36. For instance, `169.254.0.0/16` is encoded as: ``` 169 << 21 | 254 << 13 | 0 << 5 | (24 - 16) = 356499464 ``` which is `5w90qw` in base 36. ## IP test Given an IP address \$s\$, we first extract the first 3 bytes into \$(a,b,c)\$ and ignore the 4th one: ``` [a, b, c] = s.split`.` ``` For each 29-bit encoded block address \$x\$, we do the following test: ``` x >> 5 ^ (a << 16 | b << 8 | c) & -(1 << x) ``` where `-(1 << x)` is our 24-bit subnet mask. Conveniently, we can do `1 << x` without isolating the 5 least significant bits of \$x\$ because this is done implicitly by the shift operations, by ECMAScript specification. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 138 bytes ``` \. - 2=`\d+ $* ^(0|10|100-1{64,127}|127|169-1{254}|172-1{16,31}|192--[02]|192-1{88}-99|192-1{168}|198-1{51}-100|203--113|22[4-9]|2[3-5].)- ``` [Try it online!](https://tio.run/##LY09DsIwDIV3nwOkAnUUvzRpMjBziLaoSDCwMCC2pmcPTkG27O/59/34PF@3sm8ucxkNMeE8j/cT7Y50bWyW6pZlCV0r6NesIUtIWoHvVPZQlNA6UZHAPFhMG8kS48op/YWEWCeiopeV9WqGdcwiLgNDx2nKGBz7yRy4FF0yVk2/0I9l41rxtUOCaGCciSB4TQaqetKjdVg6Aytf "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `1` for special use, `0` for general use. Explanation: ``` \. - ``` Change the `.`s to `-`s because `.`s are special in regex. ``` 2=`\d+ $* ``` Convert the second octet to unary. ``` ^(0|10|100-1{64,127}|127|169-1{254}|172-1{16,31}|192--[02]|192-1{88}-99|192-1{168}|198-1{51}-100|203--113|22[4-9]|2[3-5].)- ``` Match the given special use addresses. [Answer] # Python 3 - 307 bytes ``` a=input() f=int b,c,d,e=a.split(".") b,c,d,e=f(b),f(c),f(d),f(e) print(not(not(b==0or b==10or (b==100and 63<c<128)or b==127or(b,c==169,254)or(b==172and 15<c<32)or(b,c,d==192,0,0)or(b,c,d==192,0,2)or(b,c,d==192,88,89)or(b,c==192,168)or(b==198and 17<c<20)or(b,c,d==198,51,100)or(b,c,d==203,0,113)or b>223))) ``` [Try it online!](https://tio.run/##ZY7LjoMwDEX3fAXqKpY8KHYKBIn0X3gUFWkUIkoXfD116EPtzMKv6@sjh3W5TN78hDWs29a40YfboiAZUpeOfkla7LDHs2uya/gdF3XIDvAWB9UCDqqLqY/pDEmY5Uz56RGtc3qaUykUq9ob3fg@LUzd1cQWnmsup1kJWNqiQs6PEGeZSo52ysVuGB4m7GVRMWrU/5S/HmvRVvCGi0KFfcEru8NLgfM3ymJOKL9@iKyN8InM/vOJ2QDAtpGmjEiCTcaG7g "Python 3 (PyPy) – Try It Online") Fun challenge - hooray for conditionals! Just runs the appropriate tests and gives a value of true or false (the not(not()) was necessary, else it would return a tuple for some reason). Fairly optimized for the method (I did use b,c,d == instead of b == and c == and d ==, and stripped many spaces), but this could easily be golfed by someone better. (-34 from Razetime) [Answer] # JavaScript, 154 bytes ``` s=>[[a,b,c]=s.split`.`,a-10,a%127,a<224,(b|=a<<8)>>6^401,b>>4^2753,b/2^25353,b-43518,b-49320,b-49152|c&-3,d=b-49240<<8|c-99,d-383745,d-698382].some(x=>!x) ``` [Try it online!](https://tio.run/##jZTfboIwFMbv9xa72ISkdO1pgTYTXsRohqiLixMzzOKF785aEE2Uc1gIoeTj953TPx9fxW9Rlz/bwzHaV6t1s8maOstns4ItWTnPal4fdtvjB/9gRSQFK14kpKyYAmgWLM9ZMZ2aMM@ThRaSLfNcLyCNFVu@wQJi5UeRVrE0/mkViPYpYziXr5Fiq8y/ghbO5VxG1rJVpIxKdewGiTXKwJzX1fc6OGX58ylsympfV7s131WfwSaYCN5ekzB8f3qQII77e@gDScDyH7TgicZ5wd06kQZOxuvfWJRPrJPwDi4y5ZAClwlq4FQlSd4CMYOLSLJAsUCxxnBrcbqTCV4mhurcy@TMDZeEgVPtGB9L7k@JGNERBxDKlZdSDRvcZIwHje8dKDt2@lxkCf7GXvmHKV7xe@W@9gOJo20oFcW2uTQYDslY7Y4dptvEkdWTbm4I7@NIFveJBIy2cqz3NlUSoTuNIhVK@rQZgnV6f9SHw5aOtO0XDuOdN427zgRBu5xdfxVoDodXrU8ZIHiv62Ea1N2ONX8 "JavaScript (Node.js) – Try It Online") This answer simply translate the table to a formula. | Address block | Address range | Formula | | --- | --- | --- | | 0.0.0.0/8 | 0.0.0.0 ~ 0.255.255.255 | `[a,b,c]=s.split`.`,a%127` | | 10.0.0.0/8 | 10.0.0.0 ~ 10.255.255.255 | `a-10` | | 127.0.0.0/8 | 127.0.0.0 ~ 127.255.255.255 | `a%127` | | 224.0.0.0/4 | 224.0.0.0 ~ 239.255.255.255 | `a<224` | | 240.0.0.0/4 | 240.0.0.0 ~ 255.255.255.255 | `a<224` | | 100.64.0.0/10 | 100.64.0.0 ~ 100.127.255.255 | `(b|=a<<8)>>6^401` | | 172.16.0.0/12 | 172.16.0.0 ~ 172.31.255.255 | `b>>4^2753` | | 198.18.0.0/15 | 198.18.0.0 ~ 198.19.255.255 | `b/2^25353` | | 169.254.0.0/16 | 169.254.0.0 ~ 169.254.255.255 | `b-43518` | | 192.168.0.0/16 | 192.168.0.0 ~ 192.168.255.255 | `b-49320` | | 192.0.0.0/24 | 192.0.0.0 ~ 192.0.0.255 | `b-49152|c&-3` | | 192.0.2.0/24 | 192.0.2.0 ~ 192.0.2.255 | `b-49152|c&-3` | | 192.88.99.0/24 | 192.88.99.0 ~ 192.88.99.255 | `d=b-49240<<8|c-99` | | 198.51.100.0/24 | 198.51.100.0 ~ 198.51.100.255 | `d-383745` | | 203.0.113.0/24 | 203.0.113.0 ~ 203.0.113.255 | `d-698382` | [Answer] # [Python 3](https://docs.python.org/3/), 248 bytes ``` b,c,d,e=[*map(int,input().split("."))] a=192 print(not(not(b==0 or b==10or(b==100and 63<c<128)or b==127or(b,c==169,254)or(b==172and 15<c<32)or(b,c,d in[a,0,0],[a,0,2],[a,88,89],[198,51,100],[203,0,113])or(b,c==a,168)or(b==198and 17<c<20)or b>223))) ``` [Try it online!](https://tio.run/##NY/BCsIwDIbvPsXw1EgoTeq2FpwvMnaom@BAuzLnwaefsdND@BPywZek93Kbol3XC/Y44LVpD4@Q1BgXHGN6LQr0M93HRe31HqDbhYY879IsgIrTVpemMcU0F5JkplnlNCEORWVP/YnYwW/L9XeNvbSVRy6P8MNr/uJUCm4ZNgiHYoxtQIOmw5yc0zl0XjryDktCUcnAxgpAZDv4KwJS5f4C77KgFgGbfM6Z2QLAuspD2mjScs4H "Python 3 – Try It Online") -1 byte thanks to hyper-neutrino [Answer] # [Python 3](https://docs.python.org/3/), 173 bytes ``` a,b,c,d=map(int,input().split(".")) b|=a<<8 d=b-49240<<8|c-99 print(214>a-10!=0<a%127<b>>6!=401>0<b>>4^2753<25353!=b>>1<43518!=b!=49320>b-49152|c&-3!=0!=d!=383745<698382!=d) ``` [Try it online!](https://tio.run/##XZJBb6MwEIXv/AqCtCuQEssztsGOgFsPPe2l50pAkBptN0Es1bZS/nt2HIzBDUp4vOcZxp8zfE1v14u4d9dTH1dxkiT3Zt/uu/2p@tMM6fky7c@X4WNKM/Z3eD9PacKSLIvaW9WUpY5OVXuQBiWnh1t3MCYaRqpJEWTdHIDvKl42PwCLsq3rfFdJDjW3Wr5ioUSJSiixq8iAUgoFmjStMgJ5bTuDwlv380BLqNVpVwktCqnK3GihkZzsThNH0b@383sfv4wf/TGK6TONX8e4/@y71O4re3j9Z9cPU/z862kcr@Mxbse@@X3n7HFFnKFSyzeCxYbvPme5dAlntK81Iu1qVndOckN3V@W0zwpkkM8RSQFrYnDp59TqonfRu1ozY5w/6yWBXPs@Vq9v0AyWiKQJEgXMbpFvH2yGXFAJAP1u9CNB6SZGYQIC9P9YktWd3@T8cD2Ax0@8RYAf0I2MeVgz@56x@MZfecigAvwCHQII@z34gicNG1dsOOvtCSzELOgiaGWH8KSLgDRytuHsD85Rhw1nDE5A2gRFMPV/ "Python 3 – Try It Online") Never write `a!=10and a!=127` in python [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! [try `10!=a!=127` instead!](https://codegolf.stackexchange.com/a/60/44718) ]
[Question] [ Your task here is to take a LifeOnTheEdge pattern and convert it to LifeOnTheSlope. A LifeOnTheEdge pattern is composed of these four characters: `|_L` . A pattern corresponds to a certain arrangement of "on" edges in a square grid. The pattern is placed in the grid first with the characters in the cells, and each of the four letters specifies the state of the edges on the left and the bottom of that cell. `|` means the edge on the left is on, `_` means the bottom edge is on, `L` means both of them are on and means neither of them are on. For example the following LifeOnTheEdge: ``` |_L | ``` translates to: ``` . . . . . | | . ._._. . | . . . . . ``` Your task is however convert it to LifeOnTheSlope. LifeOnTheSlope is a LifeOnTheEdge equivalent but only uses three symbols: `/\` . You should rotate the pattern 45-degree clockwise, for example the above example translates to: ``` / /\/ \ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. EDIT: You can have leading and/or trailing spaces/newlines as long as the output itself (somewhere on the screen) is correct. ## Test Cases ``` Input: |_L | Output: / /\/ \ Input: | _L L_| L_| L_| L_| | | Output: / /\/ /\ \ /\ \/ /\ \/ \ \/ /\/ / Input: __ __ __ __ __ __ __ | | | ||L_ |_ | || L_ L_ L_|_L|L_ L_|L_|L | Output: /\ / \ \ \ /\ / \ \ / \/ \ /\ \/ / \/ /\ /\ \ \ \ \ /\ / \ \ \ \/ /\ / \ \ / \/ / / \ /\ /\ \ \ ``` ``` [Answer] # JavaScript (ES6), ~~135 120~~ 119 bytes *Saved 16 bytes thanks to @Shaggy!* Expects either an array of strings or a matrix of characters. Returns a matrix of characters. ``` a=>[...a,...a[0]].map((_,y,b)=>b.map((_,x)=>'\\/ '[(c=(a[~(x-=y+a.length)>>1]||0)[x+y-~y>>1])=='_|'[x&=1]|c=='L'?x:2])) ``` [Try it online!](https://tio.run/##VY7NboQgFIX3PgWrcskonXbZBGfVrtzNEg1hGHScWLBgG03IvLoFm/6Fy@Wcez4IV/khvXL9OBXGnvXaslWyklNKZZ4a3zcNfZUjgMiX/ERYefq2czS4ru8R5qAYSH6DuWDLTtJBm266kLJ8aELYEz7vluK2JEsYwyJgPt@xmKnoKnyYnx4bQlan3957pwG3HhPqtDy/9IM@LkbBntDJHifXmw4I9ePQT4BrU5sIttY9S3UBj1iJlDXeDpoOtoMW/C@KCdn@7RLl6NX2BnAafqkNIGsQVYYCymLLoqxE@LdTFJNMCPRT6M@ZBRSRuEIVPQpi0yg9hOJ9UYUqgVGmQuET "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` WS«P↘⭆ι§ /№|Lκ↓P↘⭆ι§ \№_Lκ← ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1OhmovTtzSnJLMAKFCiYeWSX54XlJmeUaKjAFHjm1igkamj4FjimZeSWqGhpKCvpKPgnF8KVKxU4wNkZ2sCgTXQlPyyVIh@MI8kM2NiEIbGYxrqk5pWAuTV/v9fE@/DpVDD9V@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list. Explanation: ``` WS« ``` For each line in the list... ``` P↘⭆ι§ /№|Lκ ``` Diagonally print `/`s for `|`s and `L`s otherwise print spaces. ``` ↓ ``` Move to the next line. ``` P↘⭆ι§ \№_Lκ ``` Diagonally print `\`s for `_`s and `L`s otherwise print spaces. ``` ← ``` Move to the previous column. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~195~~ 186 bytes ``` T,N,a,A,b,x,y,z;f(m,X,Y)char*m;{for(x=T=y=0;x<Y*3;x++,y++,T+=~Y)for(z=X-~Y,a=x,b=y;z--;T++,b--)A=a++/2-Y,N=m[A+b/2*X],putchar(z?(A|b)>=0&A<X&b<Y*2?T%2?N%19?32:92:(N-76)%48?32:47:32:10);} ``` [Try it online!](https://tio.run/##PU3NisIwGLz7FEGoJM0XrKms2vhtyV166qFBFkkKVQ91F3EhrdVX76aXhZmB@YGpxbmux7GEAixocOChg141tIUKDKsv9h636tl836nHEjtMlN@bOFWec@gCS45vw6a@x0q8DVj04LBTvRCqDAMnBNNoOV9KYaDA9qi5W8q4@oKf38d0QPuc6sGxT0wWel8tXDiQeRnJvIhWuzyV2U5mtBCbDxatt5Nfb7Kgq4Sp13i9PUhrrzfKnjPS0DkZyOlADqfhHyEJmEMKW6Zmr/EP "C (gcc) – Try It Online") * Saved 11 thanks to @ceilingcat Example size X=3, Y=2 ``` 00 10 20 (x,y) indexes 01 11 21 of LOnH mapped to below -2 0|-2 0|-1-1|-1-1| 0-2| -2 0|-1 0|-1 0| 0-1| 0-1| -1 1|-1 0| 0 0| 0 0| 1-1| -1 1| 0 1| 0 0| 1 0| 1 0| 0 2| 0 1| 1 1| 1 0| 2 0| 0 2| 1 2| 1 1| 2 1| 2 0| 1 3| 1 2| 2 2| 2 1| 3 1| 1 3| 2 3| 2 2| 3 2| 3 1| ``` We start with x=-Y,y=0 We decrement x / increment y every 2 on first column and we do the inverse on each row. Then we mask taking only valid indexes. ``` | | | | | | | | | | | | 0 0| | | | 0 1| 0 0| 1 0| | | 0 1| 1 1| 1 0| 2 0| | | 1 1| 2 1| 2 0| | | | 2 1| | | | | | | ``` Now we have doubled (x,y) pairs one for `|`,`L` and the second for `_`,`L` ]
[Question] [ (Note: this challenge is distinct from my other challenge ([Draw a path made from direction changers](https://codegolf.stackexchange.com/questions/179083/draw-a-path-made-by-direction-changers)) because of it's rendering of direction (horizontal or vertical), crossing points and single or double paths.) --- Let's start with a frame drawn in Ascii characters. For this challenge it will always be 20 characters wide and 10 characters high. ``` +--------------------+ | | | | | | | | | | | | | | | | | | | | +--------------------+ ``` It will begin populated with one of a number of objects: ``` | Name | Char | Description | | Source | * | This will send a path to the North | | East | > | Any path meeting this will turn to the East | | West | < | Any path meeting this will turn to the West | | North | ^ | Any path meeting this will turn to the North | | West | V | Any path meeting this will turn to the South | ``` Your job will be to start with the objects above, and populate the grid with these characters, which will display the path they describe. ``` | Name | Char | Description | | Vertical path | | | The path is travelling North or South | | Horizontal path | - | The path is travelling East or West | | Double Vertical path | N | The path is doubled and is travelling North or South | | Double Horizontal path | = | The path is doubled and is travelling East or West | | Crossing point | + | A North/South path and an East/West path have met | | Double crossing point | # | A North/South path and an East/West path have met and one or both are doubled | ``` # Path drawing rules When a path meets either the edge of the map or a source, it will stop there. If a path meets a direction changer, they will go in it's direction, using the direction changer as a starting point, e.g.: ``` +--------------------+ | | | | | >---------------| | | | | | | | | | | | | | * | | | | | +--------------------+ ``` If a direction changer tells a path to go back the way it came, it will display a double path e.g.: ``` +--------------------+ | | | | | | | >====< | | | | | | | | | | | * | | | | | +--------------------+ ``` If two paths cross, they will meet with a + symbol. E.g.: ``` +--------------------+ | | | | | | | | | | >---+-----------| | | | | | | * | | | | | * | | | | | +--------------------+ ``` If two paths cross, and one or both are doubled back, they will meet with a # symbol. E.g.: ``` +--------------------+ | | | | | | | | | | >===#===< | | | | | | | * | | | | | * | | | | | +--------------------+ ``` If two paths meet the same direction changer from different directions, the ongoing path is merged (doubled up). E.g.: ``` +--------------------+ | N | | N | | >-^-< | | | | | | | | | | * * | | | | | | | | | +--------------------+ ``` Doubled paths are immutable, they can not be un-doubled or become any heavier than double paths. # The rules * It's code golf, try to write short code to do this. * Input and output are agnostic, I don't really mind about strings, arrays of chars, trailing and leading space etc. as long as I can see the outcome. * Standard loopholes etc. * Use any language you like. * Please include a link to an online interpreter. # Test cases ## Simple In: ``` +--------------------+ | | | | | | | | | | | | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | | | | | | | | | | | | | | | | * | | | | | +--------------------+ ``` ## One turn In: ``` +--------------------+ | | | | | > | | | | | | | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | >---------------| | | | | | | | | | | | | | * | | | | | +--------------------+ ``` ## Spiral In: ``` +--------------------+ | | | | | | | < | | | | > V | | | | * | | ^ < | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | |--< | | | | | | >--V | | | | | | | | * | | | ^----< | | | +--------------------+ ``` ## Reflect In: ``` +--------------------+ | | | | | | | > < | | | | | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | >====< | | | | | | | | | | | * | | | | | +--------------------+ ``` ## Two Sources In: ``` +--------------------+ | | | | | | | > | | | | * | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | | | | >---+-----------| | | | | | | * | | | | | * | | | | | +--------------------+ ``` ## One Doubles Back In: ``` +--------------------+ | | | | | | | > < | | | | * | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | | | | >===#===< | | | | | | | * | | | | | * | | | | | +--------------------+ ``` ## Path Meets Source (Note that the path ends at the source, and does not join the other path and double up) In: ``` +--------------------+ | | | | | | | | | | | > * | | | | * | | | | | +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | | | | | | | | | | >---* | | | | | * | | | | | +--------------------+ ``` ## Paths Merging In: ``` +--------------------+ | | | | | > ^ < | | | | | | * * | | | | | | | | | +--------------------+ ``` Out: ``` +--------------------+ | N | | N | | >-^-< | | | | | | | | | | * * | | | | | | | | | +--------------------+ ``` ## Full Spiral In: ``` +--------------------+ | > V | | > V | | > V | | > V | | >V | | * | | ^ < | | ^ < | | ^ < | | ^ < | +--------------------+ ``` Out: ``` +--------------------+ | >--------V | | |>------V| | | ||>----V|| | | |||>--V||| | | ||||>V|||| | | ||||*||||| | | |||^-<|||| | | ||^---<||| | | |^-----<|| | | ^-------<| | +--------------------+ ``` ## Let's Have Some Fun In: ``` +--------------------+ | | | | | V V V V | |> <| |^ <| | < | |> ^ | | | | * * * * * * * * | |* *| +--------------------+ ``` Out: ``` +--------------------+ | | | | | | | | | | | | | V | V | V | V | | |>=#=#=#=#=#=#=#=#==<| |^-#-+-#-+-#-+-#-+--<| |--#-+-#-+-#-+-#-+-<|| |>-#-+-#-+-#-+-#-+-^|| || N | N | N | N | || || * * * * * * * * || |* *| +--------------------+ ``` ## Almost all cells visited twice In: ``` +--------------------+ |> V| | > V | | > V | | >V>V>V>V>V>V>V | | | | *>^>^>^>^>^>^ | | ^ < | | ^ < | | V<V < | |^<^<^ <| +--------------------+ ``` Out: ``` +--------------------+ |>==================V| |N>================VN| |NN>==============VNN| |NNN>V>V>V>V>V>V>VNNN| |NNN||NNNNNNNNNNNNNNN| |NNN*>^>^>^>^>^>^NNNN| |NN^=#===========<NNN| |N^==#============<NN| |NV<V#=============<N| |^<^<^==============<| +--------------------+ ``` Happy Golfing :) [Answer] # JavaScript (ES6), ~~201 197~~ 195 bytes Takes input as a matrix of characters. Outputs by modifying the input. ``` f=(m,X,Y,k,d)=>m.map((r,y)=>r.map((c,x)=>~(s=' -|=N+#^<V>',i=s.indexOf(c))?k&&x%21&&y%11?x-X-~-~-d%2|y-Y-~-d%2|k>>9||f(m,x,y,-~k,i>6?i-7:d,r[x]=s[(25464-11928*(d&1)+'6')[i]||i]):0:k||f(m,x,y,1))) ``` [Try it online!](https://tio.run/##7ZbtboIwFIb/exVNFqGFlgzi3FSod7D9IxoGiQFcEIEFzAIZ89YdRjNRICyLYzPSpklP@uacnj79WszeZpEZOq8r4geWvdnMFejhCZ5iF1tIoZ7gzV4hDHGSGeHOMHGcGWsYKSwgqfLI3xiySlnsKJHg@JYdP82hidDYZZi4K4kMk3RFcRyTCVln1epKaUKm@55L6SBN51nMGCeYrF3s0P7YIfdDC4darCuRBqW7Xr9HRHEgPXDQYkTEs30WaY6epo6OhrdD9@BBRAhtVna0AgrwgELBO8iG0AiYgR8FS1tYBi9wl1S4HQ6FReD4kGUR2vee/aw/Ah@dztYN1DogK5ogCCxPSgrP6vggSUFJSa9BwjUQqApAR0d/DIu2sC4HVq1EPt@uUBuAZWwN@Vph7Q@f3J6sy4F1lkBcC6spWHIL61p@g7SFdY550@xVlpvgyeVX@//urV@B9fWWqNWTonlFJayDoiq1/F@uKnuq1i4QV7uGuX1TITHy351SiVF7axvHN/tlnCwVHLeChBadyCcSo15SoqgPZPwoI@6kFiRc0Qn3bVibTw "JavaScript (Node.js) – Try It Online") ## How? ### Updating the matrix We use the following lookup string \$s\$ to identify and write the characters from/into the matrix: ``` i = 0123456 s = ' -|=N+#^<V>' ``` NB: `*` is not included, so we have \$i=-1\$ in that case. Characters with an index \$i\$ greater than \$6\$ are direction changers, which are immutable. For the other characters, we use two translation tables to update them according to the current direction. For vertical moves: ``` ' ' (0) + '|' = '|' (2) '-' (1) + '|' = '+' (5) '|' (2) + '|' = 'N' (4) '=' (3) + '|' = '#' (6) 'N' (4) + '|' = 'N' (4) '+' (5) + '|' = '#' (6) '#' (6) + '|' = '#' (6) ``` And for horizontal moves: ``` ' ' (0) + '-' = '-' (1) '-' (1) + '-' = '=' (3) '|' (2) + '-' = '+' (5) '=' (3) + '-' = '=' (3) 'N' (4) + '-' = '#' (6) '+' (5) + '-' = '#' (6) '#' (6) + '-' = '#' (6) ``` Hence the character translation code: ``` r[x] = s[ // update r[x]: ( // build a lookup string: 25464 - // use 25464 if d is even 11928 * (d & 1) // or 13536 if d is odd + '6' // coerce to a string and append a '6', // which gives '254646' and '135366' respectively )[i] // extract the i-th digit || i // or use i if it's undefined, ] // which leaves the original character unchanged ``` ### Preventing an infinite loop There is no explicit loop detection. Instead, we take advantage of the fixed size of the frame and simply stop the recursion when the number of moves from the source is greater than \$511\$ with: ``` k >> 9 ``` This is enough to visit each cell twice (\$2\times20\times10=400\$). Beyond that, the board is guaranteed not to change anymore. We can get close to this [with a configuration like this one](https://tio.run/##ddFRa4MwEADgd3/FwahJaiJTum5tTfoPtjdpcQpF7UitOrQMZVn/epfSQld1dy933McdIbvN16aOK/l5YEWZpKfTluOcruiaZjQhXOR2vvnEuKKtbqpLE9NGN0dccwRM8VfrIfJ8gajktS2LJG3etjgmZJmZZjNyHdNsR46zbNiKHXUmI1e1bH2tMiFmSm31zYa2lB0zKsV0KdnzPKFV0IS8DrD7NJlOmOPM3JcxTkyHWGiKSCBDpWRI5o/z7LbBIYScDml9AA45cAHfoEdkAXFZ1OU@tfflB748qjqPK3tXygIjRMi1ei90vYAfwzivwYEBOgLbtpHFBsJCIb0RJaAXvron0DM@dEnX@NAnIPy/CUOkF30yFtEtB0l0t8EbIFHnitcnvud3TYdEns6OuSf/fYARktMv). ## Commented ``` f = ( // f is a recursive function taking: m, // m[] = input matrix X, Y, // (X, Y) = current position k, // k = number of moves from the source d // d = current direction in [0..3] ) => // (counter-clockwise with 0 = North) m.map((r, y) => // for each row r[] at position y in m[]: r.map((c, x) => // for each character c at position x in r[]: ~( // s = ' -|=N+#^<V>', // s = lookup string i = s.indexOf(c) // i = position of c in s ) ? // if i is not equal to -1 (i.e. c is not '*'): k && // if this is not the first iteration x % 21 && y % 11 ? // and we're not located over a border: x - X - ~-~-d % 2 | // abort if x - X is not equal to dx y - Y - ~-d % 2 | // or y - Y is not equal to dy k >> 9 || // or k is greater than 511 f( // otherwise, do a recursive call: m, // pass m[] unchanged x, y, // pass the new position -~k, // increment k i > 6 ? i - 7 : d, // update d to i - 7 if i > 6 r[x] = … // update r[x] (see above) ) // end of recursive call : // else: 0 // do nothing : // else (c = '*'): k || // unless this is not the first iteration, f(m, x, y, 1) // start a new path to the North ) // end of inner map() ) // end of outer map() ``` [Answer] # Java 8, ~~275~~ 268 bytes ``` m->{for(int r=200,R,C,k,d,v;r-->0;)if(m[R=r/20+1][C=r%20+1]==42)for(k=d=0;(v=m[R+=(d*2-1)%5%3][C+=d/2-d*2/5*2])!=42&R%11*(C%21)>0&k++<500;d=v==94?0:v==86?1:v==62?2:v==60?3:d)m[R][C]-=v==43?8:v==61&d<2?26:v==45?d<2?2:-16:v==78&d>1?43:v>99?d<2?46:81:v<33?d<2?-92:-13:0;} ``` -7 bytes thanks to *@ceilingcat*. Some inspiration taken from [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/196613/52210) (mainly the strategy of looping a max of 400 instead of keeping track of which paths were visited (at least) twice). Input as a character-matrix. Will modify the input instead of returning a new one to save bytes. [Try it online.](https://tio.run/##7Zlbb6JAGIbv@ytmTTQchAIeVmFmyMarTXa7SZtw40rCCm2pigbRpin@dncY8FQ5mK1t41ZIC8M8883M@34c2nmw5pbwYA@W/aE1nYKflus9XwDgeoHj31p9B1xFRQDmY9cGfaZ/b/ndXrcHRqxGri8uyK9pYAVuH1wBDyCwHAn4@XbsMyQC8JEiSdXraqc6qNrVueYLApY01r1lRt1r5F8qEi/3uh3kl@kZQnWFjdoOkI0kjZkjgvGIsTlFkNlyo1wjMI/sS0Ugly4bnNJjv5A2leuyLHNMp6zILJYqA56HDUnSbDRHqF3XJZUcW01djo5NRVfoUdJrqs2SDkjMnhCh9ZreolVyxYYEa0aFekOnBVWQaflrq2JjWa/X1Dlut2ldvam2SGxYq9Gi0I7gmippi6UW6TOZ/RkSfRKZqJAjIjNzE/iud0e0tNhY48CZBkyJF1I2/rdX4ilEt1IIUrbw80Hcu3WXbkuJpRafvftYiDtR7/D5vvuf7zt43FQx3s07MzqBn/yZiV@IcL7vTsy7o3XHnb37AO/g2btP/J2Jz94dVXFMXurw/QzmtoU/haQ7tnfrN5CRNya8zeR4t2GyZ7f9hZgtATYO0Ik7QMytdMqEzO0vqAzIPOBhb@6@Et7cu1V1nndhQhlhHhRTRpgPRRRhCqAQR0wRxIXFkCnAQsgk44YFkEkVgLmQmWgJw1N6Zhpg9ycFwvuB4B5kHgKlMId0Z/7z7LgXewrE7Qfi3tC7FDGN/YHvUUba7PBLJlUnbGzvr3m3cNjc7Hl/UW/ZmwaZe0mQAhnQKEwVE5K9IOmO6N0hqXL@V@WB0Ovuu90lGbrWQJ2M1xqA601mATlPFhxunqaBMxLHs0CckPpg6DGl7xGigjhYKrIOkkmskmi9wkGb/HA9ZwrQehDidDJ0SZKRySWh1qtLFCGo5zzGFzcBxKHj3QX3hIrbbNaaJA34kIIJQ8o8zya60Yqu31sNgAYjZTEYd0gP33zfemKScWSK82sW7Kjjif1YDnYzmHgSwB8/AjXuajWElIjRBGOVGNKAzZU0a1BCSfSdiWMFTEMqirC4WCz/Ag) **Explanation:** ``` m->{ // Method with char-matrix parameter and no return-type for(int r=200, // Current row/column index of the outer loop R,C, // Current row/column indices of the inner loop k, // Counter of the current path d, // Direction (0=North; 1=South; 2=East; 3=West) v; // Current value --r>0;) // Loop `r` over the rows+columns in the range [200,0): if(m[R=r/20+1][C=r%20+1]==42) // If the current cell contains a '*': for(k=d=0; // Reset `k` to 0, and the direction to North (v=m[R+=(d*2-1)%5%3] // † Update the row `R`, [C+=d/2-d*2/5*2]) // and the column `C` // Set `v` to the value at this new cell `R,C` !=42 // Inner loop as long as this next value is not '*', &R%11*(C%21)>0 // nor are we on a border of the matrix, &k++<500 // nor are we stuck in an infinite loop: ;d= // After every iteration: update direction `d`: v==94? // If the current cell contains '^': 0 // Update the direction to 0 (North) :v==86? // Else-if the current cell contains 'V': 1 // Update the direction to 1 (South) :v==62? // Else-if the current cell contains '>': 2 // Update the direction to 2 (East) :v==60? // Else-if the current cell contains '<': 3 // Update the direction to 3 (West) : // Else (any other character): d) // Keep the direction the same // †† Update the character at the current `R,C` cell // based on the current value and direction: m[R][C]-=v==43?8:v==61&d<2?26:v==45?d<2?2:-16:v==78&d>1?43:v>99?d<2?46:81:v<33?d<2?-92:-13:0;} ``` *†: Go to the next coordinate:* I'm using the directions: North: \$0\$; South: \$1\$; East: \$2\$; West: \$3\$. The coordinate changes we have to do are therefore: ``` direction d | new R,C coordinate ------------+------------------- 0 (North) | R-1,C 1 (South) | R+1,C 2 (East) | R,C+1 3 (West) | R,C-1 ``` The straight-forward implementations would be these: ``` R+=d<1?-1:d<2?1:0 C+=d>2?-1:d>1?1:0 ``` But they have been golfed to this (the `/` are integer-division): ``` R+=(d*2-1)%5%3 // maps to: 0→-1; 1→1; 2→0; 3→0 C+=d/2-d*2/5*2 // maps to: 0→0; 1→0; 2→1; 3→-1 ``` *†: Change the values:* We have to do the following mappings: The characters `*><^V#` will always stay the same in the matrix (and we don't even have to check the `*` anyway, since we already stop the inner loop if we encounter another one). That leaves us with the following mappings of the remaining characters, depending on the direction \$d\$: ``` current char (codepoint) | direction d | next char (codepoint) ---------------------------------------+---------------------- + (43) | any | # (35) <space> (32) | 0 or 1 | | (124) <space> (32) | 2 or 3 | - (45) | (124) | 0 or 1 | N (78) | (124) | 2 or 3 | + (43) - (45) | 0 or 1 | + (43) - (45) | 2 or 3 | = (61) N (78) | 0 or 1 | N (78) - unchanged N (78) | 2 or 3 | # (35) = (61) | 0 or 1 | # (35) = (61) | 2 or 3 | = (61) - unchanged ``` I'm currently using the following, although this can definitely be golfed with some magic number tricks: ``` m[R][C]-= // Subtract from the codepoint of the current value: v==43? // If it contains a '+': 8 // Change it to '#' by subtracting 8 :v==61 // Else if it contains a '=', &d<2? // and the direction is vertical (north/south): 26 // Change it to '#' by subtracting 26 :v==45? // Else-if it contains '-': d<2? // If the direction is vertical (north/south): 2 // Change it to '+' by subtracting 2 : // Else (it's horizontal (east/west) instead): -16 // Change it to '=' by adding 16 :v==78 // Else-if it contains a 'N', &d>1? // and the direction is horizontal (east/west): 43 // Change it to '#' by subtracting 43 :v>99? // Else-if it contains a '|': d<2? // If the direction is horizontal (north/south): 46 // Change it to 'N' by subtracting 46 : // Else (it's vertical (east/west) instead): 81 // Change it to '+' by subtracting 81 :v<33? // Else-if it contains a ' ' (space): d<2? // If the direction is vertical (north/south): -92 // Change it to '|' by adding 92 : // Else (it's horizontal (east/west) instead): -13 // Change it to '-' by adding 13 : // Else (it's any other character): 0; // Keep it the same by subtracting 0 ``` ]
[Question] [ Write a full program or a function taking an unsigned integer number N and doing this cut out work: * Cut out a hollow hexagon 'donut' shape with side B-C equal to 2N times '/' * Translate the piece above by 3 lines. * Repeat the job N times (from the piece obtained) decrementing by 2 '/' side B-C , until smallest hexagon (2 times '/'). This is the smallest hexagon which will be cut out last: ``` side B-C C____D is 2'/' -> / \ B/ \ side C-D \ / is 4'_' \____/ A ``` Test cases: N = 0 may output a blank sheet (nothing), but you don't heave to handle it. N = 1: ``` ____ / \ / \ \ / \____/ / \ \ / \____/ ``` N = 3: ``` ____ _/ \_ _// \\_ // \ / \\ // \____/ \\ // /______\ \\ / \ \ / / \ / \ \____/ / \ / / \ / \ \ \ \ \________/ / / \ \ / / / \ \ / / \ \ \ \________/ / / \ \ / / \ \____________/ / \ / \ / \____________/ ``` N = 8: ``` ____ _/ \_ _// \\_ _// \ / \\_ _/// \____/ \\\_ _//// /______\ \\\\_ _//// \ \______/ / \\\\_ _///// \ \____/ / \\\\\_ ////// /_\ /_\ \\\\\\ ///// \ \__\________/__/ / \\\\\ ///// \ \____________/ / \\\\\ ///// / \ \ / / \ \\\\\ //// \ \ \ \________/ / / / \\\\ //// \ \ \ / / / \\\\ //// / \ \ \____________/ / / \ \\\\ /// \ \ \ \ / / / / \\\ /// \ \ \ \ / / / / \\\ /// / \ \ \ \____________/ / / / \ \\\ // \ \ \ \ \ / / / / / \\ // \ \ \ \ \________________/ / / / / \\ // / \ \ \ \ / / / / \ \\ / \ \ \ \ \ \ / / / / / / \ / \ \ \ \ \ \________________/ / / / / / \ / / \ \ \ \ \ / / / / / \ \ \ \ \ \ \ \ \____________________/ / / / / / / \ \ \ \ \ \ / / / / / / / \ \ \ \ \ \ / / / / / / \ \ \ \ \ \ \ \____________________/ / / / / / / \ \ \ \ \ \ / / / / / / \ \ \ \ \ \________________________/ / / / / / \ \ \ \ \ / / / / / \ \ \ \ \ / / / / / \ \ \ \ \________________________/ / / / / \ \ \ \ / / / / \ \ \ \____________________________/ / / / \ \ \ / / / \ \ \ / / / \ \ \____________________________/ / / \ \ / / \ \________________________________/ / \ / \ / \________________________________/ ``` Rules: - Margins are not specified. - Standard loopholes are forbidden. - Standard input/output methods. - Shortest answer in bytes wins. Sandbox : <https://codegolf.meta.stackexchange.com/a/18143/84844> [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 80 bytes ``` F⮌…·¹N«→↘F²«M⁺³×⁴ι↑P×_⊗ι↙F⊗ι«FκP× ⁴↙¹»→Fι«FκP× ⁴↘¹»F⊖ι«FκP× ⁻׳ιλ↘¹»\P×_⊗ι»»‖BO² ``` [Try it online!](https://tio.run/##nZIxa8MwEIVn@1ccniRQhzQZSrKVLIG6DabdAsVRzomoLBlZcinFv11VJGoCXUxHvXt87/QkfqkN17X0vtEGSIUDmh7JTnHpejFgVaszkgWDneqcfXbtEQ2hlMJ3npV6QLKuxPli6eb3uNWfapIi8z6a03gfqGTJ4FW02JMVA0Epg/Vbd3VnpZNWdEYoS5KheC8YbLU7SjyRYE2uKecJmxiTcm58MTCpHxT@YiFgV4mW7eNg4jFYRH2ckqbbJKD4Lz1ybvFpa@QGW1R2/ualUKHFJCyvFTKQdEZemhWHQzG/7TEf8wobidw@OmvRNPLrJfwRWXfhYTfeP/i7Qf4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⮌…·¹N« ``` Loop from the largest to the smallest hexagon. ``` →↘F²«M⁺³×⁴ι↑ ``` Draw each hexagon twice in the desired location. ``` P×_⊗ι ``` Draw half of the top line of the hexagon. ``` ↙F⊗ι«FκP× ⁴↙¹» ``` Draw the top left diagonal, but for each row erase 4 spaces first if this is the second hexagon. ``` →Fι«FκP× ⁴↘¹» ``` Draw half of the bottom left diagonal, still erasing 4 spaces first if this is the second hexagon. ``` F⊖ι«FκP× ⁻׳ιλ↘¹» ``` Draw almost all of the rest of the bottom left diagonal, erasing until the middle of the hexagon if this is the second hexagon. ``` \P×_⊗ι ``` Finish the bottom left diagonal and draw half of the bottom line of the hexagon. ``` »»‖BO² ``` Mirror everything at the end. Alternative approach, also 80 bytes: ``` F⮌…·¹N«→↘F²«M⁺³×⁴ι↑FκG→⊗ι↓³←⊖⊗ι↙⊖⊗ι↘⊖⊗ι→⊖⊗ι↓³←⊗ι↖⊕⊗ι↗⊕⊗ι P×_⊗ι↙↙⊗ι→↘⊗ι↑P×_⊗ι»»‖M ``` [Try it online!](https://tio.run/##jZI/a8MwEMXn@lMITxKoQ9oOxVmzBOJiTD0XRz07orIkZNmllHx2V/J/CKYZdfd79453YpfcMJWLriuUQTiFFkwN@CiZaGreQprLEvCOoqPUjX1rqjMYTAhBv8FDrFrAUcrLiyX76XlQ33Iu9TOfenhoJ24qfqbonVdQ4xeKOCEURZn29IB/EZQo8VMqOc6m6KCas4BPzD3rDShyM6ITFL4JzEAF0jpgASfyHmZy2YT@BW52Wi@c6aHoMt2QZ3p02ERCFPYJxY2wXBsuLR4iDD/CtR0ZqPkS3rkvJb1mHcmiWSTz4db8zRFWgvFwd611Da5BCoUAZmNujHL/aN91r91jK/4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⮌…·¹N« ``` Loop from the largest to the smallest hexagon. ``` →↘F²«M⁺³×⁴ι↑ ``` Draw each hexagon twice in the desired location. ``` FκG→⊗ι↓³←⊖⊗ι↙⊖⊗ι↘⊖⊗ι→⊖⊗ι↓³←⊗ι↖⊕⊗ι↗⊕⊗ι ``` Before drawing the second hexagon, erase the area between it and the next smaller hexagon. ``` P×_⊗ι↙↙⊗ι→↘⊗ι↑P×_⊗ι»»‖M ``` Draw the left half of each hexagon, and then mirror everything at the end. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~113~~ 112 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` «/*α_×-/═↔⁸3+ *-╶R⇵{;X:«w╷/###/*Kky┤_×+-y#×/×-y_×-/═ŗ∙ #⟳#¶#╋# ⟳_╋↔x“kyv╴e┌/i┴⁰U<alissfr↖;,imFE!↷qB╪²-‟#ŗ}#∙ ╋↔║ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUFCLyV1RkYwQSV1MDNCMV8lRDcldUZGMEQldUZGMEYldTI1NTAldTIxOTQldTIwNzgldUZGMTMldUZGMEIlMjAldUZGMEEldUZGMEQldTI1NzYldUZGMzIldTIxRjUldUZGNUIldUZGMUIldUZGMzgldUZGMUElQUIldUZGNTcldTI1NzcvJTIzJTIzJTIzLyV1RkYwQSV1RkYyQiV1RkY0QiV1RkY1OSV1MjUyNF8lRDcldUZGMEIldUZGMEQldUZGNTklMjMlRDcvJUQ3JXVGRjBEJXVGRjU5XyVENyV1RkYwRCV1RkYwRiV1MjU1MCV1MDE1NyV1MjIxOSUyMCUyMyV1MjdGMyUyMyVCNiUyMyV1MjU0QiUyMyUyMCV1MjdGM18ldTI1NEIldTIxOTQldUZGNTgldTIwMUNrJXVGRjU5diV1MjU3NGUldTI1MEMvJXVGRjQ5JXUyNTM0JXUyMDcwVSV1RkYxQyV1RkY0MWxpcyV1RkY1M2ZyJXUyMTk2JXVGRjFCJTJDJXVGRjQ5bSV1RkYyNkUldUZGMDEldTIxQjdxQiV1MjU2QSVCMiV1RkYwRCV1MjAxRiV1RkYwMyV1MDE1NyV1RkY1RCUyMyV1MjIxOSUyMCV1MjU0QiV1MjE5NCV1MjU1MQ__,i=NQ__,v=8) A part of the answer is literally evaluating the JavaScript `p.p.overlap(p.p,0,p.p,(a,b)=>b==0?a:b)`.. [Answer] # [C (clang)](http://clang.llvm.org/), 374 bytes ``` #define F(X,R)*d=*(d=o+x*(l*3+35-g)+x/2+X+R)-32?*d:R? i,z,x,l,w,r,g,m;f(n){int*d,o[i=z=(x=n*8+1)*(n*5+4)],*c=o;for(;l=i--;)*c++=i%x?32:10;for(;l++<n;)for(g=35;i=g-29;g-=3){for(r=m+=m=w=l*2;r--;F(~-w*x-w,r)g:g)F(w*~x,r)95:95,F(w*x-w,r)95:95;for(;w--;)for(r=4;r--;F(m-~w*~-x,-r)g:47)F(w-m-w*x,r)g:47,F(w-m-~w*x,r)g:92,F(m+~w-w*x,-r)g:92;}for(;i<z;++i)printf(o[i]-35?o+i:" ");} ``` [Try it online!](https://tio.run/##NZDBisIwEIbv@xTispBkMuzaWLSNQ28@gCdh8SCtDYEmXcpCg2Jf3U2se8v/TfLNZGqsu7M3j8d7c2mtvyz27CgPXDQkWEM9BME6oUDlaDiEzwyOcOCosko05aF6s/Iqg@zkKAdppNMt8/xm/a9oZP9t6UoskBdbWHHBvMhhzU9S1NTrth@Y7sgiai5qALIfoVJZufp6lQB2XvN0NqRybclgVmiDpPgt0YEckKOROpHpIWr2bMJRBIyjcFMavmejmEIMRV4WuUxxLj7z3GVM7Wfb@iVxOMV3GCQmzXqTPOiSWc5AzmD6J0UWiYNpfN7BGen70293Vw1g@c8Qd9KyuJITqrzqwZbLxZLr@8OdrWfxR2yb0h8 "C (clang) – Try It Online") -33 more saved by @ceilingcat improvement # [C (clang)](http://clang.llvm.org/), [~~433~~](https://tio.run/##fZBPb6MwEMXv/hSWUBX/GS8pIeoGx8st3HNpq01VRRBSS0BWJBE0afLVs7ZBtJVWC4d5fh5@b5hUpMW62t5uXrbJdbXBC/IMT/AIS8oyxUimUvHMn/gjX1IxCWKWRcsYaThBC@9QQAM1ZJDAFkqZk4qe07d1zVJgGex@a3VSpFUV@8nvKSPvRk15SF9kvqtJqnZSCyEpSzlX@q6NR3gU3Y/dZaHGsuB8Xklqj4k5JvNQJlxN6HmrRt5IJNIQeMsKFvCEtbz1A16wVjbKOLJUISscqlYBa2Rtk84L0rAWRANjqOlsGs2mckHEvzzSCDPy4G@jrbxYmmwsqOOGHbWHlnYXpjF8gAW5frNmAXRNJVwbEIN1/e6FD12GNn@r5yfJuaZ/jge7UWKW@SIm09jWaBJQebn5DGGMPc9b2erEhxVzhbN63WCdY7NRtDIX1v5AuJeuC@e63h@w2SRC2PccxhUrVp3wu09sNRGv5vlvq23wHRvvN@muylx@76wwWnVqaHVU1Jkd3Io@wDYOIUZ7n0HW/hrmhvkSY68/o4ZmQ3GMOO45uJtjmKV/mY88XaXFMdvg@f6Q6d2Pt18I6eqAy7WuCMVnhHIyodINXG8Ox7rCY4kuCN3@Ag "C (clang) – Try It Online") [~~412~~](https://tio.run/##XZBBb4JAEIXv/RXGpsnuzmyqLKSFdcIN7l7UNB4MCNlkgYY0YdXoX7eAtja9zbx5883kZTKzu7q8Xp/zfWHq/SRhG1zjCpdc5CRYTpncwBpWsORSebHIo2X8ZPCIDg9oscMWc0yxxEoXrOYnU3@JDEWOzYehIzFHtXiHORfs0FcB@Hyri6ZlGTXakpFSc5EBkHlxsfKi@WycaguwqDUf6pRm2lC68HUKpPipJBXIVPcAcMIKBalw4F493ZEV3rjeUkW@sLrt8QlzshMOZYczbHkZlTxhf4QwiMIAEyb/a7dHuuHDG9O/8y6Ds8JLh3Lg@W8/wGqIY1Tw7vqVQg9vpsde6OnzeMIsjpoboM@2D69gfXBbqYK4ARNNJ1Ouz9dqZ2rGTwVTQ/cN "C (clang) – Try It Online") 407 bytes ``` #define F(Y,X,W,R)*d=*(d=c-Y+X+W+R)-32?*d:R? i,z,x,l,w,r,d,G,g,m;f(n){int*c,*d,o[i=z=(x=n*8+1)*(n*5+4)];for(c=o;l=i--;)*c++=i%x?32:10;for(;l++<n;)for(G=0;i=G<4;G+=3){g=35-G;c=o+x*l*3+G*x+x/2;for(r=m+=m=w=l*2;r--;F(x-w*x,-w,0,r)g:g)F(w*x,-w,0,r)95:95,F(-w*x,-w,0,r)95:95;for(;w--;)for(r=4;r--;F(~w*x,m,~w,-r)g:47)F(w*x,-m,w,r)g:47,F(~w*x,-m,w,r)g:92,F(w*x,m,~w,-r)g:92;}for(;i<z;)i+=printf(o[i]-35?o+i:" ");} ``` [Try it online!](https://tio.run/##XZDLasNADEX3/YrQUpiRNDTxg9aeCO/sfTZJKFkEOzYD9riYgoeE5NdT20kfdCddXR2Jm6u83tvqen0qDqWxh1kqtrShNa0kFAyi4FxtcYNrXEnlewkU8Sp5MHQkRzX11FFBGVXU6FJYeTL2E3KCgtp3w0cWji284UKCsBBiIHe6bDuRc6trNkppCTkim2eX@F68mE9TXSMurZZjnfFcG86Wgc6QfXmq2A9VpgcAOqjBxwwcuhdvWuy4QW645xo83Q30VDjVgyPV05w6WcWVTMUfIQrjKKRUqP/a7Y9@fPAGDu68y@hs6NKTGnnB6zewGbOYFLq7fqTIo5vpdy/y9Hk6YZZHLQ3yRzckV4ohtZ3yw6RFEz/OHqU@X5u9sUKeSuGP3Rc "C (clang) – Try It Online") -21 thanks to @ceilingcat -5 @ceilingcat + y removed ``` ###\ ###\ <= we draw only on spaces ' ' \### \### first time we draw '#' for collisions /####\ /######\ \######/ \####/ ____ /####\ then we move our drawing pointer /######\ 3 lines below \######/ \____/ and we draw spaces / \ instead of # \ / \____/ ____ _/####\ //######\ and we repeat for bigger donuts /#\######/ moving our drawing pointer /###\____/ /###/ \ \###\ / \###\____/ \####??####/ \________/ ``` ]
[Question] [ `/o\` Jimmy [has](https://codegolf.stackexchange.com/questions/187682/how-many-jimmys-can-fit) [been](https://codegolf.stackexchange.com/questions/187731/jimmy-needs-your-help) [receiving](https://codegolf.stackexchange.com/questions/187759/can-jimmy-hang-on-his-rope) [a](https://codegolf.stackexchange.com/questions/188140/jimmy-needs-a-new-pair-of-shoes) [lot](https://codegolf.stackexchange.com/questions/188391/a-scene-of-jimmy-diversity) of attention on this site recently and it has caused Jimmy to get a little stressed. The bodybuilder Jimmys `/-o-\` started bad mouthing the OG / acrobat `/o\` Jimmys saying they are way cooler because they are bigger. But of course the acrobat Jimmys thinks they are way cooler since after all they were the [original.](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform) This tension between Jimmys has resulted in somewhat of a Jimmy war, the acrobat Jimmys and the bodybuilder Jimmys are no longer at peace. --- ## Objective Given a string of acrobat and bodybuilder Jimmys, determine would would win the battle. * The input string will only contain bodybuilder Jimmys `/-o-\`, acrobat Jimmys `/o\` and spaces * The bodybuilder Jimmys are stronger than acrobat Jimmys, so one bodybuilder Jimmy can take down 2 acrobat Jimmys BUT he will be taken down himself after the second Jimmy `/o\ /-o-\` -> `/-o-\` `/o\ /o\ /-o-\` -> * The acrobat Jimmys are crafty and are good at surrounding the bodybuilder Jimmys, if 2 acrobat Jimmys surround a bodybuilder Jimmy, the bodybuilder Jimmy will be defeated with no damage to the acrobat Jimmys `/o\ /-o-\ /o\` -> `/o\ /o\` * The acrobat Jimmys are also faster than the bodybuilder Jimmys so their actions will occur before the bodybuilder Jimmys `/o\ /-o-\ /o\ /-o-\` -> `/o\ /o\ /-o-\` -> ## Notes * Whitespace between Jimmys will have no affect on the battle, but it can be expected in the input. * Whitespace in the output is acceptable and will be ignored as long as no Jimmys get cut in half * Whitespace will only be spaces, you can assume there will be no tabs or newlines * All Jimmys in the input will be whole, there will be no partial Jimmys `/o` * The battle will continue until only 1 type of Jimmy (or no Jimmys at all) remain * Both input and output should be in the form of a string * Jimmy actions will occur going left -> right across the field, but acrobat Jimmys have priority to bodybuilder Jimmy * Bodybuilder Jimmys will only go down to two Jimmys if it occurs on the same turn (see last example) ## More Examples ``` /o\ /o\ /-o-\ /-o-\ /o\ /o\ // Input string /-o-\ /o\ /o\ // Leftmost bodybuilder took out left two acrobats // Output will be whitespace ----------------------------------- /o\ /o\ /-o-\ /o\ /-o-\ /o\ /o\ // Input string /o\ /o\ /o\ /-o-\ /o\ /o\ // acrobat Jimmys got a surround /o\ /o\ /o\ /o\ /o\ // acrobat Jimmys win ----------------------------------- /o\ /o\ /-o-\ /o\ /-o-\ /-o-\ /o\ /o\ // Input string /o\ /o\ /o\ /-o-\ /-o-\ /o\ /o\ /o\ /-o-\ /o\ /o\ /o\ /o\ /o\ // acrobats win again ----------------------------------- /o\ /o\ /-o-\ /o\ /-o-\ /-o-\ /o\ /-o-\ // Input string /o\ /o\ /o\ /-o-\ /-o-\ /o\ /-o-\ /o\ /-o-\ /o\ /-o-\ /o\ /o\ /-o-\ // Output is empty ----------------------------------- /-o-\ /o\ /o\ /o\ /-o-\ /-o-\ // Input string /o\ /-o-\ /-o-\ /-o-\ /-o-\ // Bodybuilder Jimmys win ----------------------------------- /o\ /-o-\ /-o-\ /o\ /o\ /o\ // Input string /-o-\ /-o-\ /o\ /o\ /o\ // left most bb jimmy took out leftmost acrobat jimmy /-o-\ /o\ // right bb Jimmy took out left two acrobat Jimmys and himself /-o-\ // leftmost jimmy took out a second jimmy but survives because it occurred on a different turn the the first jimmy he took out - bodybuilder Jimmys win ``` Standard rules apply, This is code-golf so may the shortest answer win! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` +1`/-o-./o./o.|(/-o-.)/o.|(/o.(/o.)?)/-o-.(/o.)|/o./o./-o-.|/o.(/-o-.) $1$2$4$5 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4GLS9swQV83X1dPPx@EajTAHE0IM18PhDXtNcGCYHYNRB1YoAasAKyeS8VQxUjFRMX0v54@V4yC/n/9fCAJwkBpOAkR40KTyydanlRVIBYXii50dVw4TAdhAA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: The first stage simply deletes whitespace. (The footer spaces the remaining Jimmies back out out.) The second stage then repeatedly replaces the first available match with the captures until no more replacements can be made. The matches are as follows: * `/-o-./o./o.` Matches a bodybuilder next to two acrobats. There is no capture because this takes out the bodybuilder as well. * `(/-o-.)/o.` Matches a bodybuilder next to an acrobat. There's no second acrobat here, because it would have matched above, so the lone acrobat is taken out, while the bodybuilder survives. * `(/o.(/o.)?)/-o-.(/o.)` Matches a bodybuilder between two acrobats, with up to two acrobats to his left. The bodybuilder is taken out. * `/o./o./-o-.` Matches a bodybuilder with two acrobats to his left (but no acrobats to his right, as that would have already matched). All three are taken out. * `/o.(/-o-.)` Matches a bodybuilder with one acrobat to his left (but no acrobats to his right, as that would have already matched). The acrobat is taken out. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 54 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ðœṣjW}Ẉiȯ.ɗ¦FðⱮ⁽^|DB¬Ðe¤B0¦ẈṀ$ÐṀF€Ṁḟ3Ḃ Ḳ¹ƇµẈ<4ÇÐLịQṢṚƊ ``` A full program accepting a string which prints the result (as a monadic Link the result would be a list of lists of characters). The input must have spaces(s) between Jimmys, and the output has no spaces (both allowed in the question). **[Try it online!](https://tio.run/##y0rNyan8///whqOTH@5cnBVe@3BXR@aJ9Xonpx9a5nZ4w6ON6x417o2rcXE6tObwhNRDS5wMDi0DKnm4s0Hl8AQg6faoaQ2QerhjvvHDHU1cD3dsOrTzWPuhrUA1NiaH2w9P8Hm4uzvw4c5FD3fOOtb1//9//fwYBTDWzddFYSH4@TEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///whqOTH@5cnBVe@3BXR@aJ9Xonpx9a5nZ4w6ON6x417o2rcXE6tObwhNRDS5wMDi0DKnm4s0Hl8AQg6faoaQ2QerhjvvHDHU1cD3dsOrTzWPuhrUA1NiaH2w9P8Hm4uzvw4c5FD3fOOtb1/@HuLYfbgVoi///Xz49RAGPdfF04CRHjQpPLJ1qeVFUgFheKLnR1XDhMB9vABWaBATIDaiKIg8LgwuIfAA "Jelly – Try It Online"). ### How? ``` Ḳ¹ƇµẈ<4ÇÐLịQṢṚƊ - Main Link: list of characters Ḳ - split at spaces ¹Ƈ - keep those which are truthy (just the Jimmys, since empty lists aren't) µ - start a new monadic link ...i.e f(Jimmys) Ẉ<4 - length of each less than four? ...i.e: strongman->0 acrobat->1 ÐL - loop until a fixed point is reached using: Ç - last Link (1, see below) as a monad ...i.e. f(these "Binnys") Ɗ - last three links as a monad ...i.e. g(Jimmys) Q - de-duplicate Ṣ - sort (["/-o-\", "/o\"], or if only one then just that one in a list) Ṛ - reverse ị - index into (1-indexed and modular) ...i.e. get back any remaining Jimmys - implicit, smashing print ðœṣjW}Ẉiȯ.ɗ¦FðⱮ⁽^|DB¬Ðe¤B0¦ẈṀ$ÐṀF€Ṁḟ3Ḃ - Link 1: list of 1s and 0s, let's say "Binnys" ¤ - nilad followed by link(s) as a monad: ⁽^| - literal = 24625 D - to decimal = [2,4,6,2,5] B - to binary = [[1,0],[1,0,0],[1,1,0],[1,0],[1,0,1]] Ðe - apply to even indices: ¬ - NOT = [[1,0],[0,1,1],[1,1,0],[0,1],[1,0,1]] ð ðⱮ - map with the dyad: ...i.e. [f(Binnys,X) for X in that] œṣ - split Binnys at sublists equal to X } - use the right argument (X) with: W - wrap in a list j - join (the split Binnys) with (wrapped Xs) ¦ - sparse application... ɗ - ...to indices: last three links as a dyad: i - first index of (X) or 0 if not found . - literal 0.5 ȯ - OR (since an index of a half doesn't exist) Ẉ - ...action: length of each - ...i.e. replace the first, wrapped X with its length F - flatten ¦ - sparse application... 0 - ...to indices: [0] (the [1,0,1] result) B - ...action: to binary (3 -> [1,1]) ÐṀ - keep a list of those which are maximal under: $ - last two links as a monad: Ẉ - length of each Ṁ - maximum - ...i.e. keep only the one with [1,1] in if its there F€ - flatten each Ṁ - maximum ḟ3 - filter out threes (strongmen annihilating) Ḃ - modulo 2 (2->0 to cater for remaining strongmen) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 68 bytes ``` ⁵R+⁴W;“|ẹẹrḟ“€Ƙ.q“¦ḍhƁ’b⁴¤ḃ2s2Z€ị“/o\“/-o-\”ḣẎẎF€⁸œṣjƭƒ@ƬṪ ḟ⁶;ç1ɗ/ç2 ``` [Try it online!](https://tio.run/##y0rNyan8//9R49Yg7UeNW8KtHzXMqXm4aycQFT3cMR/Ie9S05tgMvUIg69Cyhzt6M441PmqYmQRUe2jJwx3NRsVGUUAVD3d3AxXo58eASN18XSA99@GOxQ939QGRG1DBo8YdRyc/3Lk469jaY5Mcjq15uHMVF8j8xm3Wh5cbnpyuf3i50X@Q5Ye2lR3aBtRtfbid6@HuLYfbgZqzHjXuO7Tt0Lb//4E2KIAxyA4YCRHjQpPLJ1qeVFUgFheKLnR1XDhMB2EA "Jelly – Try It Online") A full program that takes a string as input and outputs the final state of the Jimmys as a string. Works well for all the test cases. It works through the input one character at a time at each stage replacing 4 Jimmy sets with the appropriate output until no change. At the end, it then also looks for trailing 3 and 2 Jimmy sets that need to be resolved. Jelly doesn’t have regex, so all the possible Jimmy sets that need replacement are built. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 111 bytes ``` s/\s//g;$A=qr'/o\\';$B=qr'/-o-\\';1while s,$A\K$B$A,/o\\,g;s,($A?)$A$B|$B$A($A?),'/-o-\\'x!$+,e;/$A/*/$B/&&redo ``` [Try it online!](https://tio.run/##lUy9CsIwEN7zFBWO1p@L1w6dgkiyim@Q0VALxcRE0MFnN5pIBwuCDt/x/Z4zfmhjDKQDUSdAbs6@Iqt1JUBlzi1Pqrke@8EUAUHqHSiQmFrYiYBzkNsFSFD35GeF4@42gxUaQSBpSaCoLL052Bhf4yIj1cb79tgksz/n/7YSYx@raY99@Z7xsO7S21OIfN@u66aO3A1P "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 249 bytes ``` n=>{n=n.Replace(" ","");for(var s=@"o\/-o-\/o";n.Contains("/o")&n.Contains("-");n=new System.Text.RegularExpressions.Regex(@"/o.{4,7}-\\|/-.{4,7}o\\").Replace(n,m=>m.Value.Length>8?"":"/-o-\\",1))for(;n.Contains(s);)n=n.Replace(s,@"o\/o");return n;} ``` [Try it online!](https://tio.run/##nVLfS8MwEH62f0W4B2lY2joQlMXWgSgIA0FFX/JSajYL22Uk6ZzU/u01abdRpk@D/Li73Pfdd0cKExWmbB8qLG6M1SUuWH9l87TFNKsxxfhZrpd5IUMgwAAonysdbnJNTDoFJZJIRSJRwDG@U2jzEk0Izqfnw0DkcI5LfpGXb2PlKn6VW@uYF9Uy1/fbtZbGlAqND8ltOHUMcX3JrppIiJ8k6m0lBNCDHGSrNFvFb/mykvFM4sJ@Zte3ABPoJAlgY0q91qEyQzkd9mRY14OTy7W0lUaCvGl5sFHlB7HS2LCfB8kpqYOzd11aOSvRDeMR15WdCKwvGoFPld154wYYyRkBAUBGZB464KjzKB/indcEQVfBNytIt73w/dnHPOz/LHVC5un53hoihkzHiGPmv7V39dvEz77/QsHuI/l1sIP96y8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # JavaScript, ~~223~~ 202 bytes ## Code ### Non-recursive 206 bytes ``` x=>{x=x[u="replace"](/ /g,"");while(x[t='match'](/o...o/)){d=/(-..o|o..-)/,x=x[t](s=/o.{7}o/)?x[u](s,"o\\/o"):(a=x[t](c=/\/.{9}\\/))&&(b=x[t](d))&&(a.index<b.index)||(a&&!b)?x[u](c,""):x[u](d,"-")}return x} ``` [Try it online!](https://tio.run/##fY7BcoMgFEXX5SvsWxiYKHTXaQzth6gLVFQ6FhzF1hn12y2JnUnSdrJ5XM69XN67@BR93qnWhtoUci35OvLXaeRjPHDoZNuIXEKKmceqAIBEX7VqJB5jy3cfwub1znmGUmoYIVPBGQ6dnh0JCQtONTbFPXeR6XlxmTfX60AAJkmYAXLAYsvknCWMTi@L44T4Ps42XpwvgipdyPGYbSeZZyx8/zH76ctPqx3OsgggBLJ00g6d9sZlVbodbM9jYO5LbxuhCX/ra@QGBAju@ZfQf8btqz@xiwbPQyhFCJWmw4o/Req47UsbqStbR2q/JxN6yI3uTSNpYyq8BWKVklteXjkBJBoIWtZv) ### Recursive 202 bytes ``` f=x=>{x=x[u="replace"](/ /g,"");d=/(-..o|o..-)/;return x[t='match'](/o...o/)?f(x[t](s=/o.{7}o/)?x[u](s,"o\\/o"):(a=x[t](c=/\/.{9}\\/))&&(b=x[t](d))&&(a.index<b.index)||(a&&!b)?x[u](c,""):x[u](d,"-")):x} ``` [Try it online!](https://tio.run/##fY5NboMwEIXX9SnoLIitYLu7qiFuDwIsHGOIK2ojfiok4OzUgUpJ2qqb8ZvvvRnPu/yUrWpM3VHrcr0shRjE6ziIIekFNLqupNKQYR7wMgIgcS44poy5yTFGCY8b3fWNDYakE7sP2anzzoe9xxwnbwX2PMOt8GR8ni/I7/UgApem3AE5YCnWjBI85Wx8mT0nJAzxaeP52khmbK6H42l7yTRhGYaPp@996nLaYZV5BBSIb@bF2LrvWpEA958FW6GO/tS3yBeIEPznX0N/GfdTv2JXDUGAUIYQKlyDjXiKzXG7l1Xalt05Nvs9GdGDcrZ1lWaVK/EWSExG7nlx40SQWiBoXr4A "JavaScript (Node.js) – Try It Online") ### Explanation ``` x=x[u="replace"](/ /g,""); ``` Remove all spaces ``` while(x[t='match'](/o...o/)) return x[t='match'](/o...o/)?f(...) ``` While there is an acrobat next to a bodybuilder (o\/-o or o-\/o) Do one of the following ``` x=x[t](s=/o.{7}o/)?x[u](s,"o\\/o") ``` If there is a bodybuilder surrounded by acrobats remove the bodybuilder ``` :(a=x[t](c=/\/.{9}\\/))&&(b=x[t](d))&&(a.index<b.index)||(a&&!b)?x[u](c,"") ``` If the first acrobat next to a bodybuilder is also next to an acrobat remove both acrobats and the bodybuilder ``` :x[u](d,"-") ``` Otherwise remove only the acrobat. [Answer] # [Python 2](https://docs.python.org/2/), ~~216~~ 214 bytes ``` A='/o\\';B='/-o-\\';a=input().replace(' ','') while(A in a)*(B in a):j,k=min(enumerate([A+B+A,A+A+B,B+A+A,B+A,A+B]),key=lambda(i,k):([1,i>0][k in a],(a+'.'+k).find(k),i));a=a.replace(k,[A+A,'','',B,B][j],1) print a ``` [Try it online!](https://tio.run/##hVDLboMwEDyHr/Ch0tplQ5scqagEUnrtpTegkgNbxTEYZIEavp7aQUqloKoH27Ov2fH003DqzH6uupoSCwBzmsBTVxTwkjmw7bYeykSZfhy4iCz1jayIAwMEEMH3STXEU6YMk@KRZwuIz6iTVhlOZmzJyoF4noZZmGIauhcdcniJs1KgpilpZHusJVeoRczzHarX5zLXV74SuQwhglCL6EuZmmuBSggnS94Eacw9J3hZ6DaU@bnEnQh6q8zA5Oy@tohlH3akONgMdnL3ZqnDJzhMF6qYd@I3/1AYV6FLRf3ADu9vB2s76@eOlqSevVXserxT98jbGPzd8k/jqrxecZdez99o15TL/A8 "Python 2 – Try It Online") ]
[Question] [ You are given four numbers. The first three are \$a\$, \$b\$, and \$c\$ respectively, for the sequence: $$T\_n=an^2+bn+c$$ You may take input of these four numbers in any way. The output should be one of two distinct outputs mentioned in your answer, one means that the fourth number is a term in the sequence (the above equation has at least one solution for \$n\$ which is an integer when \$a\$, \$b\$, \$c\$ and \$T\_n\$ are substituted for the given values), the other means the opposite. This is code golf, so the shortest answer in bytes wins. Your program should work for any input of \$a, b, c, T\_n\$ where the numbers are negative or positive (or 0), decimal or integer. To avoid problems but keep some complexity, non-integers will always just end in \$.5\$. Standard loop-holes disallowed. ## Test cases ``` a |b |c |T_n |Y/N ------------------------ 1 |1 |1 |1 |Y #n=0 2 |3 |5 |2 |N 0.5 |1 |-2 |-0.5|Y #n=1 0.5 |1 |-2 |15.5|Y #n=5 0.5 |1 |-2 |3 |N -3.5|2 |-6 |-934|Y #n=-16 0 |1 |4 |7 |Y #n=3 0 |3 |-1 |7 |N 0 |0 |0 |1 |N 0 |0 |6 |6 |Y #n=<anything> 4 |8 |5 |2 |N ``` [Answer] # JavaScript (ES7), 70 bytes Returns a Boolean value. ``` (a,b,c,t)=>(t-=c,(a*=2)?(x=(b*b+2*a*t)**.5-b)%a&&(x+b+b)%a:b?t%b:t)==0 ``` [Try it online!](https://tio.run/##jZDLCsIwEEX3fkU2liRN@n5oIfYP3LtMaitKacUG6d/XSaFC1YCBDDfkzOPOTT7lUD2ud827/lxPjZiwZIpVTBNxwJqLikkqIiZLPAqsqHIjKqkmlHopV2QrHQePrnKNLFSpt6qATBFMVd8NfVt7bX/BDQ4ZggPRiBAkIcj30WmzxqIZixlKQURv7PiBBZ75h1IcEji8fldbYWH6FxZbm/LYcKZhBncfJ5Zqi9MERG51GixOOaC53emMQQxWe7NiMBrKrE2TGdt9rXd6AQ "JavaScript (Node.js) – Try It Online") ## How? For the sake of clarity, we define \$d = T\_n-c\$. (The same variable \$t\$ is re-used to store this result in the JS code.) ### Case \$a\neq0\$ The equation really is quadratic: $$T\_n=an^2+bn+c\\ an^2+bn-d=0$$ With \$a'=2a\$, the discriminant is: $$\Delta=b^2+2a'd$$ and the roots are: $$n\_0=\frac{-b-\sqrt{\Delta}}{a'}\\ n\_1=\frac{-b+\sqrt{\Delta}}{a'}$$ The equation admits an integer root if \$\sqrt{\Delta}\$ is an integer and either: $$\begin{align}&-b-\sqrt{\Delta}\equiv 0\pmod{a'}\\ \text{ or }&-b+\sqrt{\Delta}\equiv 0\pmod{a'}\end{align}$$ ### Case \$a=0, b\neq0\$ The equation is linear: $$T\_n=bn+c\\ bn=d\\ n=\frac{d}{b}$$ It admits an integer root if \$d\equiv0\pmod b\$. ### Case \$a=0, b=0\$ The equation is not depending on \$n\$ anymore: $$T\_n=c\\ d=0$$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _/Ær1Ẹ?%1Ạ ``` A monadic Link which accepts a list of lists\* `[[c, b, a], [T_n]]` and yields `0` if `T_n` is a valid solution or `1` if not. \* admittedly taking a little liberty with "You may take input of these four numbers in any way". **[Try it online!](https://tio.run/##y0rNyan8/z9e/3BbkeHDXTvsVYHkgv///0dHm@koGABRrI5CtFlsLAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8/z9e/3BbkeHDXTvsVYHkgv@H2x81rfn/Pzo6WsFQB4QUDBUUYnUUohUgrFguHaCUqY6CMVDKCC5lBJPSNYLoMtAzhUjpgljYpQxNcUopGMMNNNNRAMrqGkOkdC2NTeDOMIHqgjvDHK7LEOJCLFIKBjoghCSF8JcZupQZWCoWAA "Jelly – Try It Online"). ### How? ``` _/Ær1Ẹ?%1Ạ - Link: list of lists of integers, [[c, b, a], [T_n]] / - reduce by: _ - subtraction [c-T_n, b, a] ? - if... Ẹ - ...condition: any? Ær - ...then: roots of polynomial i.e. roots of a²x+bx+(c-T_n)=0 1 - ...else: literal 1 %1 - modulo 1 (vectorises) i.e. for each: keep any fractional part - note: (a+bi)%1 yields nan which is truthy Ạ - all? i.e. all had fractional parts? - note: all([]) yields 1 ``` --- If we could yield non-distinct results then `_/Ær1Ẹ?ḞƑƇ` would also work for 10 (it yields `1` when all values are solutions, otherwise a list of the distinct solutions and hence always an empty list when no solutions - this would also meet the standard Truthy vs Falsey definition) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Æ©²Āi²4P³n+tÐdi(‚³-IJ·Ä%P}뮳Āi³%]_ ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/182609/52210), so make sure to upvote him! Takes the input in the format \$[t,c], a, b\$. [Try it online](https://tio.run/##AVAAr/9vc2FiaWX//8OGwqnCssSAacKyNFDCs24rdMOQZGko4oCawrMtw4TCssK3w4QlUH3Dq8KuwrPEgGnCsyVdX///Wy05MzQsLTZdCi0zLjUKMg) **Explanation:** ``` Æ # Reduce the (implicit) input-list by subtraction (`t-c`) © # Store this value in the register (without popping) ²Āi # If the second input `a` is not 0: ²4P # Calculate `(t-c)*a*4` ³n+ # Add the third input `b` squared to it: `(t-c)*a*4+b*b` t # Take the square-root of that # (NOTE: 05AB1E and JS behave differently for square-roots of # negative integers; JS produces NaN, whereas 05AB1E leaves the # integer unchanged, which is why we have the `di...}` here) Ð # Triplicate this square di # If the square is non-negative (>= 0): (‚ # Pair it with its negative ³- # Subtract the third input `b` from each Ä # Take the absolute value of both ²·Ä% # Modulo the absolute value of `a` doubled # (NOTE: 05AB1E and JS behave differently for negative modulos, # which is why we have the two `Ä` here) P # Then multiply both by taking the product } # And close the inner if-statement ë # Else (`a` is 0): ® # Push the `t-c` from the register ³Āi # If the third input `b` is not 0: ³% # Take modulo `b` ] # Close both if-else statements _ # And check if the result is 0 # (which is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` Solve[n^2#+n#2+#3==#4,n,Integers]!={}& ``` [Try it online!](https://tio.run/##XYpBC8IgGIb/iiF02WelbkYHwWu3ouNYICGb0AyWdRF/u@lih/rey/M@7zdqP5hRe3vTqZfp8ri/TeuuDFcOswpzKXENDo7Om95Mz24lQ1yn88sa354m6/xW9UophEKgMCcCCgw4NMAK7jZNtoQByfQjaPMneGmE55q/BZADr@c9rzXsv8iB0IVL6IICRIwdKpfSBw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` _3¦UÆr=Ḟ$;3ị=ɗẸ ``` [Try it online!](https://tio.run/##y0rNyan8/z/e@NCy0MNtRbYPd8xTsTZ@uLvb9uT0h7t2/D866eHOGTqPGuYo6NopPGqYq3N4uT5Q9lHjvki/Y11ch9sfNa2J/P8/OtpQBwhjQSg62kjHWMcUyjbQMwXK6BrF6ugCmagihqboIsYgrq4xkG@ko2sG1GNpbAJWAZQHMswhbGMdXUM4BwhhVgHZQD1msQA "Jelly – Try It Online") Built-in helps here but doesn’t handle a=b=0 so this is handled specially. ]
[Question] [ ## Introduction For the purposes of this challenge, we will define the *neighbours* of an element \$E\$ in a square matrix \$A\$ (such that \$E=A\_{i,j}\$) as all the entries of \$A\$ that are immediately adjacent diagonally, horizontally or vertically to \$E\$ (i.e. they *"surround"* \$E\$, without wrapping around). For pedants, a formal definition of the neighbours of \$A\_{i,\:j}\$ for an \$n\times n\$ matix \$A\$ is (0-indexed): $$N\_{i,\:j}=\{A\_{a,\:b}\mid(a,b)\in E\_{i,\:j}\:\cap\:([0,\:n)\:\cap\:\Bbb{Z})^2\}$$ where $$E\_{i,\:j}=\{i-1,\:i,\:i+1\}\times \{j-1,\:j,\:j+1\} \text{ \\ } \{i,\:j\}$$ Let's say that the element at index \$i,\:j\$ lives in hostility if it is coprime to *all* its neighbours (that is, \$\gcd(A\_{i,\:j},\:n)=1\:\forall\:n\in N\_{i,\:j}\$). Sadly, this poor entry can't borrow even a cup of sugar from its rude nearby residents... ## Task Enough stories: Given a square matrix \$M\$ of positive integers, output one of the following: * A flat list of elements (deduplicated or not) indicating all entries that occupy some indices \$i,j\$ in \$M\$ such that the neighbours \$N\_{i,\:j}\$ are hostile. * A boolean matrix with \$1\$s at positions where the neighbours are hostile and \$0\$ otherwise (you can choose any other consistent values in place of \$0\$ and \$1\$). * The list of pairs of indices \$i,\:j\$ that represent hostile neighbourhoods. [Reference Implementation in Physica](https://tio.run/##fZLfbtMwGMWvm6c4RDC1moqSdB0oplMr0FAnQBNI3GS5aINhblNnyh8BSi3tclzzCogH64uUL7bXpYwhJXIcn@@czz/76vJ7IZLZdntayQTvuPhyOc@qvIgmIVJRlAwihJA0LvQYIzQLodOROzVGqJXTOc1y5NlXbG5uUIu@T8X0HPqKxJ3pZzzqetj8@KU1L/CGy/Gk9lQvRJLJUsiKk6zxSLK0Wkljs2hsFvRYm7aP1WkrjKHNsF6jSwHMrvYwGqFLfSz2c9rdH1L7k5qKVG2KFG3mPS@rXOJO5jiOhvT65atoZqHM76DQSP3RIsHwDYul3kIUYHP9G2@FjOoZlag4tjxmeEIa6m9@@@HpLRqT5a4HmlP4albm4hstTOVVVT52pvKTSLhl30YfeTqQoESmJu77TeRfaB@SdXjKV1yWZGz@75FxOvvn3royRs3Qoh@TPMmucrHipJ2kadTtn2AZaog2h2EZN3v3exiPW7yb2vOcsEYtQwZ3c/3TZdgVu/0Tmn4o86hV@jRdVEUZDYYxCdZuU62biA14OzP3yWJsLsHexVGOY@LdC3khz7OiEPOUI6tKwl@Ebny7/JHnhcgk/JCC6n8wgz0d1sZvc9U9m0Db1N0pw1mvLcXBAfzmfnva8OyBU0Qffmwyp/@V3EseNMk2LN5u6/r4iMH36D1S1FLwjCEIGAZBMxsOGIbPaXas1B8 "Physica – Try It Online") – supports [Python](https://tio.run/##fZLfbtMwFMavm6f4iGBKtRbVrbZBQqdWoKFOgCaQuPF80QbD3KZOlT8ClEba5bjmFRAP1hcpJ47XpYwhRXKc853vO/7Fq6vvqQqn2@1ZrkO8k@rL1SzOk5SPfUQqzQIoH0rTOjergF8XfKeld2oMUZRO6yxOkMRfsbm5QaG6jJrpOWQliVuTz3jk9bD58ctoXuCN1KNx0SvbPsJYZ0rnkmSVRxhH@VLXNvPKZk6PtWn6WJ2xwgjGDOs1PAoIbLWN4RAezTHfz2lOf0jjjwtqKou6qaTDvJdZnmjcyRzHMZBev3zFpxbK7A4KrTQfFQkGq1kszBF4H5vr33irNC@m1FIKYXlM8YQ0NN/s9qVnjlibLHYz0J7Cl9MsUd@oMNGrPHvsTPQnFUrLvome90wgQeF1j@iyKvIvtA/JWjKSS6kzMq6/75FxWvv/vXFlanWABn1B8jBeJWopSTuOIu51T7HwDUSbE2AhqrOzNkajBu@q9yIhrLxhGMDdXP90A@ya3e4pbT9kCW@0Po3meZrxwZEgwdqtus0QogZvd/V9shirS7B3cUrHWZl491Jf6os4TdUskojzjPCnvituyx9lkqpYg/kUVPyDGezfCZr4bW55z6ZvbApvEuC83ZTi4ACsut89Y3j@wF9EF0zUmZP/Su4lD6pkGya2W84Hzzo4OemAMdEBZ/R2xDoY9Kvd8THVqM6eC/EH) syntax as well for I/O. You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is code-golf, so the shortest code in bytes (in every language) wins! Moreover, you can take the matrix size as input too and additionally can take the matrix as a flat list since it will always be square. ## Example Consider the following matrix: $$\left(\begin{matrix} 64 & 10 & 14 \\ 27 & 22 & 32 \\ 53 & 58 & 36 \\ \end{matrix}\right)$$ The corresponding neighbours of each element are: ``` i j – E -> Neighbours | All coprime to E? | 0 0 – 64 -> {10; 27; 22} | False 0 1 – 10 -> {64; 14; 27; 22; 32} | False 0 2 – 14 -> {10; 22; 32} | False 1 0 – 27 -> {64; 10; 22; 53; 58} | True 1 1 – 22 -> {64; 10; 14; 27; 32; 53; 58; 36} | False 1 2 – 32 -> {10; 14; 22; 58; 36} | False 2 0 – 53 -> {27; 22; 58} | True 2 1 – 58 -> {27; 22; 32; 53; 36} | False 2 2 – 36 -> {22; 32; 58} | False ``` And thus the output must be one of the following: * `{27; 53}` * `{{0; 0; 0}; {1; 0; 0}; {1; 0; 0}}` * `{(1; 0); (2; 0)}` ## Test cases ``` Input –> Version 1 | Version 2 | Version 3 [[36, 94], [24, 69]] -> [] [[0, 0], [0, 0]] [] [[38, 77, 11], [17, 51, 32], [66, 78, 19]] –> [38, 19] [[1, 0, 0], [0, 0, 0], [0, 0, 1]] [(0, 0), (2, 2)] [[64, 10, 14], [27, 22, 32], [53, 58, 36]] -> [27, 53] [[0, 0, 0], [1, 0, 0], [1, 0, 0]] [(1, 0), (2, 0)] [[9, 9, 9], [9, 3, 9], [9, 9, 9]] -> [] [[0, 0, 0], [0, 0, 0], [0, 0, 0]] [] [[1, 1, 1], [1, 1, 1], [1, 1, 1]] -> [1, 1, 1, 1, 1, 1, 1, 1, 1] or [1] [[1, 1, 1], [1, 1, 1], [1, 1, 1]] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] [[35, 85, 30, 71], [10, 54, 55, 73], [80, 78, 47, 2], [33, 68, 62, 29]] -> [71, 73, 47, 29] [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]] [(0, 3), (1, 3), (2, 2), (3, 3)] ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 17 bytes ``` 1=⊢∨(×/∘,↓)⌺3 3÷⊢ ``` [Try it online!](https://tio.run/##VY5NSgNBEIX3nuLtpguUdHVN/0TIYQZkRByIhGyCuJMhUQMRF2YbV15AhGxzk7rI2KODxlVVvVdfvapumrOLRdVML7uu1nbDE3140@W7ObyOdLk91faF9GkvkMNndrpunpdudf2hq90st7Wu9@fF9LrQx/uirq6aIgvZnt2dGG2fjSTECGYyHOEZ4siEgJjAY6J5v8KwsGTsX2H6gUMJzlNJxkU49w17gU@QMMADxcdlSPZIHmIR@3ALX8J7RCGTbJ9f5pNkRBASgoMbH1/ML/xv@PfFrHwB "APL (Dyalog) – Try It Online") (credits to ngn for translating the test cases to APL) ### Brief explanation `(×/∘,↓)⌺3 3` gets the product of each element with its neighbours. Then I divide by the argument `÷⊢`, so that each entry in the matrix has been mapped to the product of its neighbors. Finally I take the gcd of the argument with this matrix `⊢∨`, and check for equality with 1, `1=` Note, as with [ngn's answer](https://codegolf.stackexchange.com/a/172275/71256), this fails for some inputs due to a bug in the interpreter. [Answer] # JavaScript (ES6), 121 bytes Returns a matrix of Boolean values, where *false* means hostile. ``` m=>m.map((r,y)=>r.map((v,x)=>[...'12221000'].some((k,j,a)=>(g=(a,b)=>b?g(b,a%b):a>1)(v,(m[y+~-k]||0)[x+~-a[j+2&7]]||1)))) ``` [Try it online!](https://tio.run/##nZFNbsIwEIX3PYU3LbYYQmwTByqFHsTywmkBFQhBUCGQUK@ePidUBYJU2siR34x/vueZud/57evmff3RW5Vvk2qaVUU2LqLCrznf0EFk400T7GiPwEZR1JFKKRnHccdF27KYcL6gOXms8lnGPeVQ@cuM5@Qfc/Hsx1LgNC/sofvZW7jjMRZ2D@ntvKueUoeMFPiq13K1LZeTaFnO@JRbqw2x0cARs2pAzIycE4L94@v3mbUxsThcVc/uocUaEktTYlKGTRIqkcS0CpGBjxTr8g4HNQsnz3EXUt6AGzxPhrXmsYAr9Q1PNKwArs2d8DOibMs2fIQiY4RNmPWPrLP3l/wafkO24bAVxsnhtfwj/JfL2j1PiA3xa5hLm71QCZqRIJvqkBnGTe8HoSkhoVEhg4RBh1RTn/OXn6C3InlZjdpT9QU "JavaScript (Node.js) – Try It Online") ### How? The method used to isolate the 8 neighbors of each cell is similar to [the one I described here](https://codegolf.stackexchange.com/a/168817/58563). ### Commented ``` m => // m[] = input matrix m.map((r, y) => // for each row r[] at position y in m[]: r.map((v, x) => // for each value v at position x in r[]: [...'12221000'] // we consider all 8 neighbors .some((k, j, a) => // for each k at position j in this array a[]: ( g = (a, b) => // g is a function which takes 2 integers a and b b ? // and recursively determines whether they are g(b, a % b) // coprime to each other : // (returns false if they are, true if they're not) a > 1 // )( // initial call to g() with: v, // the value of the current cell (m[y + ~-k] || 0) // and the value of the current neighbor [x + ~-a[j + 2 & 7]] // || 1 // or 1 if this neighbor is undefined )))) // (to make sure it's coprime with v) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 22 bytes ``` tTT1&Ya3thYC5&Y)Zd1=A) ``` Input is a matrix. Output is all numbers with hostile neighbours. [Try it online!](https://tio.run/##y00syfn/vyQkxFAtMtG4JCPS2VQtUjMqxdDWUfP//2hjCx0Fc3MdBUNDawVDIG1qqKNgbGStYGYGFAfKGVrGAgA) Or [verify all test cases](https://tio.run/##XU4xCsMwDNzzCk0JAQciK5ZjRIfSPiFD0xBooEOHdsv/3TOhS0GyJN/pTp9tf@dH3qeJ63mT/TVfQj239yefzm1uuq65Xae8iDpKg5EfHGlaqVpkdBSjI2YjRg3sSLyRghmBcVqrRUHnHllWQfL@IAXBAkiiICVII6y88mtKAINoCaP/BpgERyNSYBALghpgGPAXxWjsj0uGYmwk0FaMiht8Wr8). ### Explanation with worked example Consider input `[38, 77, 11; 17, 51, 32; 66, 78, 19]` as an example. Stack contents are shown bottom to top. ``` t % Implicit input. Duplicate % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [38, 77, 11; 17, 51, 32; 66, 78, 19] TT1&Ya % Pad in the two dimensions with value 1 and width 1 % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [1, 1, 1, 1, 1; 1, 38, 77, 11, 1; 1, 17, 51, 32, 1; 1, 66, 78, 19, 1 1, 1, 1, 1, 1] 3thYC % Convert each sliding 3×3 block into a column (in column-major order) % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [ 1, 1, 1, 1, 38, 17, 1, 77, 51; 1, 1, 1, 38, 17, 66, 77, 51, 78; 1, 1, 1, 17, 66, 1, 51, 78, 1; 1, 38, 17, 1, 77, 51, 1, 11, 32; 38, 17, 66, 77, 51, 78, 11, 32, 19; 17, 66, 1, 51, 78, 1, 32, 19, 1; 1, 77, 51, 1, 11, 32, 1, 1, 1; 77, 51, 78, 11, 32, 19, 1, 1, 1; 51, 78, 1, 32, 19, 1, 1, 1, 1] 5&Y) % Push 5th row (centers of the 3×3 blocks) and then the rest of the matrix % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [38, 17, 66, 77, 51, 78, 11, 32, 19] [ 1, 1, 1, 1, 38, 17, 1, 77, 51; 1, 1, 1, 38, 17, 66, 77, 51, 78; 1, 1, 1, 17, 66, 1, 51, 78, 1; 1, 38, 17, 1, 77, 51, 1, 11, 32; 17, 66, 1, 51, 78, 1, 32, 19, 1; 1, 77, 51, 1, 11, 32, 1, 1, 1; 77, 51, 78, 11, 32, 19, 1, 1, 1; 51, 78, 1, 32, 19, 1, 1, 1, 1] Zd % Greatest common divisor, element-wise with broadcast % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [1, 1, 1, 1, 1, 1, 1, 1, 1; 1, 1, 1, 1, 17, 6, 11, 1, 1; 1, 1, 1, 1, 3, 1, 1, 2, 1; 1, 1, 1, 1, 1, 3, 1, 1, 1; 1, 1, 1, 1, 3, 1, 1, 1, 1; 1, 1, 3, 1, 1, 2, 1, 1, 1; 1, 17, 6, 11, 1, 1, 1, 1, 1; 1, 1, 1, 1, 1, 1, 1, 1, 1] 1= % Compare with 1, element-wise. Gives true (1) or false (0) % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [1, 1, 1, 1, 1, 1, 1, 1, 1; 1, 1, 1, 1, 0, 0, 0, 1, 1; 1, 1, 1, 1, 0, 1, 1, 0, 1; 1, 1, 1, 1, 1, 0, 1, 1, 1; 1, 1, 1, 1, 0, 1, 1, 1, 1; 1, 1, 0, 1, 1, 0, 1, 1, 1; 1, 0, 0, 0, 1, 1, 1, 1, 1; 1, 1, 1, 1, 1, 1, 1, 1, 1] A % All: true (1) for columns that do not contain 0 % STACK: [38, 77, 11; 17, 51, 32; 66, 78, 19] [1, 0, 0, 0, 0, 0, 0, 0, 1] ) % Index (the matrix is read in column-major order). Implicit display % [38, 19] ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~23~~ 22 bytes -1 byte thanks to @H.PWiz ``` {∧/1=1↓∨∘⊃⍨1⌈4⌽,⍵}⌺3 3 ``` [Try it online!](https://tio.run/##VY7NSsNQEIX3fYqzy71gMXN/E8GHCZVIMFBpuxHpSglRE1FEcOPClX2Bbgq@zLxIvImN1s38nJlvzmSX5fTsKivn59NZmS2Xxazjx9diztVT3OUhXnP9eUynxNUL1xuu3/j@htsNcVMbbr6OuN2uudlp6K5bDfvtlu8@FqHMud2dRPOLiB9uozwryigIYbxYT7h9F1w9C@2QGimUgUulXPVSjFgOYfKzkcB7EElBHpaglRTOwSegkSCMzJhoDzsDCl3v4KHUAFsNm0C7P7ueosO0d7ZILHQM35vHsAbWwmspkrj3N@GkFFrDJXAKKj28GF74X9Dvi0H5Bg "APL (Dyalog Classic) – Try It Online") doesn't support matrices smaller than 3x3 due to [a bug](https://chat.stackexchange.com/transcript/52405?m=42700294#42700294) in the interpreter [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Hmm, seems long. ``` ỊẠ€T ŒJ_€`Ç€ḟ"J$ịFg"FÇịF ``` A monadic Link accepting a list of lists of positive integers which returns a list of each of the values which are in hostile neighbourhoods (version 1 with no de-duplication). **[Try it online!](https://tio.run/##ZU4xDoIwFN05RUMcO9CWtnABTJjdGqKLMTFcwNWFRDcmNz2AB1BxIxykXqS@UoiDyS99vPd@39tv6/rgnO1O9nX7HO@raGjLNcCmb/C1j2tcLmx3LnZx0TceuOE9SkNrnxfcmKVzxhihKMnTihLDU0pUXlU0IqAzSrSmhDEvMSDJKBHc/ymsaOhsNitssgQnvAMz57NZCqzCLNRkzpGH8Rpu8YMjGzyI8jNG/8OpoaQkwxEI1kEHkqgiwWrhmSwJTVNfyRMCeQqEQj@OtOoL "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##ZU4xDoIwFN05RUMcO9CWtnABTJjdGqKLMTFcwNWFRDcmNz2AB1BxIxykXqS@UoiDyS99vPd@39tv6/rgnO1O9nX7HO@raGjLNcCmb/C1j2tcLmx3LnZx0TceuOE9SkNrnxfcmKVzxhihKMnTihLDU0pUXlU0IqAzSrSmhDEvMSDJKBHc/ymsaOhsNitssgQnvAMz57NZCqzCLNRkzpGH8Rpu8YMjGzyI8jNG/8OpoaQkwxEI1kEHkqgiwWrhmSwJTVNfyRMCeQqEQj@OtOoL "Jelly – Try It Online"). ### How? ``` ỊẠ€T - Link 1: indices of items which only contain "insignificant" values: list of lists Ị - insignificant (vectorises) -- 1 if (-1<=value<=1) else 0 € - for €ach: Ạ - all? T - truthy indices ŒJ_€`Ç€ḟ"J$ịFg"FÇịF - Main Link: list of lists of positive integers, M ŒJ - multi-dimensional indices ` - use as right argument as well as left... € - for €ach: _ - subtract (vectorises) € - for €ach: Ç - call last Link (1) as a monad $ - last two links as a monad: J - range of length -> [1,2,3,...,n(elements)] " - zip with: ḟ - filter discard (remove the index of the item itself) F - flatten M ị - index into (vectorises) -- getting a list of lists of neighbours F - flatten M " - zip with: g - greatest common divisor Ç - call last Link (1) as a monad F - flatten M ị - index into ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~182~~ ~~177~~ 166 bytes ``` lambda a:[[all(gcd(t,a[i+v][j+h])<2for h in[-1,0,1]for v in[-1,0,1]if(h|v)*(i+v>-1<j+h<len(a)>i+v))for j,t in E(s)]for i,s in E(a)] from fractions import* E=enumerate ``` [Try it online!](https://tio.run/##ZVDLbsIwEDyXr/ANGxYJ28QBlHDjK1wfXEhIUF4yLlKl/nu6m7RqpUq2MjOeyax2@IhV36mxzF/HxrdvV8/80VrfNPx2ufII3tbrp7P3deVEpso@sIrVnd1I2IJ0xJ9/eF3y6vMpVhxDp43MMJY1Rce9OKEiBPnvEDHBzvwhpnwNj5l74RZl6FtWBn@Jdd@h3g59iKvFOS@697YIPhYjZTwlrLXaADvsHDCrdsDMwRG0eg8sTYFJSVQiSiQwrYgZTKT4Lr@9BnNyi3f@C3qV@vEmGpPo1Wb2HrAMD2H86l84qZMFe@hMvf/hPF0CbI9XY2s6PyNKcI4E1VSTst/OU@5oHhI0thkUDA6nsMsdFy9DqLvIPCzz0xJs6weOHMK05EALKmml4/gF "Python 2 – Try It Online") Outputs a list of lists with True/False entries. [Answer] # [Haskell](https://www.haskell.org/), 95 bytes ``` m?n|l<-[0..n-1]=[a|i<-l,j<-l,a<-[m!!i!!j],2>sum[1|u<-l,v<-l,(i-u)^2+(j-v)^2<4,gcd(m!!u!!v)a>1]] ``` [Try it online!](https://tio.run/##ZVDBboUgELy/r1iTHjDFFwFFTdT3Bf0CShPTNi1WiKlPT/673dXYHpoAu8zMMhM@u@nrfRi2zd/COtSJSa/XkAjbmG51dTLwno4OCR9FLop6y2U7zd6IdSZmoYO5ZI5f5CPrkwVrnfGP1zeGA3MULXHXCms3F8b5PjWGGaM0hyqzHIzMOOjK4psxJ6LkUBQchCBSYJcLDkrSTeNQgbwgudrlGqdFivt4C@VSnvJc4TDKlf6VV@iKi1is6q/d0VOFhrT2AP/bU6VyDiVuhfbFocAux0A5ooUipEyPxBkFI0Chp0ZAY0pJjllsLxffuQAN@G58AvbMPIcQQ9LC@O3CHR7Aw42Q4/@2Hw "Haskell – Try It Online") The function `?` takes the matrix `m` as a list of lists and the matrix size `n`; it returns the list of entries *in hostility*. ]
[Question] [ A matrix can be thought of as the altitudes of a surface in 3D space. Consider the 8 neighbours (orthogonal and diagonal) of a cell as a cyclic sequence in clockwise (or anticlockwise) order. Some neighbours may be higher than the original cell, some lower, and some levelled at the same height as the original cell. We split the cycle of neighbours into segments according to that property and discard the levelled segments. If we end up with exactly 4 segments alternating between higher and lower, we call the original cell an *order-2 saddle point*. Boundary cells (edges and corners) are never considered to be saddle points. Your task is to output the number of order-2 saddle points in a given matrix. For instance, in the matrix ``` 3 3 1 4 2 3 2 1 2 ``` the central cell's neighbours in clockwise order are ``` 3 3 1 3 2 1 2 4 + + - + - + // + for higher, - for lower a a b c d a // segments ``` Note that the list is cyclic, so we consider the final `4` part of the initial segment `a`. The signs of segments `abcd` are alternating - this is indeed a saddle point. Another example: ``` 1 7 6 5 5 5 2 5 6 ``` Neighbours: ``` 1 7 6 5 6 5 2 5 - + + + - a b b c d ``` We have 4 +/- segments but their signs are not alternating, so this is *not* a saddle point. Note how segment `b` is separated from segment `c` by a levelled segment. We discard the levelled segment, but `b` and `c` remain separated. Same goes for `d` and `a`. Third example: ``` 3 9 1 8 7 0 3 7 8 ``` Neighbours: ``` 3 9 1 0 8 7 3 8 - + - - + - + a b c c d e f ``` The signs are alternating but the number of +/- segments is 6. This is known as a *monkey saddle* or an *order-3 saddle point*. For the purposes of this challenge we should *not* count it. Write a function or a complete program. Input is an integer matrix as typically represented in your language. It will consist of integers between 0 and 9 inclusive. Output is a single integer. Standard loopholes are forbidden. The shortest solution per language wins, as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ([obviously?](https://codegolf.meta.stackexchange.com/questions/13090/does-the-op-have-to-explicitly-state-the-winning-criteria)) indicates. ``` in out [[3,3,1],[4,2,3],[2,1,2]] 1 [[1,7,6],[5,5,5],[2,5,6]] 0 [[3,9,1],[8,7,0],[3,7,8]] 0 [[3,2,3,9,0,4,2,1,9,9,1,4,8,7,9,3], [1,1,5,7,9,9,0,9,8,9,9,8,8,9,0,5], [5,8,1,5,1,6,3,5,9,2,5,6,9,0,7,5], [3,0,2,4,7,2,9,1,0,0,7,2,4,6,7,2], [6,7,1,0,2,7,3,2,4,4,7,4,5,7,3,2], [6,5,1,1,6,2,1,2,8,9,4,6,9,7,1,0], [1,6,1,8,2,2,7,9,2,0,2,4,8,8,7,5], [0,6,5,4,1,3,9,3,2,3,7,2,2,8,5,4]] 19 [[2,3,2,0,8,5,5,1,2,3,7,5,6,0,0,5], [4,1,4,9,4,7,3,8,6,8,4,2,8,7,1,7], [4,1,4,6,9,3,0,1,0,7,8,5,3,0,5,3], [5,6,0,8,0,4,9,3,2,9,9,8,4,0,0,3], [7,4,1,6,7,8,7,3,6,1,4,9,4,6,2,0], [3,1,6,7,9,7,7,6,8,6,8,1,4,9,7,0], [8,9,1,1,2,4,8,2,3,9,8,7,5,3,1,9], [0,9,5,3,8,7,7,7,8,9,0,0,2,7,3,4]] 31 [[6,6,2,3,4,6,5,4,9,5,5,1,4,7,7,6], [1,5,0,5,6,7,9,8,5,0,5,6,1,5,2,9], [0,0,0,6,1,8,1,1,9,0,7,4,5,4,5,5], [4,5,3,6,3,8,0,0,7,3,9,1,3,9,2,2], [8,8,5,3,7,1,0,7,1,1,8,1,3,0,7,7], [4,5,8,0,7,2,0,4,6,7,3,3,2,8,1,2], [1,1,6,2,5,8,4,2,6,1,6,9,8,4,8,1], [3,9,1,7,0,8,1,1,7,8,5,4,8,2,0,3]] 7 ``` [Answer] # JavaScript (ES6), 179 bytes ``` a=>a.map((r,y)=>r.map((v,x)=>t+=x*y/r[x+1]&&a[y+1]?[...(S='12221000')+S].map((n,i)=>p-(p=d=Math.sign(v-a[y+~-n][x+~-S[i+2&7]]))&&d?s&s!=-(s=d)?T=a:T++:0,T=s=p=0)|T>>1==4:0),t=0)|t ``` [Try it online!](https://tio.run/##fVPBjtowEL3zFdsLmxSH2o5jO1SGL@gJblEO0bK7pdoCIgiBVO2v05nnGHrYraIkM/abmec341/dqeufDpv9sdju1s/Xl3Dtwryb/u72WXYQlzzMD9E5iTM5x0k4f718OzTniWrH46650H/RTKfTbBkeldZaSSkf88myjWFbsaGwfZHtwzr86I4/p/3mdZudCg59L7YtZXovls1moseubfN8PF4v@nH/JRRZH9b5YhW62WoymUmxCn3YB5n/Wc3nKgQzk7k4sn@8Pu22/e7tefq2e81esmb08NCUohSqFWwaoUUZTS2U0O2I6oxGHwQp4YSNyErQk4IqWv00qBR1quQpXkazJNP/L4g4UaAUzE6RRUnI5gx1YqtoqcICA2varPH18KtE1AOmhKWMFW2BLyAugUpyNKV39OVCEpu8YvkfQWwqAJ0osckBBhTKO4hLcTFoCS4G5RCciFtyPG1r0NdDeY/zDZyk4FyGgCxEFMQhxPM6tPv@oXgaaAlcBRYcyYeWd10M9KxxhpKgll6D5EzU/QuyqC9xeIes7FWpDTGxR68i0dgGg3IDyOEkFvFc0N7Ks1K3oYgQFsuBkUX3DFZkGqIaCkfB4phANp5oUSfxaix4ZHLDSKTemc8Hz4JPCV4VCkcNTaSU@ldBgMjV3zxe13cK/MRGK4ywHMbF3O@OAUsLpnHocF3w1Wmm/KC5GzqghpwlPHfP5IexlcPgluiGx6W@3RiLCxCbbeHHZvl0SyMDh54qWBg4iM39hHbXvw "JavaScript (Node.js) – Try It Online") ### How? We iterate on each cell \$v\_{y,x}\$ of each row \$r\_y\$ of the input matrix. We first make sure that we're not located over an edge of the matrix with: ``` x * y / r[x + 1] && a[y + 1] ``` (neither \$x\$ or \$y\$ is \$0\$ and both \$v\_{y,x+1}\$ and \$r\_{y+1}\$ are defined) We iterate twice on each neighbor cell and keep track of the number of valid segments in \$T\$. By doing this, each segment is guaranteed to be counted twice, except the first one which may be counted either twice or three times, depending on its starting point in relation to the starting point of the cycle. Either way, we have \$\lfloor{T/2}\rfloor=4\$ for order-2 saddle points, in which case we increment the counter \$t\$. Example: If the first segment is aligned with the starting point: ``` neighbor cells: AAAABCCD --> AAAABCCDAAAABCCD ^ ^^ ^^ ^^ ^ --> T = 8 ``` If it is not aligned: ``` neighbor cells: AABCCDAA --> AABCCDAAAABCCDAA ^ ^^ ^^ ^^ ^^ --> T = 9 ``` We iterate on neighbor cells by starting with the rightmost one and moving clockwise with: ``` [...(S = '12221000') + S].map((n, i) => a[x + ~-n][y + ~-S[i + 2 & 7]]) ``` [Try it online!](https://tio.run/##LYvLDsIgFET39ytmZSFSAvjooqk/0SVhQWpjaio01ph2468jPlZnzkzm6p9@7u7D9ChDPPcpeTSwBIuDwFGgghMf24tSC6i/7QSMgIYjVxMt@aJrWn@gLoY5jr0c44URYKWUrM1boY0xWilVcGzROnnzE2NBYOBoTvB2yfWrDM6u39DaIdNgg8o5TjylNw "JavaScript (Node.js) – Try It Online") We store the sign of the difference between the current cell and its current neighbor in \$d\$. We keep track of the previous value of \$d\$ in \$p\$ and the previous sign (for non-zero values) in \$s\$. The logic to update \$p\$, \$s\$ and \$T\$ reads as follows: ``` p - (p = d) && d ? s & s != -(s = d) ? T = a : T++ : 0 ``` In plain English: * Ignore identical consecutive values. * Ignore segments with \$d=0\$. * Increment \$T\$ on valid sign transitions. * Whenever an invalid sign transition is detected, do `T = a` to force all upcoming operations on \$T\$ to either ***NaN*** or \$0\$, thus invalidating the final test. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~70~~ 66 bytes ``` D←⊢-1∘⌽ +/,{16=×/|D⍵/⍨×⍵×D⍵}¨(⍉1↓⌽)⍣4×(⊢-{⊂(,⍵)[8(-,⊢)3,⍳3]}⌺3 3)⎕ ``` [Try it online!](https://tio.run/##bVM9jxMxEO33V7jzrvAp/lrbW1DdiR9AG7aIgENIxwUdCAmFayjCKbqcQAhCQ0N1HQWiQaK5/BP/kTDzbFJFq1177Od5z29mZy/Pjp68nZ3Nn@3y1YfT3UlefsyrH0cmX33L13@bexO1MOH@djN5d5LXvyd5fbvd0GS74fDy7vbupxX05uVnk1dfDZ3ZblrOsMir960iUDcNYhBJROEp/OXGy3z9xwnX5ZsvTNrk9XfxYH7xYvZaPJ6fv3l68er5/Lw5JiULgrCg5ae8vmmlkhQ/lEJ2rXw0lqBDMC1BKztWtTttjoWcTp1yyoxq6pVVjkarjLLjKJuSVsqmAo2KKhCgV/QA2FN8AOjUgIyJDmgaHY3pMJAoCawVkxua0UGa88EBYgzFPSJGDbQz4JsQ91CTgDEqUK6e1qEL@xEIRzNLWSN9Ob/GDq8EHgnBowEqKocdRnswu4pgBuaAPeD3YMFJKA00S7RnoddW1oTbsA6tOIsnFN@53D0Cn3j9kEEWMA1AD2I@wtfT9foehg0Q7AgX6PVIycLiHhFAqXHNiHwc9TC55EsoQxFWTPZgYUSE7ICTzBP2rGxIqXHZZ0MiVAQUxmNFoxsGWFhMKYWHNdx/aoBBA6KEHLEW@X9ZDhoUIMBBSA@yYpQvMlCXHhct4tI@4nVbafkp1TPoQl2r72une8gKkFa6By2Or0V/pGpprAabms0hijVHqp2na@85mJ3ww5VeD@jeUsKAuBQi4YcqrBHFMpihc2AnF2qU/wA "APL (Dyalog Unicode) – Try It Online") *-4 bytes thanks to @Bubbler and @ngn* Full program that requires `⎕IO←0` ``` ⍝ Helper function D: cyclic differences of a list D←⊢-1∘⌽ ⊢ ⍝ Each element - ⍝ Subtract 1∘⌽ ⍝ The one after ⍝ Main code +/,{16=×/|D⍵/⍨×⍵×D⍵}¨¯2 ¯2↓1⊖1⌽×(⊢-{⊂(,⍵)[6 9 8 7 4,⍳3]}⌺3 3)⎕ ⎕ ⍝ The input grid {...}⌺3 3 ⍝ For the 3×3 window centered on each cell: (,⍵)[8(-,⊢)3,⍳3] ⍝ Obtain the cycle elements clockwise from the right ⊂ ⍝ Ensure that the output is the same shape as G ×⊢- ⍝ The sign of the difference between each cycle and its center in G (⍉1↓⌽)⍣4 ⍝ Trim off the entries with centers on an edge/corner {...}¨ ⍝ For each sign-difference cycle: ×⍵×D⍵ ⍝ The indices where a +/- segment ends ⍝ (nonzero and different from the following element) ⍵/⍨ ⍝ The signs of each segment in order ⍝ (must be ¯1 1 ¯1 1 or reverse to be truthy --- can only have entries +/- 1) D ⍝ Cyclic differences (must be 2 ¯2 2 ¯2 or reverse to be truthy --- can only have entries ¯2, 0, or 2) 16=×/ ⍝ Test if product is 16: ensures right length and right values. ⍝ Note that the sum of the cyclic differences are always 0, so 2 2 2 2 is impossible) +/, ⍝ Count the total number that meet the condition ``` A creative idea I had was taking 2×2 stencils of 2×2 stencils with `({⊂⍵}⌺2 2)⍣2⊢G` then extracting cycles with `{1⌷⊃,/0 1 2 3{⍉∘⌽⍣⍺⊢⍵}¨,⍵}¨`. This might have been shorter (if golfed a bit more) because it didn't initially require `¯2 ¯2↓1⊖1`, but unfortunately we still had to subtract corresponding elements of G. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 66 bytes ``` gÍF3£D¬gÍFε3£}`R«ćªćU«X.Sγ€Ù˜ÐнsθQsʒ0Ê}©gs-4Q®ü‚€OÄO0Q&ˆ€¦}\\¦D}¯O ``` I'm 100% sure that I can reduce some bytes here, working on it :) Meanwhile, I'll post this basic idea. Explenation: ``` gÍF3£D¬gÍFε3£}`R«ćªćU«X.Sγ€Ù˜ÐнsθQsʒ0Ê}©gs-4Q®ü‚€OÄO0Q&ˆ€¦D}\\¦}¯O `R«ćªćU«X.Sγ€Ù˜ÐнsθQsʒ0Ê}©gs-4Q®ü‚€OÄO0Q&ˆ Expects a 3x3 matrix. We will run this part for each relevant cell in the overall matrix. Pushes 1 to the global array when this cell is order-2 saddle point, pushes 0 otherwise. ---------- gÍ number of rows in the matrix minus 2. F } Loop Rows-2 times 3£ Take 3 first rows. D¬ Push itself and the first element (first line) gÍ Size. (number of columns) F } Loop Cols-2 ε3£} Trim first 3 elements from each of the selected 3 rows. €¦D Remove the first element of each row and duplicate it for the next iteration. \\¦ Clear remaining elements on stack, remove current first row of the 3 rows, prepare for next iteration. ---------- ` Push the 3x3 matrix we got from the nested loop in 3 separate values to the stack. Last row on top. R Reverse last row. « Merge with the second row. ćª Extract head and append ćU Extract head and save in X « Merge with the first row. Now all values of the cell are in order clockwise. X.S For each element in the list, put -1 if lower than X (middle of cell), 0 if equal, 1 if greater. γ Split a into chunks of equal adjacent elements. (segment) €Ù˜ Uniquify each element and flat the list. Ð Triplicate нsθQ Extract head, extract tail, are they equal? sʒ0Ê}© Filter (remove zeros from the list), save the filtered list in register C g Size of the filtered list. s- Size of the filtered list - [1 if head was equal to the tail] 4Q Is it equal to 4 (segments)? {{Condition I}} ®ü‚ Overlapping pairs €O Sum each pair (desired: [-1,1] or [1,-1] will give 0) Ä Abs(a) O0Q Is the sum of all sums of pairs equals 0? (which means there was alternating 1/-1) {{Condition II}} & Does both of the conditions were okay? ˆ Push the result to the global array. ---------- ¯O Push the global array and sum its values to get the number of order-2 saddle points. ``` [Try it online!](https://tio.run/##PY89SwNBEIb/jdUo@5X76IPtcYogXA5UkGCV4uoDCWJAEMROsRMCmqCFCBbazKYycPgb8kfWdychDDsz785z786NmtOzi/MQhv523/Jzn@ex6z7RtycHPFtM@HUxOeLZ8d5h97Eaz/3D8snf/f003VfZ/N4rf9Pyy7DZdSW/@e/V5SOYwl8VqtxZXqPnab8dDHja8nsRQlUllJAhSw61h5wj90ijSxFJTZWGVjgJdE7ZVsV7QzkIRTHiTYajQSmwTvzgBiJWC8KCUDK1oLRkQwZEJs4WEy1zvXGzotKNRybKIDvZxyKMcEY21fI3kXOoiehcFBgQ61dTfL/eNJVX4zR62roO/w) [Answer] # [Python 2](https://docs.python.org/2/), 254 bytes ``` lambda m:sum(s(m[i][j:j+3],m[i+1][j:j+3],m[i+2][j+2::-1][:3])for j in range(len(m[0])-2)for i in range(len(m)-2)) t=['-','+']*2 def s(q,(x,m,y),w):a=''.join(' -+'[cmp(m,v)]for v in q+[y]+w+[x]);return[v for v,_ in zip(a,a[-1:]+a)if' '!=v!=_]in(t,t[::-1]) ``` [Try it online!](https://tio.run/##hVPbcptADH33V5AnoMidvQC70PGXUCZDG7vFE7BjO07Sn3elsxvXyUvNYFarI@nskXb/dvq9m81ls/p@eRymHw9DMrXH5yk7ZlM39t223Ra2J14X@oNl2CpM2y55u7V9vtkdkm0yzslhmH@ts8f1zAlUny8NXOMnl@zni9OqS5cppUXafzGLh/UmOWZPlL3SRG85veTtsErTr9vdOGdpsizS7ue0zyY6573kPEvOp6J764uXonvt82@H9en5MHfnBG66F8CfcZ8NNHRL3fbFkI@bNEnvVue71X3PaU906nCI/LI/jPMp2WRdZ8mS7qkryRAftzOkyfR9TsntTy8W/0I0OaoZWhE/CKnY/hyibkMsNajiOVTx1/LX/y@ECXGYIqGmecUpeC0pGqG6SJiJ5toOPsWvx8rjq4QbYyq2BKWp5nwVe8AXCBcxlteGczv@lyoKPtmp5QuMrDRwjix8gi9R314xUkcqQUbwKFELsZFzzWvPXgPmJtb2OFngo0gylYwTBYISDhFe9oNwurmVywCmAKhQXELkoOoqRQkBGxC3jKz5LZFU6LkbTI2yCgd2yClWFWUPWT1aE@gF2UvUChgH@jWipVp9rS3iqCh7QIg8DmxqNKvETsB4NERHicJIQCiZW2qiXA1sjzwutv@9VVEu@2GGa9CwoFOhYJCtDFRipyocOlD0V0v2zbW0PKGjGlOq4lSU4XZA0goCWEimQKqJvTVxcnwU2UXJdcxoYblrHh8nU8XZtJDf49K@34gaEx5aW8MOzfFyBSG7VHdoocYKUwV5pX2Qy13@Ag "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~237 218~~ 207 bytes ``` ->a,z=0,i=j=1{l=z+=1if[[*a[i-1][h=j-1,3],(x=a[i])[j+1],*a[i+1][h,3].reverse,x[h]].map{|n|l=n<=>x[j]}.drop_while{|i|i==l}.map{|b|b==l||(l=b)==0?5:l}-[5]]-[[1,-1]*2,[-1,1]*2]==[];x[1+j+=1]||a[1+i+=j=1]?redo:z} ``` [Try it online!](https://tio.run/##bVPbbtpAEH3nKyz1JQkL2ov34rSbfMhqVYFChJGbIKq2FMy305mztuGhwpidmTMzZ88Mh1/rv9f3eF28rMQpStHGXVTnLp7mUbXvKT2tUrtQOW3jbqGEyeLhGMmVH9NurrLg8JzDFFoeNr83h58bcUzbnJc/Vvtz/9F38eNbfDmmXb4s3w6f@@9/tm23Ofdt38bYXQps3a/J6PuHLq4fY5Sv9rm7LJLNeZGSEkTgSYtEBPiQY0z56zGp@Y5I5r5f0bGdM/H8eti8fT6fLtd9ReRnVZWMqOghqmzUotJkF4NOiuw8y7n6UqnZbMohtxeVKzArKn6mHMuRkiPvcqhJM/UJKCCLYWCE/@ZoYUQjpKjppOjU0LsWQXg6DTTp0sLCwcCGgg3eAbYdSQbAlHBU0VJI09sB4keQIUNTeU9vbiQRZI/j3wLiowLQC4MgJ9SgYG4gbsXNmLYGlxrtkDwSd2QECmvQ10P7gPsNnKTgWjUBWYgiiEdKYP84nOZONQ2YBMCiPafwbeVNkBpCNiBvCOroW6MqM/T3IIfGErf2qMqWHfUvhQOGVBgW/Wu0G0AeV3DI54Zuas8STYtQIKySByOHsdXwyHF1GkhblCr7Ab0Epzejag0cAZX8sAvj0EbVzP1OOzAxYGTRsqhXFzLjyCyuXliGyWK/vjXnT5mtwtbKYUP4O@lvIYOBchK8mmHKelyjMKjtB@3VUNPA8rdKYdhUOeyqwRwYqm9/EoedL2N2sMuYCDbqzww8pqlwwo5BZp5kUc1f/wE "Ruby – Try It Online") ]
[Question] [ You have been given N piles of coins. You have decided to divide each of those B1, B2, ..., BN piles among separate groups of people. The amount of people receiving coins has to be a prime number and the amount of money given to each person must be different in each pile. Input: N, B1, B2, ..., BN (The amount of coins in each individual pile). Output: NP1, NP2, ..., NPN with NP being the number of people(prime number) receiving the coins. If this is impossible then yield some unachievable result (like `0`, `-1`, `None`, `[]`, or `"impossible"`) or raise an error. Example: ``` 3 7 8 9 ``` Output: `7 2 3` Because 7 is the only prime number that can divide 7 evenly, the same for 8 and 2 and 9 and 3. Also, notice that (7 / 7 = 1) ≠ (8 / 2 = 4) ≠ (9 / 3 = 3). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Ò.»â€˜ʒ÷DÙQ}θ ``` **[Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//8OSLsK7w6LigqzLnMqSw7dEw5lRfc64//9bNyw4LDEyXQ "05AB1E – Try It Online")** A port of my Pyth answer. * `Ò` gets the prime fact**Ò**rs of each. * `.»` folds a dyadic command, `â` (c**â**rtesi**â**n product) between each two elements in the list from right to left with opposite right/left operands. * `€˜` flattens **€**ach. * `ʒ...}` filt**ʒ**rs those which satisfy the following condition: + `÷` pairwise integer division with the input. + `D` **D**uplicate (pushes two copies of the item to the stack). + `Ù` removes duplicate elements, keeping a **Ù**niq**Ù**e occurrence of each element. + `Q` checks for e**Q**uality. * `θ` gets the last element. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ³:ŒQẠ ÆfŒpÇÐfṪ ``` A full-program which accepts one argument, a list of numbers, and prints a representation of another list of numbers, or `0` if the task is impossible. **[Try it online!](https://tio.run/##ASkA1v9qZWxsef//wrM6xZJR4bqgCsOGZsWScMOHw5Bm4bmq////WzcsOCw5XQ "Jelly – Try It Online")** ### How? ``` ³:ŒQẠ - Link 1, unique after division?: list of primes, Ps e.g. [7,2,2] or [7,3,3] ³ - program's first input e.g. [7,8,8] or [7,9,30] : - integer division by Ps [1,4,4] [1,3,10] ŒQ - distinct sieve [1,1,0] [1,1,1] Ạ - all truthy? 0 1 ÆfŒpÇÐfṪ - Main link: list of coin stack sizes, Bs e.g. [7,8,12] Æf - prime factorisation (vectorises) [[7],[2,2,2],[2,2,3]] Œp - Cartesian product [[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3]] Ðf - filter keep if: Ç - call last link (1) as a monad 1 1 0 1 1 0 1 1 0 - [[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2]] Ṫ - tail (note: tailing an empty list yields 0) [7,2,2] - implicit print ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` ef{I/VQT.nM*FPM ``` **[Try it here!](http://pyth.herokuapp.com/?code=ef%7BI%2FVQT.nM%2aFPM&input=%5B7%2C8%2C12%5D&debug=0)** ### How? ``` ef{I/VQT.nM*FPM | Full program, which foregoes the size. | PM | Prime factorisation of each integer. *F | Fold Cartesian Product over the list of primes. .nM | Flatten each. f | Filter. {I/VQT | Filter condition (uses a variable T). /V | Vectorised integer division... QT | Over the input and the current item. {I | Is invariant over deduplication (removing duplicates)? e | Take the last element. | Output the result implicitly. ``` ]
[Question] [ I've been really interested with sequences that follow the property \$a(n+1) = a(n - a(n))\$ recently, so here's another question about these sequences. In particular we are concerned with sequences from the integers to the natural numbers. A periodic sequence with the above property is an **n**-Juggler if and only if it contains exactly **n** distinct values. For example the following sequence is a 2 juggler ``` ... 2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1 ... ``` because it only contains the numbers `1` and `2`. An example of a three juggler would be ``` ... 3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5 ... ``` because it juggles `1`, `3`, and `5`. # Task Given **n > 1** as input, output any **n**-Juggler. You may output a sequence in a number of ways, you can * output a function that indexes it. * take an additional input of the index and output the value at that index. * output a continuous subsection of the sequence that, with the given property *uniquely determines* the sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with less bytes being better. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` t+*%E ``` Try the **[2](https://pyth.herokuapp.com/?code=t%2B%2a%25E&input=3%0A0&test_suite=1&test_suite_input=2%0A0%0A%0A2%0A1%0A%0A2%0A2%0A%0A2%0A3%0A&debug=0&input_size=3)**, **[3](https://pyth.herokuapp.com/?code=t%2B%2a%25E&input=3%0A0&test_suite=1&test_suite_input=3%0A0%0A%0A3%0A1%0A%0A3%0A2%0A%0A3%0A3%0A%0A3%0A4%0A%0A3%0A5%0A%0A3%0A6%0A%0A3%0A7&debug=0&input_size=3)**, **[4](https://pyth.herokuapp.com/?code=t%2B%2a%25E&input=3%0A0&test_suite=1&test_suite_input=4%0A0%0A%0A4%0A1%0A%0A4%0A2%0A%0A4%0A3%0A&debug=0&input_size=3)** Jugglers. Receives two numbers, **N** and **I**, separated by a newline and in this order. **I** is the index into the sequence. This uses a quite simple formula: **N - 1 + N \* (I % N)**. Its validity was [confirmed by the OP](https://chat.stackexchange.com/transcript/message/40787752#40787752). [Answer] # CJam, 9 How about this? ``` q~1$,=)*( ``` [Try it online](http://cjam.aditsu.net/#code=q~1%24%2C%3D)*(&input=3%200) Input is `n i` where `n` is the main input and `i` is the index you want to get the value for. **Explanation:** ``` q~ read and evaluate the input (n and i) 1$ copy n ,= basically this is a modulo (i%n) that avoids a negative result for negative i )* increment, then multiply by n ( decrement ``` [Answer] # [Haskell](https://www.haskell.org/), 17 bytes ``` n!i=i`mod`n*n+n-1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08x0zYzITc/JSFPK087T9fwf25iZp6CrUJuYoGvQkFRZl6JQnR0noKiQqZCDRDb6CpEG@rpGRrExgL5eWC@kZ6eaWzsfwA "Haskell – Try It Online") Another answer using Mr. Xcoder's idea. I wouldn't be able to answer the question otherwise to be honest. :P [Answer] # [Python 2](https://docs.python.org/2/), 20 bytes ``` lambda n,i:i%n*n+n-1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9MqUzVPK087T9fwf1p@kUKeQmaeQlFiXnqqhpGOuaYVlwJINBMhamqgaVVQlJlXopCmAdSuqcOlAOb@BwA "Python 2 – Try It Online") Same principle as [Mr. Xcoder's answer](https://codegolf.stackexchange.com/a/146397/38592) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` %›*‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIl4oC6KuKAuSIsIiIsIjNcbjAiXQ==) [Answer] # Java 8, 15 bytes ``` n->i->i%n*n+n-1 ``` Boring port of [*@Mr.Xcoder*'s Pyth answer](https://codegolf.stackexchange.com/a/146397/52210). [Try it here.](https://tio.run/##jU4xasNAEOz1isUQOEXREQdSSafS4MKVy5DicpbNyue9Q1oZjNHblRUc2EWKwMIMzMzOdPZqyxBb6g7n2Xk7DLCzSPcMYGDL6KAThx4ZvT6O5BgD6U0i9Za4PbX92/9MiTQNODAwU9mg3Au9UkHleq6kUy6OP15qU/s14AEuskjtuUc6fX2DzZd1AMfQKyQGMh8VUG3W7wJFkdSHjkYErM3nAk86wP42cHvRYWQd5Tkrp22M/qYoTwTzYgWrvEqRKfs76Eklz@KYsmn@BQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ɠ%×+’ ``` [Try it online!](https://tio.run/##y0rNyan8///YZNXD07UfNcz8/9/gvwkA "Jelly – Try It Online") Port of Mr. Xcoder's approach. The index I is in STDIN, N is an argument. ]
[Question] [ **The Problem:** This challenge comes from a real problem I was having. I have a dual monitor setup at work, and I wanted to use the following image as my wallpaper: [![Ideal Image](https://i.stack.imgur.com/2bdJJ.jpg)](https://i.stack.imgur.com/2bdJJ.jpg) However, my monitors have quite significant bezels, and when I set my background, it looks something like this, where the pier appears (appiers?) to be broken: [![Issue Image](https://i.stack.imgur.com/JJfpR.jpg)](https://i.stack.imgur.com/JJfpR.jpg) I was able to solve this by making an image with the center cut out of it, and then stretching it back to the original size, as in the image below: [![Challenge Image](https://i.stack.imgur.com/0Ayao.jpg)](https://i.stack.imgur.com/0Ayao.jpg) --- **The Challenge:** Write a program that takes in an image and "monitorizes" it for use with a dual monitor setup (i.e. deletes the center section of the image, where the bezels are). The rules are as follows: 1. It must be a full program that accepts the image, either as a path (string argument, etc), or in the form of a file chooser dialog. 2. The program must take as an input the number of vertical lines (one pixel in width) to crop out from the center of the image 3. The cropping must come from the center (width-wise) of the original image 4. The resultant image must be re-scaled back to the original size of the input image. (Either the halves can be scaled individually, and then concatenated, or concatenated and then scaled. Scaling individually produces a better image/effect, but is hardly noticeable in the real world) 5. Background images are generally even, so to make this challenge easier, input images will only have an even number of pixels, and number of lines to remove will only be even as well. 6. This challenge is code golf - shortest code in bytes wins **Good Luck!** [Answer] ## Matlab 2013, 150 bytes Here is my attempt in Matlab. Definitely won't be the shortest code, but it's a start. Warning, this overwrites the original image, so make a copy first. **Golfed Version** ``` function mi(f,n) o=imread(f); s=size(o); imwrite([imresize(o(:,1:((s(2)-n)/2),:),[s(1),s(2)/2]) imresize(o(:,((s(2)+n)/2):end,:),[s(1),s(2)/2])], f); end ``` --- **Ungolfed Code, with improvements for odd image sizes and odd number of columns** ``` function monitorizeImage( filename, num_columns ) orig = imread(filename); orig_size = size(orig); f = factor(orig_size(2)); origsize_iseven = f(1)==2; f = factor(num_columns); num_columns_iseven = f(1)==2; odd_even_size_mismatch = xor(origsize_iseven,num_columns_iseven); img_resized = imresize(orig,[orig_size(1) orig_size(2)+odd_even_size_mismatch]); leftimg = img_resized(:,1:((orig_size(2)+odd_even_size_mismatch-num_columns)/2),:); leftimg = imresize(leftimg,[orig_size(1),floor(orig_size(2)/2)]); rightimg = img_resized(:,((orig_size(2)-odd_even_size_mismatch+num_columns)/2):end,:); rightimg = imresize(rightimg,[orig_size(1),floor(orig_size(2)/2)]); monitorized_image = [leftimg rightimg]; monitorized_image = imresize(monitorized_image,[orig_size(1),orig_size(2)+ ~origsize_iseven]); [~, ~, ext] = fileparts(filename); imwrite(monitorized_image,strcat(filename(1:end-length(ext)),'_',num2str(num_columns),ext)); end ``` [Answer] # Wolfram Language, ~~134~~, ~~127~~, ~~119~~ 111 bytes ``` f[i_,c_]:=(d=ImageDimensions@i;ImageAssemble[ImageTake[i,a=All,#]&/@{{0,e=-#&@@d/2-c/2},{-e,a}}]~ImageResize~d) ``` Creates a function `f` that takes an image as the first input (as a symbol in Mathematica or the Wolfram Cloud), and an integer as the second input. **Ungolfed**: ``` f[image_,columns_]:=( (*Define Function*) d=ImageDimensions[image]; (*Get image dimensions*) e=d[[1]]/2+columns/2; (*Add half the image width to half the number of removed columns*) ImageResize[ImageAssemble[Map[ImageTake[i,All,#]&,{{0,-e},{e,All}}]],d] (*Map the function onto a list with the desired column ranges and merge and scale the resulting image*) ) ``` ~~Technically, it won't work properly if either of the image dimensions exceed 362,880 pixels, but I assume that's okay, since that is way outside the scope of the problem (and some computers).~~ Fixed! [Answer] # PHP, 206 bytes ``` ($c=imagecopyresized)($t=imagecreatetruecolor($w=imagesx($s=imagecreatefrompng($argv[1])),$h=imagesy($s)),$s,0,0,0,0,$v=$w/2,$h,$x=$v-$argv[2]/2,$h);$c($t,$s,$v,0,$w-$x,0,$v,$h,$x,$h);imagepng($t,$argv[3]); ``` takes three command line arguments: source file name, number of lines to crop and target filename. Run with `-r`. You may want to use `imagecopyresampled` instead of `imagecopyresized` (+2 bytes) for a better result. **ungolfed** ``` $s=imagecreatefrompng($argv[1]); # load source image $w=imagesx($s);$h=imagesy($s); # get image dimensions $t=imagecreatetruecolor($w,$h); # create target image $v=$w/2; # $v = half width $x=$v-$argv[2]/2; # $x = width of remaining halves # resize and copy halves: imagecopyresized($t,$s, 0,0, 0,0,$v,$h,$x,$h); imagecopyresized($t,$s,$v,0,$w-$x,0,$v,$h,$x,$h); imagepng($t,$argv[3]); # save target image ``` I could save 9 more bytes by sending the PNG result to STDOUT ... but what for? [Answer] ## Octave, 85 bytes ``` @(f,n)imsave(imresize((o=imread(f))(:,[1:(end-n)/2,(end+n)/2:end],:),size(o)(1:2)),f) ``` Defines an anonymous function with `f` the file name, and `n` the number of columns to remove. Since an anonymous function requires a single expression, inline assignment is used, a feature not present in MATLAB. ### MATLAB, 98 bytes As a bonus, I also golfed a MATLAB compatible answer. Interestingly, this is only 13 bytes longer, since the Octave version needs a lot of parentheses to correctly parse the inline assignments. ``` function m(f,n) o=imread(f);imsave(imresize(o(:,[1:(end-n)/2,(end+n)/2:end],:),size(o(:,:,1))),f) ``` ]
[Question] [ # Introduction One day, you were just relaxing in your office in the CIA, when suddenly you see an alert on your computer. Your programs have just intercepted hundreds of coded messages! A quick examination reveals the rule for encoding, but you need a program in order to decode fast. # Challenge You will be given a list of strings, separated by commas. Each string will contain either: * Part of the coded message + It is part of the coded message if it is **not** in the form `a=b`. Note that it **is** part of the message if it is `ab=c`. Add this string to the coded message. * Part of the encoding scheme + This will be in the form of `a=b`. That means that all a's in the message must be replaced by b's. Note that it could be `a==`, meaning that all a`s must be replaced with ='s. Your program must then output the message, decoded using the scheme found. Other info: Your input will only contain commas for separating the strings. It could contain other characters, like !1#, etc. It will not contain uppercase letters. Bits of decoding info do not decode each other. Only the message is affected by the decoding information. Only one replacement will be given for each character, e.g. no `"io,"i=u","i=g"` # Examples Input:`"ta","y=s","y","a=e","b=t","b"," ","j","j=1"` Output:`test 1` Input:`"z=p","zota","g=e","yugkb","y=t","u=o","k=s","li","fg","b=="` Output:`potatoes=life` Input:`"p","=","==n","ot","p=a","hiz","i=e","z=r"` Output:`another` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # Python 3, 98 ``` lambda l:''.join(x*('='!=x[1:-1])for x in l).translate({'='!=x[1:-1]or ord(x[0]):x[2:]for x in l}) ``` This `lambda` function receives a list of strings (input) and returns a string (the decoded message). Examples: ``` >>> f(['ta', 'y=s', 'y', 'a=e', 'b=t', 'b', ' ', 'j', 'j=1']) 'test 1' >>> f(['z=p', 'zota', 'g=e', 'yugkb', 'y=t', 'u=o', 'k=s', 'li', 'fg', 'b==']) 'potatoes=life' >>> f(['p', '=', '==n', 'ot', 'p=a', 'hiz', 'i=e', 'z=r']) 'another' ``` [Answer] # Haskell, 85 bytes ``` f x=[(a,b)|[a,'=',b]<-x] h x=map(\v->maybe v id$lookup v$f x)$concat[c|c<-x,[]==f[c]] ``` ### Usage ``` >h ["p","=","==n","ot","p=a","hiz","i=e","z=r"] >"another" ``` ### Description `f` creates a lookup table. `concat[c|c<-x,[]==f[c]]` extracts the message. `map(\v->maybe v id$lookup v$f x)` perfoms the lookup. [Answer] # JavaScript (ES6), 87 bytes ``` (l,s='',d={})=>l.map(v=>/.=./.test(v)?d[v[0]]=v[2]:s+=v)&&[...s].map(c=>d[c]||c).join`` ``` ``` <input id=a oninput="try{b.innerText=((l,s='',d={})=>l.map(v=>/.=./.test(v)?d[v[0]]=v[2]:s+=v)&&[...s].map(c=>d[c]||c).join``)(eval(`[${a.value}]`))}catch(e){}"/> <p id=b /> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḊṖ⁼“=” ÇÐfKm2yÇÐḟF$ ``` **[Try it online!](https://tio.run/nexus/jelly#@/9wR9fDndMeNe551DDH9lHDXK7D7YcnpHnnGlWCGA93zHdT@f//f7RSgZKOki0I2@YByfwSIFFgmwgkMzKrgGSmbSqQrLItUooFAA "Jelly – TIO Nexus")** ### How? ``` ḊṖ⁼“=” - Link 1, isMappngElement?: string Ḋ - dequeue Ṗ - pop “=” - char-list,['='] ⁼ - equal? ÇÐfKm2yÇÐḟF$ - Main link: list of strings Ðf - filter keep: Ç - last link (1) as a monad K - join with spaces m2 - modulo 2 slice (every other character) $ - last two links as a monad: Ðḟ - filter discard: Ç - last link (1) as a monad F - flatten y - translate right according to the mapping of left ``` [Answer] # Retina, ~~84~~ ~~82~~ ~~77~~ 74 bytes Takes a comma-separated list as input. Note the trailing newline ``` ^|$ ,, +`,(.=.)(,.*) $2$1 M!&`(.).*,,.*\1=.|.+, %`(.).*,$|.*(.) $1$2 \n|, ``` [Try it Online!](https://tio.run/nexus/retina#LYxBDoIwFET3/xSaFFNg0qTs/9qVNyCGligCBoiWBU3vjl/jZjKZmTeZPjf7NSkCqGygDZtcwxQ5qUpZuhxPjTa5KSBZbdkkU4Kyf6aSKcSRsqqiekqgfQ8OG7@xwfENngM8DhgwsKXIC@Isg06qbe1GL9OAlWeMgjx73DtBmBYwmCfMAQs7PPqIXpDIL3K@leeveP45bj8) **Explanation:** First, we move all expressions of the form `.=.` to the end of the string and separate these from the message with a double comma (`,,`). This is so that in the next step, we can find all encodings by checking if each character ahead of the `,,` has a matching `=.` afterwards. This is achieved by `M!&`(.).*,,.*\1=.|.+,` which finds all such matches and places them into a linefeed separated list of strings. We then modify each string to only contain either one unencoded character or the encoded version of the character. Finally we replace all linefeeds and commas with the empty string so that our output is formatted nicely. [Answer] ## Batch, 188 bytes ``` @echo off set/pm= set c= for %%s in (%m%)do call:c %%s "%%c%%%%~s" not for %%s in (%m%)do call:c %%s "%%c:%%~s%%" echo %c% exit/b :c set s=%~1 if %3 "%s:~1,1%"=="=" call set c=%~2 ``` Explanation: Loops through the list of strings twice (conveniently `for` likes a string in CSV format). The first time, looks for strings that do not contain an `=` as the second character, and concatenates them to the result. The second time, looks for strings that do contain an `=` as the second character, and performs the substitution. (even more conveniently, the substitution is already in Batch format.) [Answer] # PHP, 116 Bytes ``` <?foreach($_GET as$i)$i[1]=="="&&strlen($i)==3?$r[]=$i:$s.=$i;foreach($r as$l)$s=str_replace($l[0],$l[2],$s);echo$s; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/7c45c0d1bcbef3abdd22c0d8823f8a9f7ded3b7f) [Answer] # PHP, ~~89~~ 87 bytes two versions: ``` while(a&$s=$argv[++$i])3==strlen($s)&"="==$s[1]?$t[$s[0]]=$s[2]:$m.=$s;echo strtr($m,$t); while(a&$s=$argv[++$i])preg_match("#^.=.$#",$s)?$t[$s[0]]=$s[2]:$m.=$s;echo strtr($m,$t); ``` takes input from command line arguments; run with `-nr`. * loop through arguments creating parameters for `strtr` (translation if argument contains `=`, message else). * perform `strtr`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes ``` vy'=åyg3Q&iyˆyS}})øJÁ¨`¹¯KJ.Ás‡ ``` [Try it online!](https://tio.run/nexus/05ab1e#@19WqW57eGllunGgWmbl6bbK4NpazcM7vA43HlqRcGjnofXeXnqHG4sfNSz8/z9aqcq2QElHqSq/JBFIpdumAsnK0vTsJBBtWwIkS23zgWS2bTGQzMkEEmnpQCLJ1lYp9mtevm5yYnJGKgA "05AB1E – TIO Nexus") ``` vy } '=åyg3Q& # See if it's length 3 with an equals in the mid. iyˆyS # If so, add to global array, split into chars. } )øJÁ¨` # Transpose, join, and remove the middle =. ¹¯KJ # Push original input without decryption key. .Ás‡ # Shift stack to the right, swap and transliterate. ``` ]
[Question] [ Given positive integer `n < 10`, create a 2 dimensional matrix where each location is filled with its `x` and `y` index (starting from the top left). For example: Input: 2 ``` 00 10 10 11 ``` Input: 3 ``` 00 10 20 01 11 21 02 12 22 ``` Once the grid is created, randomly fill each index. This can be with an 'x' or any other way to denote a spot has been filled. You determine which location to fill by randomly generating indices to fill the matrix. You can only fill n^2 times so you cannot fill as many times as you want until the matrix is completely filled. At the end the matrix must be filled so you must do some work to make sure that you check the random numbers that you use to fill to make sure that spot is not already filled. Refresh or print after each fill in order to show the progression of the filling iterations. Example for filling: Input: 2 ``` 00 10 01 11 ``` `00` is randomly chosen: ``` XX 10 01 11 ``` `01` is randomly chosen: ``` XX 10 XX 11 ``` `00` is randomly chosen, but since it's already been chosen a re-roll chooses `10`: ``` XX XX XX 11 ``` `11` is randomly chosen: ``` XX XX XX XX ``` Do not print out the random numbers as visually I should be able to see which index was selected. By this I mean do not print "`11` is randomly chosen:". It is here for exploratory sake. Since this is code-golf The shortest code wins. Have fun and happy golfing! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 29 bytes ``` <ÝDâJU[X¹ä»,XÐÙg#Jþ2ô.R„ :)U ``` [Try it online!](http://05ab1e.tryitonline.net/#code=PMOdRMOiSlVbWMK5w6TCuyxYw5DDmWcjSsO-MsO0LlLigJ4gIDopVQ&input=OQ) Space chosen as the char for the removed numbers (as it looks nice), but it could be replaced with any char without affecting byte-count. **Explanation** ``` # implicit input n <ÝDâ # cartesian product of [0..n-1] and [0..n-1] JU # join pairs and store in X [ XÐÙg# # loop until there's only spaces left in X X¹ä # split X into n pieces », # join rows by space and columns by newlines and print Jþ # join X to string and remove all non-digits 2ô.R # split in pieces of 2 and pick a pair at random „ :) # replace this pair with 2 spaces U # and store in X ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), ~~41~~ ~~40~~ ~~38~~ 36 bytes 35 bytes of code, +1 for the `-S` flag. ``` Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r} ``` Takes input from cmdline argument. Replaces with space (any other character is possible for +1 byte). Outputs successive iterations separated by a single newline (which is legal but can make it a bit hard to read). [Try it online!](http://pip.tryitonline.net/#code=UG06Sl9NTSBaQ0dhe1NUOm1tUjphc1gyfU0kQUxtU0t7cn0&input=&args=LVM+Mw) ~~All kinds of dirty tricks in this one.~~ Shorter version has fewer dirty tricks. :^( Explanation: ``` Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r} -S flag means nested lists are delimited first by newlines then by spaces when stringified/printed a 1st cmdline arg CG Coordinate Grid, a list of lists of coord pairs Z Zip (transposes so it's x,y instead of row,col) J_ Function that takes a list and joins all items MM MapMap: map this function to each sublist This joins a coord pair [1;0] into a string "10" Pm: Assign the result to m and print it $ALm Fold m on Append List: appends all sublists of m together, making a single list of coord pairs SK Sort with the following function as key: {r} Return a random number We now have a randomly-ordered list of all the coord pairs from m { }M Map this function to that list: ST:m Convert m to string in-place mR: Replace (in-place)... a the argument (a coord pair)... sX2 ... with two spaces The map operation returns a list of strings, one for each step of the process, which are autoprinted (separated by newlines) ``` [Answer] # Groovy (202 Bytes) ``` {a->b=new String[a][a];while(b.flatten().flatten().contains(null)){b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX";b.eachWithIndex{e,i->e.eachWithIndex{f,j->print f?"XX ":"${i}${j} "}println()}}} ``` That specific output format really messed up my byte count, but meh. Try it out: <https://groovyconsole.appspot.com/edit/5171951567896576> (+9 bytes for a prettier print) ## Ungolfed: ``` y={a-> b=new String[a][a]; while(b.flatten().flatten().contains(null)) { b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX"; b.eachWithIndex{ e,i-> e.eachWithIndex{ f,j-> print f ? "XX ": "${i}${j} " } println() } } } y(4)​ ``` ## Output Example: ``` 00 01 02 XX 10 11 12 13 20 21 22 23 30 31 32 33 00 01 02 XX XX 11 12 13 20 21 22 23 30 31 32 33 XX 01 02 XX XX 11 12 13 20 21 22 23 30 31 32 33 XX 01 XX XX XX 11 12 13 20 21 22 23 30 31 32 33 XX 01 XX XX XX 11 12 XX 20 21 22 23 30 31 32 33 XX 01 XX XX XX 11 12 XX XX 21 22 23 30 31 32 33 XX 01 XX XX XX 11 XX XX XX 21 22 23 30 31 32 33 XX 01 XX XX XX XX XX XX XX 21 22 23 30 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 30 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 30 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 23 XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 XX XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 XX XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 XX XX 31 32 33 XX XX XX XX XX XX XX XX XX 21 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX 31 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX 32 XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX 22 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX ``` [Answer] # R, ~~84~~ ~~81~~ 74 bytes Now uses one-indexing rather than zero-indexing. Got rid of 7 bytes thanks to @Billywob. ``` N=scan() m=outer(1:N,1:N,paste0) for(i in sample(N^2)){m[i]="XX";print(m)} ``` Example output for N=3 ``` [,1] [,2] [,3] [1,] "11" "12" "XX" [2,] "21" "22" "23" [3,] "31" "32" "33" [,1] [,2] [,3] [1,] "11" "12" "XX" [2,] "21" "22" "23" [3,] "31" "XX" "33" [,1] [,2] [,3] [1,] "11" "12" "XX" [2,] "XX" "22" "23" [3,] "31" "XX" "33" [,1] [,2] [,3] [1,] "11" "XX" "XX" [2,] "XX" "22" "23" [3,] "31" "XX" "33" [,1] [,2] [,3] [1,] "XX" "XX" "XX" [2,] "XX" "22" "23" [3,] "31" "XX" "33" [,1] [,2] [,3] [1,] "XX" "XX" "XX" [2,] "XX" "22" "23" [3,] "XX" "XX" "33" [,1] [,2] [,3] [1,] "XX" "XX" "XX" [2,] "XX" "XX" "23" [3,] "XX" "XX" "33" [,1] [,2] [,3] [1,] "XX" "XX" "XX" [2,] "XX" "XX" "XX" [3,] "XX" "XX" "33" [,1] [,2] [,3] [1,] "XX" "XX" "XX" [2,] "XX" "XX" "XX" [3,] "XX" "XX" "XX" ``` [Answer] ## AWK, 229 bytes ``` func p(a){for(k=1;k<=m;k++){if(k==a)gsub("[0-9]","X",M[k]) printf"%s",M[k]}}{n=$1;m=n*n k=1 for(i=0;i<n;i++)for(j=0;j<n;j++){s=k%n==0?k==m?"\n\n":"\n":" " M[k++]=i j s}p() for(;z<m;z++){do{y=int(rand()*m+1)}while(M[y]~"X")p(y)}} ``` I added a few bytes to give the output a space between each matrix. Note: to make it more 'random' between runs, a call to `srand()` could be added for 7 additional bytes. Usage and output after storing above code in `FILE`: ``` awk -f FILE <<< 2 00 01 10 11 XX 01 10 11 XX XX 10 11 XX XX 10 XX XX XX XX XX ``` [Answer] # PHP, 172 Bytes ``` for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0);echo($c=chunk_split)(join(" ",$r),$a*3);for(;$q<$s;){if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX;echo$c(join(" ",$r),$a*3);} ``` Breakdown ``` for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0); #make the array echo($c=chunk_split)(join(" ",$r),$a*3); # Output array for(;$q<$s;) { if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX; #fill position if it is not XX and raise increment echo$c(join(" ",$r),$a*3); #Output array } ``` [Answer] # Python 2, 190 bytes ``` from random import * R=range(input()) G=[(x,y)for x in R for y in R] def f():print"\n".join(" ".join(["XX","%d%d"%(x,y)][(x,y) in G]for x in R)for y in R) f() while G:G.remove(choice(G));f() ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 bytes ``` ↑{'×'@⍵⊢x}¨,\⊂¨y[?⍨≢y←,x←⍳2/⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@P2qbWK1@eLq6w6PerY@6FlXUHlqhE/Ooq@nQispo@0e9Kx51LqoEqtapABKPejcb6QP1x/4Hav2fxmUKAA "APL (Dyalog Unicode) – Try It Online") Uses `⎕IO←0` (0-indexing) Uses the `×` symbol for replacement, in a grid of co-ordinate pairs. ## Explanation ``` ↑{'×'@⍵⊢x}¨,\⊂¨y[?⍨≢y←,x←⍳2/⎕] ⎕ get the input n ⍳2/ create an n×n coordinate grid x← store in x y←, convert to a list, and store in y ?⍨≢ get indexes for shuffling the list y[ ] and get a random permutation of y ⊂¨ wrap each list ,\ and get it's array prefixes { }¨ for each prefix: '×'@⍵⊢x place an '×' at those coordinates in the grid x ↑ align all the grids into a matrix ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 (or 17 or 19?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L<ãíJD.rĆvDIô,yðº: ``` [Try it online.](https://tio.run/##ASMA3P9vc2FiaWX//0w8w6PDrUpELnLEhnZEScO0LHnDsMK6Ov//Mw) The program above outputs each matrix on a separated line. If these matrices have to be pretty-printed, a `»` can be added before the `,`: [try it online](https://tio.run/##ASUA2v9vc2FiaWX//0w8w6PDrUpELnLEhnZEScO0wrssecOwwro6//8z). (Using the exact output format as the challenge description is 22 bytes: [try it online](https://tio.run/##ASkA1v9vc2FiaWX//0w8w6PDrUpELnLEhnZEScO0wrsswrY/eeKAnlhYOv//Mw).) If we're allowed to output with 1-based indexing instead of 0-based, the `<` can be dropped for -1 byte: [try it online.](https://tio.run/##ASIA3f9vc2FiaWX//0zDo8OtSkQucsSGdkRJw7QsecOwwro6//8z) **Explanation:** ``` L # Push a list in the range [1, (implicit) input] < # Optional: decrease each by 1 to change the range to [0, input) ã # Create all possible pairs of this list í # Reverse each pair J # Join each pair together to a single 2-digit string D # Duplicate this list .r # Pop and shuffle this copy Ć # Enclose, appending it's own head # (this is so the final iteration will print the empty matrix) v # Loop `y` over each index in the shuffled list: D # Triplicate the unshuffled matrix Iô # Pop one copy, and split it into parts equal to the input » # Optional: join each inner list by spaces, and then each string by newlines , # Pop and print this matrix with trailing newline y # Push the current random index ðº # Push a space, and mirror it to two spaces: " " : # Replace the index in the list with these double spaces ``` ]
[Question] [ ## Task Your task is simple. Write a program or function which takes three positive integer arguments \$n\$, \$k\$, and \$b\$ in any order, such that \$2 ≤ b ≤ 36\$, and returns or outputs the nth (1-indexed) base-\$b\$ digit after the decimal point of the rational number (\$b^k-1)^{-2}\$. The output must be correct for \$n\$ and \$b^k\$ up to the largest integer value your language of choice can natively represent. This will most likely mean that you cannot depend on built-in floating point representations to exactly represent the base-\$b\$ expansion of the number. Fortunately, this class of numbers has a rather nice property [Spoiler Alert!]: <https://www.youtube.com/watch?v=daro6K6mym8> ## Rules * Base conversion built-ins are permitted. * Built-in spigot functions capable of indexing digits of exactly represented real numbers are forbidden. * The digits for base \$b\$ are the first \$b\$ symbols in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ` or alternately `0123456789abcdefghijklmnopqrstuvwxyz`. Your choice. ## Winning This is code golf. Shortest solution in bytes wins. ## Test Cases (You need not be able to correctly handle all of these if \$n\$ or \$b^k\$ overflows your integer datatype.) ``` Input (n,k,b) Output 9846658,3,31 5 789234652,4,10 4 4294967295,17,2 1 4294967254,72,15 B 137894695266,3,30 H 184467440737095595,6,26 L 184467440737095514,999,36 T ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes ``` (⎕D,⎕A)⊃⍨⊃⎕⌽¯1⌽,⍉⎕(⊣⊤⍳⍤*~*-2⍨)⎕ ``` [Try it online!](https://tio.run/##JYw9CsJAEIVr5yRJSCD7m91SEMFK8AaBJDZBLSy0sRH8CW6wyQlMYWdhbeNR5iLrBJuP9968efmmTop9Xq@XSbnblquiLDy23WyOp3sKpKYLUoybDPByrnxA0SQmjENsjuieA9sOb5/vixFjdFfyATYPbHp0b3R9dIgSTtWQDp5W/KgCAYKBNVJrZYC8BJZCZiwXUis@JCwDDpJbaXXGrYL/UwpMUE1qq7jW8AM "APL (Dyalog Extended) – Try It Online") A full program that takes numbers from stdin in the order of `k`, `b`, `n`. `n` being 1-based cost me 3 bytes `¯1⌽`. ### How it works The main mathematical trick is well explained in [Neil's answer](https://codegolf.stackexchange.com/a/70656/78410). The gist is that the repeating part of the base-`b` representation consists of length-`k` base-`b` digits of `0..b^k-1`, except `b^k-2`. This answer implements it very literally: list all repeating base-`b` digits, cyclically fetch `n`th digit from it, and convert it to `0-9A-Z`. Cyclic indexing uses [ngn's trick](https://codegolf.stackexchange.com/a/177911/78410). ``` ⎕(...)⎕ ⍝ Take k (the right) and b (the left) from stdin ⍳⍤*~*-2⍨ ⍝ Create a list of 0..b^k-1, and remove the number b^k-2 ⊣⊤ ⍝ Convert these numbers into base-b digits into columns ,⍉ ⍝ Transpose and flatten to get the repeating base-b digits ⊃⎕⌽¯1⌽ ⍝ Take n from stdin and get the nth digit cyclically (⎕D,⎕A)⊃⍨ ⍝ Convert the number to the corresponding char in 0-9A-Z ``` [Answer] ## ES7, 59 bytes ``` (n,k,b)=>(1+!(n/k%(d=b**k-1))+d+--n/k%d).toString(b)[n%k+1] ``` ES6-compatible version for people who don't have Firefox Nightly: ``` (n,k,b)=>(1+!(n/k%(d=Math.pow(b,k)-1))+d+--n/k%d).toString(b)[n%k+1] ``` Explanation (possibly the same as in the video; I haven't watched it): I start with the simple case of (b-1)-1 in b-ary notation. Obviously b-1 does not divide 1, so we add an extra zero after the b-ary point. 1.0 divided by b-1 is 0.1 remainder 0.1. This continues in the obvious manner to give (b-1)-1 as being 0.111... in b-ary notation. (bk-1)-1 is not much harder; the only difference is that we have to add k extra zeros before we can divide. We then have 1.00...00 [k zeros] divided by bk-1 is 0.00...01 remainder 0.00...01 [k-1 zeros]. This obviously continues to give (bk-1)-1 as being 0.00...0100...0100... [k-1 zeros each time] in b-ary notation. To form (bk-1)-2 it merely suffices to divide (bk-1)-1 itself by bk-1. Again we consider k digits each time. The first k digits are just 00..01 which obviously don't divide by bk-1, so the first k digits of the result are 00..00. The next k digits are of course also 00..01 so we divide bk+1 by bk-1 giving 1 remainder 2. Considering the next k digits we divide 2bk+1 by bk-1 giving 2 remainder 3. At each step we have mbk+1 = m(bk-1)+m+1. This continues until we reach (bk-3)bk+1 which divides by bk-1 giving bk-3 remainder bk-2. At this point (bk-2)bk+1 is equal to (bk-1-1)(bk-1+1)+1 which can be written as (bk-1)2-12+1 or simply (bk-1)2, which therefore divides exactly by bk-1. We therefore have managed to divide the first k(bk-1) digits of (bk-1)-1 by bk-1 exactly, and the sequence therefore repeats at this point. In effect, (bk-1)-2 is formed by concatenating all the (zero-padded) k-digit numbers from 0 to bk-3, plus bk-1 itself, and then repeating. My solution divides n-1 by k and then reduces modulo bk-1 to find the appropriate k-digit number. If n is an exact multiple of k(bk-1) it adds 1 to the number because the last k-digit number is bk-1 itself. Having found the number it then adds bk, which has the effect of forcing the base conversion to generate any required leading zeros. The appropriate digit of the converted number is then returned. [Answer] ## Python 2, 110 bytes ``` n,k,b=input() n=~-n%(k*b**k-k) print"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[(n/k+(n/k+2==b**k))/b**(k-1-n%k)%b] ``` Maybe answering it myself (poorly) will bring this EASY question some more attention. Usually easy questions get more answers... ]
[Question] [ **This question already has answers here**: [The centers of a triangle](/questions/11767/the-centers-of-a-triangle) (3 answers) Closed 8 years ago. Try to write the shortest program or function you can that prints or returns the calculated orthocenter of a triangle. The orthocenter of a triangle is the intersection point of the three altitudes of a triangle. The altitude of a triangle is a perpendicular segment from the vertex of the triangle to the opposite side. ![](https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Triangle.Orthocenter.svg/220px-Triangle.Orthocenter.svg.png) Input: * Three points in 2D space correponding to the triangle's vertices Output: * The calculated orthocenter of the triangle A sample input would be ``` A(0,0) B(3,6) C(6,0) ``` and a sample output would be: ``` Calculated Othocenter (3, 1.5) ``` One formula for orthocenter can be written as ``` (x, y) = ((ax*tan(α) + bx*tan(β) + cx*tan(γ))/(tan(α) + tan(β) + tan(γ), (ay*tan(α) + by*tan(β) + cy*tan(γ))/(tan(α) + tan(β) + tan(γ)) ``` Shortest program in bytes wins. [Answer] # Python, ~~193~~ 168 Should work for any valid triangle... ``` def h(a,A,b,B,c,C): if A==B:b,B,c,C=c,C,b,B m=(a-b)/(B-A) return m,C-m*c def f(a,A,b,B,c,C): m,q=h(a,A,b,B,c,C) k,z=h(c,C,b,B,a,A) x=(q-z)/(k-m) return (x,k*x+z) ``` [Answer] # CJam, 90 bytes ``` q~:C2$]_2ew::.-:D;;D1=0=D2=0=*D1=1=D2=1=*+D0=1=D2=0=*D0=0=D2=1=*-/_D0=1=*C0=+C1=@D0=0=*-S\ ``` [Try it online](http://cjam.aditsu.net/#code=q~%3AC2%24%5D_2ew%3A%3A.-%3AD%3B%3BD1%3D0%3DD2%3D0%3D*D1%3D1%3DD2%3D1%3D*%2BD0%3D1%3DD2%3D0%3D*D0%3D0%3DD2%3D1%3D*-%2F_D0%3D1%3D*C0%3D%2BC1%3D%40D0%3D0%3D*-S%5C&input=%5B0.%200.%5D%20%5B3.%206.%5D%20%5B6.%200.%5D) CJam isn't really optimized for geometry, so the code isn't doing anything fancy. It uses the parametric representation for two of the lines passing through a corner and being orthogonal to the opposite side, and solves the 2x2 system of equations resulting from intersecting the two lines. Well, it only needs one of the resulting parameters, which is then used for calculating the intersection point. Note that some of the signs in the intermediate values are wrong. Instead of flipping them with additional code, I kept them the way they are, and corrected for the wrong sign by changing additions to subtractions (or vice versa) when the value is used later. For example, if you see a `+` where you would normally expect a `-` when calculating a determinant, that's because one of the terms has the wrong sign. In fact, both determinants have the wrong sign (at least relative to my paper notes), but that doesn't matter because they are divided by each other. Since the input format was not precisely specified, I made it CJam friendly. The code expects 3 points in CJam array format, where the values have to be floating point. For the given example, the expected input is: ``` [0. 0.] [3. 6.] [6. 0.] ``` Explanation: ``` q~ Get and interpret input. :C Store away the last point in variable C. Will be needed at the end to calculate the intersection point. 2$] Repeat the first point, and wrap all points in an array. _2ew Generate array with all pairs of points [[A B] [B C] [C A]]. ::.- Calculate the vector difference of all point pairs [A-B B-C C-A]. These are the vectors for each side of the triangle. :D;; Store the side vectors in a variable, and clear the stack. D1=0=D2=0=*D1=1=D2=1=*+ Calculate determinant for first unknown in 2x2 system of equations. D0=1=D2=0=*D0=0=D2=1=*- Calculate main determinant of 2x2 system of equations. / Divide the two determinants. This gives the parameter of the intersection point for the line starting at C and orthogonal to A-B. _ Copy it because we'll need it twice. D0=1=*C0=+ Calculate x-coordinate of intersection point. C1=@D0=0=*- Calculate y-coordinate of intersection point. S\ Put a space between the two values. ``` [Answer] # R, ~~102~~ ~~70~~ 68 bytes As an unnamed function which implements the formula in the question. The parameter for the function a vector of complex numbers (X+Yi) and it returns a complex number. I'm assuming that complex numbers are okay for input and output. ``` function(E)sum((F=tan((D=Arg(E-E[c(3,1,2)]))-D[c(2,3,1)]))*E)/sum(F) ``` **Edit** Vectorized it a lot Expanded explanation ``` f=function(E){ D=Arg(E-E[c(3,1,2)]); # Angles of sides F=tan(D-D[c(2,3,1)]); # Internal triangle angles tangents sum(E*F)/sum(F); # Orthocenter coordinate return } ``` Test ``` > f=function(E)sum((F=tan((D=Arg(E-E[c(3,1,2)]))-D[c(2,3,1)]))*E)/sum(F) > f(c(0+0i,3+6i,6+0i)) [1] 3+1.5i ``` [Answer] # Cobra - 247 ``` def f(p as System.Drawing.Point[]) a,b,c=p d,e,f=for q in[[b,c],[a,c],[a,b]]get if(z=q[0].x-q[1].x,(q[0].y-q[1].y)/z,0f) print (a.x*(g=((e-f)/(1+e*f)).abs)+b.x*(h=((d-f)/(1+d*f)).abs)+c.x*(i=((e-d)/(1+e*d)).abs))/(j=g+h+i),(a.y*g+b.y*h+c.y*i)/j ``` ]
[Question] [ The task is to write code that can find small logical formulae for sums of bits. The overall challenge is for your code to find the smallest possible propositional logical formula to check if the sum of y binary 0/1 variables equals some value x. Let us call the variables x1, x2, x3, x4 etc. Your expression should be equivalent to the sum. That is, the logical formula should be true if and only if the sum equals x. Here is a naive way to do it to start with. Say y=15 and x = 5. Pick all 3003 different ways of choosing 5 variables and for each make a new clause with the AND of those variables AND the AND of the negation of the remaining variables. You end up with 3003 clauses each of length exactly 15 for a total cost of 45054. Your answer should take be a logical expression of that sort that can just be pasted into python, say, so I can test it. If two people get the same size expression, the code that runs the fastest wins. You ARE allowed to introduce new variables into your solution. So in this case your logical formula consists of the y binary variables, x and some new variables. The whole formula would be satisfiable if and only if the sum of the y variables equals x. As a starting exercise some people may want to start with y=5 variables adding to x=2. The naive method will then give a cost of 50. The code should take two values y and x as inputs and output the formula and its size as the output. The cost of a solution is just the raw count of variables in its output. So `(a or b) and (!a or c)` counts as 4. The only allowed operators are `and`, `or` and `not`. **Update** It turns out there is a [clever method](http://www.cs.cmu.edu/~wklieber/papers/2007_efficient-cnf-encoding-for-selecting-1.pdf) for solving this problem when x =1, at least in theory . [Answer] ## Python, 644 A simple recursive equation generator. `S` generates an equation that is satisfied iff the list of `vars` adds up to `total`. There are some obvious improvements to be done. For instance, there are a lot of common subexpressions that appear in the 15/5 output. ``` def S(vars, total): # base case if total == 0: return "(" + " and ".join("not " + x for x in vars) + ")" if total == len(vars): return "(" + " and ".join(vars) + ")" # recursive case n = len(vars)/2 clauses = [] for s in xrange(total+1): if s > n or total-s > len(vars)-n: continue a = S(vars[:n], s) b = S(vars[n:], total-s) clauses += ["(" + a + " and " + b + ")"] return "(" + " or ".join(clauses) + ")" def T(n, total): e = S(["x[%d]"%i for i in xrange(n)], total) print "equation", e print "score", e.count("[") # test it for i in xrange(2**n): x = [i/2**k%2 for k in xrange(n)] if eval(e) != (sum(x) == total): print "wrong", x T(2, 1) T(5, 2) T(15, 5) ``` Generates: ``` equation (((not x[0]) and (x[1])) or ((x[0]) and (not x[1]))) score 4 equation (((not x[0] and not x[1]) and (((not x[2]) and (x[3] and x[4])) or ((x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))))) or ((((not x[0]) and (x[1])) or ((x[0]) and (not x[1]))) and (((not x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))) or ((x[2]) and (not x[3] and not x[4])))) or ((x[0] and x[1]) and (not x[2] and not x[3] and not x[4]))) score 27 equation (((not x[0] and not x[1] and not x[2] and not x[3] and not x[4] and not x[5] and not x[6]) and (((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6]))))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6]))))) and (not x[7] and not x[8] and not x[9] and not x[10] and not x[11] and not x[12] and not x[13] and not x[14]))) score 644 ``` [Answer] I would have made this a comment, but I don't have a reputation. I wanted to comment that the results of Kwon & Klieber (known as the "Commander" encoding) for k=1 have been generalised for k>=2 by Frisch et al. "SAT Encodings of the At-Most-k Constraint." What you're asking about is a special case of the AM-k constraint, with an additional clause to guarantee At-Least-k, which is trivial, just a disjunction of the all variables to the AM-k constraint. Frisch is a leading researcher in constraint modelling, so I would feel comfortable suggesting that [(2k+2 C k+1) + (2k+2 C k-1)] \* n/2 is the best bound known on the number of clauses required, and k\*n/2 for the number of new variables to be introduced. The details are in the quoted paper, along with the instructions of how this encoding to built. It's fairly simple to write a program to generate this formula, and I think such a solution would be competitive with any other solutions you'll likely find for now. HTH. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6284/edit). Closed 6 years ago. [Improve this question](/posts/6284/edit) Back when I was a freshman in highschool taking chemistry, I'd look at the periodic table of elements and spell dirty words out with the number of the elements (HeCK would be 2619, 2-6-19). I was thinking about this the other day when I saw an amazing shirt that spelled out BeEr (4-68) So my codegolf challenge is shortest program to output a list of words you can spell with the periodic table of elements AND the number code that would represent that word. /usr/share/dict/words or whatever dictionary you want to use for the word list. If you're using a "non-standard" word list, let us know what it is! [Answer] ## GolfScript (339 303 302 301 294 chars) ``` n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAl PSClArKCa TiVCrMnFe ZnGaGeAsSeBrKrRbSrYZr MoTcRuRhPdAgCd TeIXe BaLaCePrNdPmSmEuGdTbDy ErTm Lu TaWRe IrPtAuHgTl AtRnFrRaAcThPaU AmCm EsFmMd LrRfDbSg MtDsRg UutFl Lv'{[1/{.0=96>{+}*}/]}:S~:^/}%.{L}%2$?.){=S{^?}%`+p 0}{;{L.,2$<=},.}if}do}%; ``` With credit to [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) whose observation on unnecessary elements allowed me to save 33 chars. This is IMO much more idiomatic GolfScript than the previous recursive approach. Note that I allow words in the dictionary to be mixed case (`L` is a function to lower-case text on the assumption that it doesn't matter if non-alpha characters get broken) but reject any with apostrophes or accents. Since this is code golf, I've optimised for code length rather than speed. This is horrendously slow. It expects the word list to be supplied at stdin and outputs to stdout in the format: ``` "ac[89]" "accra[89 6 88]" "achebe[89 2 4]" ... ``` (lower-casing any mixed-case input words for which it finds a match). If you're more interested in the elements than the numbers per se, for the low low price of 261 253 chars you can use ``` n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAlPSClArKCaTiVCrMnFeZnGaGeAsSeBrKrRbSrYZrMoTcRuRhPdAgCdTeIXeBaLaCePrNdPmSmEuGdTbDyErTmLuTaWReIrPtAuHgTlAtRnFrRaAcThPaUAmCmEsFmMdLrRfDbSgMtDsRgUutFlLv'[1/{.0=96>{+}*}/]/}%.{L}%2$?.){=p 0}{;{L.,2$<=},.}if}do}%; ``` which gives output like ``` "Ac" "AcCRa" "AcHeBe" ... ``` [Answer] # Ruby - 547 393 New version, thanks for the suggestions: ``` e='HHeLiBeBCNOFNeNaMgAlSiPSClArKaCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'.scan(/[A-Z][a-z]*/).map &:upcase r="(#{e.join ?|})" $<.each{|w|(i=0;i+=1 until w=~/^#{r*i}$/i $><<w;p$~.to_a[1..-1].map{|m|e.index(m.upcase)+1})if w=~/^#{r}+$/i} ``` --- ``` e=%w{h he li be b c n o f ne na mg al si p s cl ar ka ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo} x = "(#{e.join(?|)})" regex = /^#{x}+$/i File.foreach('/usr/share/dict/words'){|w| if w=~/^#{x}+$/i puts w i=1 i+=1 until w=~/^#{x*i}$/i puts $~[1..-1].map{|m|e.index(m.downcase)+1}.join ?- end } ``` uses regexes. slow, and much room for improvement but i must go now :-) [Answer] ## Python 710 (357 + 261 + 92) ``` e=". h he li be b c n o f ne na mg al si p s cl ar k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo".split() i=e.index def m(w,p=("",[])): if not w:return p x,y,z=w[0],w[:2],w[:3] if x!=y and y in e: a=m(w[2:],(p[0]+y,p[1]+[i(y)])) if a:return a if x in e: b=m(w[1:],(p[0]+x,p[1]+[i(x)])) if b:return b if z in e: c=m(w[3:],(p[0]+z,p[1]+[i(z)])) if c:return c f=open('/usr/share/dict/words','r') for l in f: x=m(l[:-1]) if x:print x[0],x[1] f.close() ``` There's sure to be room for improvement in there somewhere. It's also worth noting that the second level of indentation uses the tab character. It takes just over 5 seconds (on my computer) to go through the whole dictionary, producing output like this: ``` acaciin [89, 89, 53, 49] acacin [89, 89, 49] acalycal [89, 13, 39, 6, 13] ... ``` By adding another **18** characters, you can get output with the right capitalization: ``` e=". H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Uup Lv Uus Uuo".split() i=e.index def m(w,p=("",[])): if not w:return p w=w.capitalize() x,y,z=w[0],w[:2],w[:3] if x!=y and y in e: a=m(w[2:],(p[0]+y,p[1]+[i(y)])) if a:return a if x in e: b=m(w[1:],(p[0]+x,p[1]+[i(x)])) if b:return b if z in e: c=m(w[3:],(p[0]+z,p[1]+[i(z)])) if c:return c OUTPUT: AcAcIIn [89, 89, 53, 49] AcAcIn [89, 89, 49] AcAlYCAl [89, 13, 39, 6, 13] ... ``` You can also check individual words: ``` >>> m("beer") ('beer', [4, 68]) ``` [Answer] ## Python - 1328 (975 + 285 chars of code + 68 dictionary code) ``` t1={'c':6,'b':5,'f':9,'i':53,'h':1,'k':19,'o':8,'n':7,'p':15, 's':16,'u':92,'w':74,'v':23,'y':39} t2={'ru':44,'re':75,'rf':104,'rg':111,'ra':88,'rb':37, 'rn':86,'rh':45,'be':4,'ba':56,'bh':107,'bi':83, 'bk':97,'br':35,'os':76,'ge':32,'gd':64,'ga':31, 'pr':59,'pt':78,'pu':94,'pb':82,'pa':91,'pd':46, 'cd':48,'po':84,'pm':61,'hs':108,'ho':67,'hf':72, 'hg':80,'he':2,'md':101,'mg':12,'mo':42,'mn':25, 'mt':109,'zn':30,'eu':63,'es':99,'er':68,'ni':28, 'no':102,'na':11,'nb':41,'nd':60,'ne':10,'np':93, 'fr':87,'fe':26,'fl':114,'fm':100,'sr':38,'kr':36, 'si':14,'sn':50,'sm':62,'sc':21,'sb':51,'sg':106, 'se':34,'co':27,'cn':112,'cm':96,'cl':17,'ca':20, 'cf':98,'ce':58,'xe':54,'lu':71,'cs':55,'cr':24, 'cu':29,'la':57,'li':3,'lv':116,'tl':81,'tm':69, 'lr':103,'th':90,'ti':22,'te':52,'tb':65,'tc':43, 'ta':73,'yb':70,'db':105,'dy':66,'ds':110,'at':85, 'ac':89,'ag':47,'ir':77,'am':95,'al':13,'as':33, 'ar':18,'au':79,'zr':40,'in':49} t3={'uut':113,'uuo':118,'uup':115,'uus':117} def p(s): o=0;b=0;a=[];S=str;l=S.lower;h=dict.has_key;L=len while o<L(s): D=0 for i in 1,2,3:exec('if h(t%d,l(s[o:o+%d])) and b<%d:a+=[S(t%d[s[o:o+%d]])];o+=%d;b=0;D=1'%(i,i,i,i,i,i)) if D==0: if b==3 or L(a)==0:return else:b=L(S(a[-1]));o-=b;a.pop() return '-'.join(a) ``` For the dictionary part: ``` f=open(input(),'r') for i in f.readlines():print p(i[:-1]) f.close() ``` [Answer] ## C, 775 771 chars ``` char*e[]={"h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","uut","fl","uup","lv","uus","uu",0}; b[99],n; c(w,o,l)char*w,*o,**l;{ return!*w||!strncmp(*l,w,n=strlen(*l))&&c(w+n,o+sprintf(o,",%d",l-e+1),e)||*++l&&c(w,o,l); } main(){ while(gets(b))c(b,b+9,e)&&printf("%s%s\n",b,b+9); } ``` **Input**: Word per line, must be lowercase. `usr/share/dict/words` is fine. **Output**: Word and numbers, e.g.: `acceptances,89,58,15,73,7,6,99` **Logic**: `c(w,o,l)` checks the word `w`, starting with element `l`. Two-way recursion is used - if the first element matches the head of the element list, check the remainer of `w` against the full element list. If this match fails, check the word against the tail of the list. The buffer `o` accumulates the element numbers along the successful path. After a match, it will contain the list of numbers, and is printed. **Issues**: The list isn't encoded efficiently - too much `"` and `,`". But this way it's easy to use. I'm sure it can be much improved, without too much cost in code. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/4900/edit). Closed 9 years ago. [Improve this question](/posts/4900/edit) **Where's Waldo** is a searching game where you are presented an image of some scene, and your goal is to find a man named Waldo in the picture. Here are a couple pictures showing what Waldo looks like. He always wears a red and white striped sweater and hat, blue pants, brown shoes and hair. He can be with or without accessories such as a camera, glasses, or a cane. ![](https://i.stack.imgur.com/otkrN.jpg) ![](https://i.stack.imgur.com/1Gpq7.jpg) And here are some of the scenes where Waldo is hidden. (You can right click the images and go to the image source for higher resolution.) ![](https://i.stack.imgur.com/FDKBZ.jpg) ![](https://i.stack.imgur.com/bGkYx.jpg) ![](https://i.stack.imgur.com/E5Pvx.jpg) ![](https://i.stack.imgur.com/QcAMq.jpg) ![](https://i.stack.imgur.com/XGDsj.jpg) # The Challenge Write a program that processes the images (provided as input however you like) and finds Waldo in as many of the above five images as possible. Your program is scored using the following formula ``` codeLength / numberOfPicturesInWhichWaldoIsFound ``` and, of course, the lower the score, the better. [Answer] # Shell script, score 30/5 = 6 Since there's no specification on what comprises finding Waldo (i.e. how exact the location must be specified), I figure this program should give a rather good score, finding Waldo in every one of those pictures. ``` echo Waldo is in the picture. ``` ]
[Question] [ A Bingo card is five columns of five squares each, with the middle square designated "FREE". Numbers cannot duplicate. The five columns are populated with the following range of numbers: * B:1-15 * I:16-30 * N:31-45 * G:46-60 * O:61-75 In as few characters as possible, output a string that can be interpreted as a randomized Bingo card. For example: > > 1,2,3,4,5,16,17,18,19,20,31,32,33,34,35,46,47,48,49,50,61,62,63,64,65 > > > This example is not randomized so that I can show that column 1 is populated with 1,2,3,4,5. Also note that the free space has not been given any special treatment because the front-end that interprets this string will skip it. Another example would be: > > 1,16,31,46,61,2,17,32,47,62... > > > In this example, the output is by row instead of by column. A third example might be: > > 01020304051617181920313233343546474849506162636465 > > > This is the same output as the 1st example except in fixed length. [Answer] # [R](https://www.r-project.org/), 38 bytes ``` cat(apply(matrix(1:75,,5),2,sample,5)) ``` [Try it online!](https://tio.run/##K/r/PzmxRCOxoCCnUiM3saQos0LD0MrcVEfHVFPHSKc4MbcgJxXI1vz/HwA "R – Try It Online") (another 7 years [later](https://codegolf.stackexchange.com/questions/2631/bingo-card-generator/257259#comment237021_97529)... ) [Answer] # PHP, 86 ``` for($o=[];25>$i=count($o);){$n=rand(1,15)+($i-$i%5)*3;$o[$n]=$n;}echo implode(",",$o); ``` [Answer] # R, ~~63~~ ~~51~~ ~~50~~ ~~49~~ 45 bytes Thanks to Billywob for ongoing suggestions and encouraging my competitive streak. ``` cat(sapply(split(n<-1:75,cut(n,5)),sample,5)) ``` > > 5 14 15 3 1 20 30 28 18 27 32 45 42 43 41 49 54 50 56 47 68 66 64 73 71 > > > [Answer] ## Ruby 1.9, 48 characters ``` $><<(0..4).map{|i|[*1..75][15*i,15].sample 5}*?, ``` [Answer] ## Windows PowerShell, 51 ~~54~~ I'm not sure whether I understood your task correctly, though. ``` (0..4|%{($x=15*$_+1)..($x+14)|random -c 5})-join',' ``` Sample outputs: ``` 5,9,1,7,13,26,18,23,17,22,37,33,34,41,44,50,53,59,60,58,73,72,64,69,66 14,10,13,5,1,24,29,26,17,30,34,33,43,41,38,59,50,60,49,56,71,61,72,70,68 3,11,4,5,13,27,16,25,26,22,43,34,42,32,38,51,52,49,58,54,61,70,73,71,62 1,9,13,12,4,23,25,20,26,22,40,33,35,44,37,55,47,52,59,53,74,70,75,64,69 8,6,7,1,9,16,21,23,18,17,35,41,37,38,34,60,50,57,51,59,66,75,73,74,71 11,6,13,4,1,29,27,24,22,18,40,35,41,32,43,51,54,57,58,53,74,71,69,66,64 ``` [Answer] **PHP 106** ``` <?$z=1;for($i=0;$i<5;$i++){for($j=0;$j<rand(1,5);$j++){$o[]=rand($z,$z+15);}$z+=15;}echo implode(",", $o); ``` I'm not sure I understood correctly the problem... Can you provide a more detailed explanation? [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` 75ɾ15ẇƛÞ℅5Ẏ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI3Ncm+MTXhuofGm8Oe4oSFNeG6jiIsIiIsIiJd) ``` 75ɾ # range(1, 75) 15ẇ # Cut into chunks of 15 ƛ # Over each Þ℅ # Shuffle 5Ẏ # Get the first five items ``` [Answer] ## Clojure - 52 chars ``` (map #(take 5(shuffle %))(partition 15(range 1 76))) ``` Example output (note that it provides the separate rows as sub-lists): ``` ((4 1 12 10 2) (25 23 21 16 27) (39 33 45 44 43) (48 53 59 54 47) (73 71 61 64 63)) ``` [Answer] # Python 2, 84 bytes ``` from random import* print sum([sample(range(1+i*15,16+i*15),5)for i in range(5)],[]) ``` If the output as list if lists is okay there is a **75 bytes** solution: ``` from random import* print[sample(range(1+i*15,16+i*15),5)for i in range(5)] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 75õ òF Ëá5 ö ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NzX1IPJGIMvhNSD2&input=LVE) (or [formatted as a Bingo card](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NzX1IPJGIMvhNSD2&footer=1WkiQklOR08irCD5MiBtuLc)) ]
[Question] [ This is an exact inverse of the question [Convert to Spoken Binary](https://codegolf.stackexchange.com/questions/268685/convert-to-spoken-binary). This introduction is copied from there. > > # Introduction > > > In the video [the best way to count](https://www.youtube.com/watch?v=rDDaEVcwIJM), binary is proposed as the > best system of counting numbers. Along with this argument is a > proposal on how to say numbers in this system. First, we give names to > each "double power of two", \$2^{2^n}\$ for each \$n\$. > > > > ``` > number = symbol = spoken > ============================ > 2^0 = 1 = "one" > 2^1 = 2 = "two" > 2^2 = 4 = "four" > 2^4 = H = "hex" > 2^8 = B = "byte" > 2^16 = S = "short" > 2^32 = I = "int" > 2^64 = L = "long" > 2^128 = O = "overlong" > 2^256 = P = "byteplex" > > ``` > > Then, to get from [a number to its spoken binary](https://youtu.be/rDDaEVcwIJM?si=ZFzrA-zpjOc1OAXY&t=3587), we > > > 1. Take its (big-endian) bit string and break off bits from the end equal to the number of zeros in the largest double power of two less > than or equal to the number. > 2. Use the name for the corresponding double power of two in the middle, and recursively name the left and right parts through the same > procedure. If the left part is one, it is not spoken, and if the right > part is zero, it is not spoken. > > > This system is similar to how we normally read numbers: 2004 -> 2 "thousand" 004 -> "two thousand four". > > > You can find examples of this procedure in the linked question. To [parse a number in spoken binary](https://youtu.be/rDDaEVcwIJM?si=D5Ir7c9SncGkWS7h&t=3597), do the opposite of the above, i.e. 1. Find the largest double power of two in the spoken binary (it is unique). 2. Recursively parse the sections to the left and the right through the same procedure (assuming one on left and zero on right if either are empty), and compute left \* middle + right. This system is similar to how we normally parse numbers: "two thousand four" -> 2 \* 1000 + 4 -> 2004. As an example, ``` "2H214" "2" * 16 + "214" 2 * 16 + "21" * 4 + 0 2 * 16 + (2 + 1) * 4 + 0 44 ``` # Challenge Your program must take a string of symbols for the spoken binary of a positive integer \$n\$ as input and output the integer it represents in decimal. While numbers under \$2^{512}\$ are expressible in this system, you only need to handle integers **up to and including** \$2^{32}\$ = `I`, and as such, do not need to consider `L`, `O`, or `P`. You only need to consider valid spoken binary strings; you do not need to handle cases like `HH`, `1H`, `H44`, `4121S` etc. Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins. # Example Input and Output ``` 1 -> 1 2 -> 2 21 -> 3 4 -> 4 41 -> 5 42 -> 6 421 -> 7 24 -> 8 241 -> 9 242 -> 10 2421 -> 11 214 -> 12 H241 -> 25 2H214 -> 44 42H4 -> 100 21B2142H24 -> 1000 21421H21421B21421H21421S21421H21421B21421H21421 -> 4294967295 I -> 4294967296 ``` If you need any more test cases, the answers to the linked question can help. [Here](https://tio.run/##AT8AwP9qZWxsef//QlXhuJ/igqww4oCcMjRIQlNJ4oCdczJqxZNyMcmX4bqO4biK4biiJD/igqzJl8aSVf///zEwMDA) is one TIO (Credit to @Nick Kennedy). [Answer] # Ruby, ~~91~~ 88 bytes ``` ->(s){s.each_char.reduce(0){|x,a|v=2**(2**("124HBSI".index a)/2);x%v>0?x+x%v*(v-1):x+v}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf106jWLO6WC81MTkjPjkjsUivKDWlNDlVw0CzuqZCJ7GmzNZIS0sDhJUMjUw8nII9lfQy81JSKxQSNfWNNK0rVMvsDOwrtIG0lkaZrqGmVYV2WW3t/4KizLwShbRoJSNDJyNDEyMPIxOl2P8A) I'm only posting this one because I didn't see one remainder based approach. Basically, for each digit, we decide if we're adding it as it is, or using it as a multiplier. If we've seen something smaller than the current digit, then whatever is smaller should be multiplied, else we just add the digit. Thanks @Neil for -3 bytes! [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~78~~ 76 bytes ``` f=(x,i=6,z)=>i--?x.split('24HBSI'[i]).map(s=>z=(z|z<1)*2**2**i+f(s,i))&&z:+x ``` [Try it online!](https://tio.run/##dVBNb4IwGL73V/SkrRSk7wqOZWWJJzx7NGYSBqYLChGzANl/Z@2rS9xhSdPns8@hn/lX3hUX0179c/NRTlOlWS@MjsXIdWp8/60PurY2VzYHla23m/nO7HlwylvW6XTUbPweXyVfwMId41WsE4bz2Wx88fqpaM5dU5dB3RzZgUjqp1QScAAEUD4R5UARhTIiCuPYIhorAlh4tohGYglWZOjYbVNSavewKIFakd3bEDkF2T1UykkF2a0ahvhubVNb@fVC3AKZ4b1@4Nt/fJyGRCXxCpKIbP7omByCS9nWeVGyJQs87lKHy9NRUPYuejHYr95VrOdaD8KhGPacTz8 "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ⊞υ⮌SFISBH42≔ΣEυ…⊞OE⪪κι∨μIν0²υI⍘⮌υ² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY67CsIwFIZ3nyJkOoEWNHQQnGyXOohiRnGIJW2DtQm5CD6Li4OiOPo2vo1prcvhwP_9l8uzqLkpFG-u17t3ZTz9vNfe1uAjtBEnYayARau9Y87ItgJCyGxUKoMAL1iaJxQTNLdWVi0wf4Ql150zOxeNyGqloctaaWG4U6ZXmW6kg0OEJInQysAx0Nw6aENyhPAYh0v734emdSh10AMpt2IY8R_mB3Z2s_vCDvsfWxyfGrx70UlKJwnNafITvg "Charcoal – Attempt This Online") Link is to verbose version of code. Will produce values up to `18446744073709551615`. Explanation: ``` ⊞υ⮌S ``` Start with the reverse of the input in a single piece. ``` FISBH42 ``` Work down from the highest double power of two to the lowest. ``` ≔ΣEυ…⊞OE⪪κι∨μIν0²υ ``` Split each piece into two, defaulting the first piece to `0` and the second piece to `1`, but if the split only resulted in one piece then pad it with a `0` piece. Examples: `2` splits on `2` to give two empty strings, so the first becomes `0` and the second `1`, representing `10` in binary; `21` splits on `2` to give `1` and an empty string, the latter becoming `1`, representing `11` in binary; `1` splits on `2` to give `1`, which is padded with a `0`, representing `01` in binary. ``` I⍘⮌υ² ``` The reversed list is now a list of binary digits so convert it to decimal. A port of @Pufe's Ruby answer is also 34 bytes: ``` ≔⁰θFESX²÷X²⌕124HBSIι²≧⁺∨×﹪θι⊖ιιθIθ ``` [Try it online!](https://tio.run/##PY5BCoMwFAX3PcWnqx9IoQZ3rmql6EIqtRcIJtVATDSJ9vipttC3HJjhdQN3neU6xov3qjd4pjCT7PCyDrDmE1ZmWkIbnDI9EgqNfUuHjEJlQqFWJST@0U0ZgceEpWXeVkcKimwCI9tgK/36D9UPARu9eAp3h081So@1FYu2OO8KhUJ2To7SBCnwm9jh/qnZTgS8ch9wJiSLkSU5S1JWsjSeVv0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰θ ``` Start with zero. ``` FESX²÷X²⌕124HBSIι² ``` Map the characters of the input string to the double powers of `2` and loop over the results. ``` ≧⁺∨×﹪θι⊖ιιθ ``` Add on the current value modulo the current power multiplied by one less than the current power, unless that is `0`, in which case just add on the current value. ``` Iθ ``` Output the final result. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~127~~ 125 bytes ``` 21 3 (?<!\d)[4H]|(?<![\dH])B|^S 1$& I 1SS S BB (\d)4(\d?) $.($1*4*_$2* (\d+)H(\d*) $.($1*16*_$2* +`(\d+)B(\d*) $.($1*256*_$2* ``` [Try it online!](https://tio.run/##dYy9jsJADIT7eQpOilA20QE2TiDSCaRtbqm3JOFHgoKGAiFdw7vnvA5IXHGNx/5mPLfz/XI9Uj/N118fE9f@lNN9/n3omTBHYu3JbSV0j7Rv21PonH/sIigbYwOKERHeI9eY6Fg7ZJM8o0KKfcZF4qULOouXQfXglAfz/LvH1WD2PY0@VyMCJ2GwnXNIEoHYWUHMrlUNLMAWWKoaaHSxCM3SNnRqKVmMGOEZ5Aocnli0n8OQmOkfeTXUfZGEtCvY9G97/IdbKTfS1AtuKmz@3PUv "Retina – Try It Online") Link is to test suite that converts the first number on each line. Explanation: ``` 21 3 ``` `2` always has an implicit `1` preceding it. If it also has a `1` following it, that's then `3`. ``` (?<!\d)[4H]|(?<![\dH])B|^S 1$& ``` Put in explicit `1`s in places that need them. ``` I 1SS ``` Special-case `I` as we only need to support a lone `I`. (Although this will actually work for numbers up to but not including `IS`.) ``` S BB ``` Change `S` to `BB` as we can multiply by `256` twice without ambiguity. (See below.) ``` (\d)4(\d?) $.($1*4*_$2* ``` For each `4`, multiply the digit before by `4` and add any digit after. Conveniently after this stage all the decimal digits are now part of the computation rather than the input. ``` (\d+)H(\d*) $.($1*16*_$2* ``` For each `H`, multiply the number before by `16` and add any number after. ``` +`(\d+)B(\d*) $.($1*256*_$2* ``` For each `B`, multiply the number before by `256` and add any number after. Examples for multiple `B`s: * `S1` ⇒ `1BB1` ⇒ `256B1` ⇒ `65537` * `SB1` ⇒ `1BB1B1` ⇒ `256B257` ⇒ `65793` * `BSB1` ⇒ `1BBB1B1` ⇒ `256BB257` ⇒ `65536B257` ⇒ `16777473` * `B1SB1` ⇒ `1B1BB1B1` ⇒ `257BB257` ⇒ `65792B257` ⇒ `16843009`. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~57 55~~47 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⍵≡⍬:0⋄⍵(∇⍤↓+⌷×1⌈∘∇¯1↓↑)⍨⊃⍒⍵}2*∘⌊2*6-'ISBH42'∘⍳ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VR58JHvWusDB51twB5Go862h/1LnnUNln7Uc/2w9MNH/V0POqYARQ9tN4QKPqobaLmo94Vj7qaH/VOAqqvNdICSfd0GWmZ6ap7Bjt5mBipg0R6NwMA&f=S1M3MfIwMjRxAmIQbRQMIgxhXEN1rjR1sIgHXBzGDsYhrg4A&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f) -8 bytes thanks to att. ## Explanation ``` {⍵≡⍬:0⋄⍵(∇⍤↓+⌷×1⌈∘∇¯1↓↑)⍨⊃⍒⍵}2*∘⌊2*6-'ISBH42'∘⍳­⁡​‎⁠⁠⁠⁠⁠⁠⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣⁡​‎⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁤⁣​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁤⁤​‎‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁡⁡​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢⁡⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁡⁣​‎‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁡⁤​‎‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ 'ISBH42'∘⍳ ⍝ ‎⁡‎⁡indices of input in 'ISBH42' 6- ⍝ ‎⁢subtract from 6 2* ⍝ ‎⁣2 to that power 2*∘⌊ ⍝ ‎⁤2 to floor of that 2*∘⌊2*6-'ISBH42'∘⍳ ⍝ ‎⁢⁡converts the symbols to numbers ⍵≡⍬: ⍝ ‎⁢⁢‎⁢⁣if passed empty vector: 0 ⍝ ‎⁢⁣return 0 ⋄ ⍝ ‎⁢⁤else: ⍒⍵ ⍝ ‎⁣⁡indices to sort descending ⊃ ⍝ ‎⁣⁢first ⊃⍒⍵ ⍝ ‎⁣⁣index of maximum ⍵ ⍝ ‎⁣⁤input vector ( )⍨ ⍝ ‎⁤⁡reverse the left and right arguments ↑ ⍝ ‎⁤⁢take vector up to the max value ¯1↓ ⍝ ‎⁤⁣drop the last element ∇ ⍝ ‎⁤⁤apply this dfn 1⌈∘ ⍝ ‎⁢⁡⁡max with 1 ⌷× ⍝ ‎⁢⁡⁢times the max value (via indexing) + ⍝ ‎⁢⁡⁣plus ↓ ⍝ ‎⁢⁡⁤drop vector up to and including max value ∇⍤ ⍝ ‎⁢⁢⁡apply this dfn 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).­ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` W“ISBH42”ṣȯ"JŻƊṫ-ʋ€Ẏ¥ƒFOḂḄ ``` * [Try it online!](https://tio.run/##AUQAu/9qZWxsef//V@KAnElTQkg0MuKAneG5o8ivIkrFu8aK4bmrLcqL4oKs4bqOwqXGkkZP4biC4biE////MjFCMjE0MkgyNA "Jelly – Try It Online") * [Test suite](https://tio.run/##y0rNyan87xT6cMf8R01rDB41zDEy8XAK9nzUMLfYKOvo5CLDk9Mf7up7uKPr4Y5FKvZANSenH5sU@j8cqNIz2MnDxAio8uHOxSfWK3kd3X2s6@HO1bqnuoHKgJoOLT02yc3/4Y6mhzta/hse2e@mc7hdxdohC6hVQddOAaiR63A7UGnk//@GOgpGOgrGOgomOgqmOgpmOgrmOgoWOgqWOgqGBkAMlDcEKjAEqjAEKjEEqjEEKjIEqjICsk1AYgYGYAJImhhZmliamRtZmiKxzQA) A monadic link that is called as a monad with a spoken binary string argument and returns an integer. The test suite takes a list of integers, uses [my answer to the companion challenge](https://codegolf.stackexchange.com/a/268708/42248) to make spoken binary and then converts it back. Inspired by [@Neil’s Charcoal answer](https://codegolf.stackexchange.com/a/268762/42248) so please be sure to upvote that one too! ## Explanation ``` W“ISBH42”ṣȯ"JŻƊṫ-ʋ€Ẏ¥ƒFOḂḄ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎⁠⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁣​‎⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌­ W # ‎⁡Wrap in a list “ISBH42” ¥ƒ # ‎⁢Reduce using the wrapped spoken binary string as the starting argument and each of "ISBH42" in turn as the right argument using the following dyadic chain: ʋ€ # ‎⁣- For each list in the list of lists: ṣ # ‎⁤ - Split with the current character (from ISBH42); will return a list of either one or two pieces, either of which may be empty Ɗ # ‎⁢⁡ - Following as a monad: ȯ"J # ‎⁢⁢ - Or with the list indices (will replace empty pieces in the first and second position with 1 and 2 respectively) Ż # ‎⁢⁣ - Prepend zero ṫ- # ‎⁢⁤ - Take the last two Ẏ # ‎⁣⁡- Join outer lists F # ‎⁣⁢Flatten O # ‎⁣⁣Convert to Unicode code points (will convert "1" to 49 and leave the existing 1s and 2s alone) Ḃ # ‎⁣⁤Mod 2 Ḅ # ‎⁤⁡Unitary (convert from base 2) 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ## Original answer, Jelly, 41 bytes ``` >oḊ$k⁸ṣȯ"1,0Fæ.ʋċ¡€F “24HBSI”iⱮ’2*2*ḞṢçƒ$ ``` * [Try it online!](https://tio.run/##AVgAp/9qZWxsef//Pm/huIoka@KBuOG5o8ivIjEsMEbDpi7Ki8SLwqHigqxGCuKAnDI0SEJTSeKAnWnisa7igJkyKjIq4bie4bmiw6fGkiT///8yMUIyMTQySDI0 "Jelly – Try It Online") * [Test suite](https://tio.run/##y0rNyan87xT6cMf8R01rDB41zDEy8XAK9nzUMLfYKOvo5CLDk9Mf7up7uKPr4Y5FKvZANSenH5sU@t8uHyikkv2occfDnYtPrFcy1DFwO7xM71T3ke5DC4Gq3LiQjcp8tHHdo4aZRlpGWg93zHu4c9Hh5ccmqfw3PLLfTedwu4q1QxZQtYKunQJQLdfhdqD@yP//DXUUjHQUjHUUTHQUTHUUzHQUzHUULHQULHUUDA2AGChvCFRgCFRhCFRiCFRjCFRkCFRlBGSbgMQMDMAEkDQxsjSxNDM3sjRFYpsBAA "Jelly – Try It Online") A pair of links that is called as a monad with a spoken binary string argument and returns an integer (wrapped in a length 1 list). When called as a full program will print the integer implicitly. In brief this works like this: 1. Convert from spoken binary digits to the relevant powers of 2 (e.g. `B` -> `256`) 2. Work up through each digit in ascending order; find sublists of between 1 and 3 adjacent integers which are not greater than the relevant digit (e.g. `3, 4, 1` if the current digit is `2`). 3. Within each sublist, multiply the current digit by the prefix if there is one (or by 1 if none) and add any suffix if there is one. So for the example above, `3, 4, 1` becomes 13. 4. Continue until all of the digits have been used (and so we have a single final integer result). ]
[Question] [ This challenge is to list out all possible words which are built from a pattern of syllables. Words are composed by joining syllables together. Syllables are composed of a number of vowels with some number of consonants optionally to the left and/or right. Your code should take in: * a list of consonants * a list of vowels (the vowels and consonants may be assumed to be mutually exclusive) * a syllable structure in some format you define; the format must contain information describing: + the minimum and maximum number of left consonants ( >= 0) + the minimum and maximum number of vowels ( >= 1) + the minimum and maximum number of right consonants. ( >= 0) * A minimum and maximum number of syllables ( >= 1) Examples: ``` Consonants: tk Vowels: au Structure: (c)cv(c) (means: 1 to 2 left consonants, 1 vowel, 0 to 1 right consonants) Syllables: 1 Output: ta tat tak tu tut tuk ka kat kak ku kut kuk tta ttat ttak ttu ttut ttuk tka tkat tkak tku tkut tkuk kta ktat ktak ktu ktut ktuk kka kkat kkak kku kkut kkuk Consonants: 'b', 'c', 'd' Vowels: 'e' Structure: 1, 1, 1, 2, 0, 0 (means: 1 left consonant, 1 to 2 vowels, 0 right consonants) Syllables: 1, 2 Output: be bee ce cee de dee bebe bebee bece becee bede bedee beebe beebee beece beecee beede beedee cebe cebee cece cecee cede cedee ceebe ceebee ceece ceecee ceede ceedee debe debee dece decee dede dedee deebe deebee deece deecee deede deedee Example of using a single string as input("4|P|T|C|K|2|A|I||vvV||ss") Consonants: "4|P|T|C|K|" Vowels: "2|A|I|" Structure: "|vvV||" (means: 0 left consonants, 2 to 3 vowels, 0 right consonants) Syllables: "ss" (means: 2) Output: AAAA;AAAI;AAIA;AAII;AAAAA;AAAAI;AAAIA;AAAII;AAIAA;AAIAI;AAIIA;AAIII;AIAA;AIAI;AIIA;AIII;AIAAA;AIAAI;AIAIA;AIAII;AIIAA;AIIAI;AIIIA;AIIII;IAAA;IAAI;IAIA;IAII;IAAAA;IAAAI;IAAIA;IAAII;IAIAA;IAIAI;IAIIA;IAIII;IIAA;IIAI;IIIA;IIII;IIAAA;IIAAI;IIAIA;IIAII;IIIAA;IIIAI;IIIIA;IIIII;AAAAAA;AAAAAI;AAAAIA;AAAAII;AAAIAA;AAAIAI;AAAIIA;AAAIII;AAIAAA;AAIAAI;AAIAIA;AAIAII;AAIIAA;AAIIAI;AAIIIA;AAIIII;AIAAAA;AIAAAI;AIAAIA;AIAAII;AIAIAA;AIAIAI;AIAIIA;AIAIII;AIIAAA;AIIAAI;AIIAIA;AIIAII;AIIIAA;AIIIAI;AIIIIA;AIIIII;IAAAAA;IAAAAI;IAAAIA;IAAAII;IAAIAA;IAAIAI;IAAIIA;IAAIII;IAIAAA;IAIAAI;IAIAIA;IAIAII;IAIIAA;IAIIAI;IAIIIA;IAIIII;IIAAAA;IIAAAI;IIAAIA;IIAAII;IIAIAA;IIAIAI;IIAIIA;IIAIII;IIIAAA;IIIAAI;IIIAIA;IIIAII;IIIIAA;IIIIAI;IIIIIA;IIIIII duplication test case: Consonants: k Vowels: a Structure: cVc (means: 0 to 1 left consonants, 1 vowel, 0 to 1 right consonants) Syllables: 2 Output: kakkak kakka kakak kaka kaak kaa akkak akka akak aka aak aa (note that there is only one of each aka, kaka, akak, and kakak; you get two if you treat ak a and a ka separately) ``` Duplicate words should be removed. The order and format of the words does not matter, as long as they can be told apart (ie, don't output one long unbroken string of letters). The max and min of the left and right consonants is any non-negative integer; the max and min of the vowel and the number of syllables is any positive integer. The set of consonants will never have tokens from the set of vowels and vice versa. There will always be at least one consonant and one vowel provided in the input. You may define the format and order of the inputs. The words of the output must be built from the same characters as those entered in the input. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. To be considered valid, solutions must at least accept English vowels and consonants as valid vowels and consonants (having only upper or lower case is still valid), and must come up with a complete and correct word list for any valid input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes ``` F…·NN⊞υ×ιζFυ¿ΣιF⌊ι«≔⪪⎇‹κ3εδ¹ζF№24κ⊞ζωF⁻Eζ⭆ι⎇⁼ξ⌕ικλνυ⊞υλ»⟦ι ``` [Try it online!](https://tio.run/##VY9BT8MwDIXPy6@wenKkcOi2W08IgTRpQxPdDXHI2qyzlqYlqQcM8dtLUjEEJ/s9W9@zq6P2VaftOB46D7hyleVAZ/OkXWOi7Hl45HZvPEoF/6SUsOVwRFawo9YEJAUXKQsxgVgCHQBLbpHi5uRtyFH7Y3yK2W0I1Dgse0sD7ox32n/g2oSAJwXZIouBRkEdSy4TuhCzCXPXsRswmy8zBafrFRcFb78bMYgDbnSf7HLw5Jok4oHXmPtX1jbgu4IHcnWaRJICq8DJ1PCf72zkfgljg4FtRA34TC@yGMdczEW@WIp9VQsz3pztNw "Charcoal – Try It Online") Link is to verbose version of code. See below for input format. Explanation: ``` F…·NN ``` Input the minimum and maximum number of syllables and loop from one to the other (inclusive). ``` ⊞υ×ιζ ``` Repeat the syllable structure by the number of syllables and push the result to the predefined empty list. (In Charcoal, `Divide` splits a string, so `Multiply` joins a list with a string, rather than vectorised repeating the string.) ``` Fυ ``` Loop over the structures and words that will be generated below. ``` ¿Σι ``` If this is a structure or partial word, then: ``` F⌊ι« ``` Get a digit from the structure. ``` ≔⪪⎇‹κ3εδ¹ζ ``` Choose consonants or vowels depending on whether the digit is less than `3`. ``` F№24κ⊞ζω ``` If the digit is even then add an empty string to make the letter optional. ``` F⁻Eζ⭆ι⎇⁼ξ⌕ικλνυ⊞υλ ``` Replace the digit with each character in the list and push any new results to the predefined empty list for further processing. ``` »⟦ι ``` Otherwise, output the word. The program takes five inputs: 1. The minimum number of syllables 2. The maximum number of syllables 3. A string describing the syllable format 4. A string of consonants 5. A string of vowels. The syllable format is a string of digits from `1` to `4`, where they have the following meanings: 1. A consonant 2. An optional consonant 3. A vowel 4. An optional vowel [Answer] # [JavaScript (V8)](https://v8.dev/), 139 bytes Input format: `([[consonants], [vowels]], min_syllables, max_syllables, [[min, max], [min, max], [min, max]])` Prints all valid words. ``` (a,p,q,m)=>(g=(s,k=0,i=0,j=0)=>i<3?j<m[i][j<m[i][0]||g(s,k,i+1),1]&&a[i&1].map(c=>g(s+c,k,i,j+1)):g[++k<q&&g(s,k),s]||k<p||print(g[s]=s))`` ``` [Try it online!](https://tio.run/##ZY7RjsIgEEXf/QrDA4F0dgP1xWhxP2RCIlu1oU0NSten/nsdKq4mJgx34M490Lqbi/XVh@Hrtp5OZhIOAlygl2YnGiMidEaBp2qNojtfrX7aqkdvMYuy49ikOfCFlqAt5w491/a7d0HUZkdmUScbWhqQmwaLoqsunM8pCZEAXRXGMVz9eRANRmuilPv9dBKIbGDAOmZhicxR@8cs9XpeiLSVyUrnpCqpldvlgyUXM@KXcjXV4YE5PhFlRuiMKDNCfSL@f5CiZY6qV/T99ekO "JavaScript (V8) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 24 bytes ``` ∞¨Z$÷ṡv↔f;Π£÷ṡƛ¥ÞẊvṅǍ;fU ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLiiJ7CqFokw7fhuaF24oaUZjvOoMKjw7fhuaHGm8Klw57huop24bmFx407ZlUiLCIiLCJbXCJiXCIsIFwiZVwiXVxuW1swLCAxXSwgWzEsIDFdLCBbMCwgMV1dXG5bMSwgMl0iXQ==) Takes input as ``` [consonants, vowels] [min, max]: left-consonants, vowels, right-consonants [min-syllables, max-syllables] ``` Explanation: ``` ∞¨Z$÷ṡv↔f;Π£÷ṡƛ¥ÞẊvṅǍ;fU­⁡​‎‎⁡⁠⁡‏⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠⁠⁠⁠⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁤‏⁠⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌­ ∞ # ‎⁡Palindromise [constants, vowels] (1. input) -> [constants, vowels, constants] ¨Z ; # ‎⁢Zip that with [min, max] (2. input) and map for each item: $÷ṡ # ‎⁣- Create a range from min to max v↔f # ‎⁤- For each number n in range, push all combinations of constants/vowels with length n Π # ‎⁢⁡Cartesian product over [left-constant, vowel, right-constant]-combinations ÷ṡ # ‎⁢⁢Create range from syllables-min to syllables-max (3. input) £ ƛ¥ÞẊv ; # ‎⁢⁣For each number n in range, push cartesian product of combinations-list with itself n times vṅǍ # ‎⁢⁤Merge each sublist fU # ‎⁣⁡Flatten and remove duplicates 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Zsh](https://www.zsh.org/), ~~67~~ 65 bytes *saved **2 bytes** by moving everything into `eval`*, so no `$=shwordsplit` is needed. ``` eval "c=($1) C=('' $1) v=($2) V=('' $2) s=($3) S=('' $3) echo $4" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwao0DU2N4tQSBd2KpaUlaboWNx1TyxJzFJSSbTVUDDW5nG011NUVQKwyoICRJlcYRADIKgYKGGtyBUMEgKzU5Ix8BRUTJahBqppcXGkK6iUK2eoK6okKqUBSJS5ZJa5MJc4ZzC5WiQtWhyhesABCAwA) ~~[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwao0DU2N4tQSBd2KpaUlaboWN52TbTVUbA01uZxtNdTVFVSSNbnKQCJGmlxhEJEyTa7UssQcBaVioLixpnUwRBjISk3OyFdQMVGCGqWqycWVpqBeopCtrqCeqJAKJFXiklXiylTinMHsYpW4YHWI4gULIDQA)~~ ~~Ab~~uses flexible structure format to take input of the form `$^c$^C$^v$^V$^c`/`$^s$^S`, which when `eval`'d does cross product concatenations of the list elements. `echo` is needed because `<<<` does not permit expansions which result in lists. The ATO link enables tracing in the function for your convenience. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~114 ...~~ 82 bytes ``` ->c,v,*s{[*?a..?z*s[7]*s.sum].grep /^(#{[k=?[+c+?],?[+v+?],k,?),?$]*"{%d,%d}"%s}/} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Zp0xHq7g6Wss@UU/PvkqrONo8VqtYr7g0N1YvvSi1QEE/TkO5Ojrb1j5aO1nbPlYHSJeB6Gwde00de5VYLaVq1RQd1ZRaJdXiWv3a/@m2OAw1Ic9ArgKF9Gj1kmx1HfXEUnUdQx0jIDbUMQCThrFc/wE "Ruby – Try It Online") Works only in theory, takes forever to complete. TIO link contains a hardcoded speedup version. [Answer] # Excel, ~~324~~ 312 bytes `z` defined within Name Manager as: ``` =LAMBDA(a,b,c,d,e, IF( OR(d,e), IF( c=e, IF(d,a,VSTACK(a,"")), LET( f,VSTACK( a, z(TOCOL(a&"|"&TOROW(b)),b,c+1,d,e) ), FILTER(f,1+LEN(f)-LEN(SUBSTITUTE(f,"|",""))>=d) ) ), "" ) ) ``` `(162 bytes)` Within the worksheet: ``` =LET( g,A1#, h,"|", i,SUBSTITUTE( TOCOL( TOROW( z(g,g,1,C1,C2)&h&TOROW(z(B1#,B1#,1,E1,E2)) )&h&z(g,g,1,D1,D2) ), h, "" ), UNIQUE(SUBSTITUTE(z(i,i,1,F1,F2),h,"")) ) ``` `(150 bytes)` * Consonant and vowel lists are spilled, vertical ranges `A1#` and `B1#` respectively. * Left consonant min and max in `C1` and `C2` respectively. * Right consonant min and max in `D1` and `D2` respectively. * Vowel min and max in `E1` and `E2` respectively. * Syllable min and max in `F1` and `F2` respectively. [Answer] # PHP, 401 bytes (surely I can do better than that!?!) a recursive generator parameters: * consonants (array) * vowels (array) * structure (array): V for vowels, C for consonants; lower case for optional and upper case for mandatory * minimum number of syllables (int) * maximum number of syllables (int) usage: `foreach(f($c,$v,$s,$min,$max)as$w)echo "$w ";` ``` function c($a){if($a){if($u=array_pop($a))foreach(c($a)as$p)foreach($u as$v)yield$p+[count($p)=>$v];}else yield[];}function f($c,$v,$s,$y,$x,$r=NULL){static$z;is_null($r)&&$z=[];$x--;$y&&$y--;foreach(c(array_map(function($h)use($c,$v){return${strtolower($h)}+($h>'Z'?[-1=>'']:[]);},$s))as$b){$w=$r.implode($b);$y||!$w||in_array($w,$z)||yield$w;$z[]=$w;if($x)foreach(f($c,$v,$s,$y,$x,$w)as$w)yield$w;}} ``` [Try it online](https://onlinephp.io/c/17c48) ## breakdown: (my cartesian generator is explained at <https://stackoverflow.com/a/39174062/6442316>) ``` // function to build cartesian product function c($a){if($a){if($u=array_pop($a))foreach(c($a)as$p) foreach($u as$v)yield$p+[count($p)=>$v];}else yield[];} // function f builds one syllable, then recurses function f($c,$v,$s,$y,$x,$r=NULL) /* $c: array consonants $v: array vowels $s: array syllable structure $y: int syllables min $x: int syllables max for recursions: $r:string word so far the first three parameters should be string, but with arrays I can spare two str_split calls */ { static$z; is_null($r)&&$z=[]; // if new call, empty yielded words $x--;$y&&$y--; // decrease (remaining) syllable counts // loop through cartesian product of possible syllables: foreach(c( // create cartesian product over ... array_map(function($h)use($c,$v){ // map structure array -> possible letters return${strtolower($h)} # $$c or $$v +($h>'Z'?[-1=>'']:[]); # if $h is lower case, add empty char },$s)) as$b) { { $w=$r.implode($b); // add syllable $y // if minimum syllables are reached || !$w // and the word is not empty || in_array($w,$z) // and it has not been yielded || yield$w; // yield word $z[]=$w; // add word to "already yielded" if($x) // if maximum syllables are not reached ... foreach(f($c,$v,$s,$y,$x,$w)as$w)yield$w; // ... recurse } } ``` ]
[Question] [ #### Background From [Wikipedia](http://en.wikipedia.org/wiki/Egyptian_fraction): An Egyptian fraction is the sum of distinct unit fractions. That is, each fraction in the expression has a numerator equal to 1 and a denominator that is a positive integer, and all the denominators differ from each other. The value of an expression of this type is a positive rational number a/b. Every positive rational number can be represented by an Egyptian fraction. #### Task Write a function that given \$ n \$, outputs the longest sequence of Egyptian fractions (that sum up to 1) where \$ n \$ is the largest denominator. #### Rules * If no solution exists, you may output anything or nothing except any real number * If there are two or more solutions, output any one of them * Assume \$ n \$ is not two and is a natural number * Your output must be in descending order * You must not output duplicates * Each individual fraction must be separated by a plus symbol (`+`). Spaces are optional. However the plus symbol should not come after the last fraction. * Your code does not need to practically handle very high \$ n \$, but it must work in theory for all \$ n \$ for which a solution exists * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden #### Examples `6` ⟶ `1/2 + 1/3 + 1/6` `15` ⟶ `1/3 + 1/4 + 1/6 + 1/10 + 1/12 + 1/15` `20`: ``` 1/4 + 1/5 + 1/6 + 1/9 + 1/10 + 1/15 + 1/18 + 1/20 ``` or ``` 1/3 + 1/5 + 1/9 + 1/10 + 1/12 + 1/15 + 1/18 + 1/20 ``` `2016`: ``` 1/15 + 1/22 + 1/24 + 1/25 + 1/30 + 1/32 + 1/33 + 1/39 + 1/40 + 1/42 + 1/44 + 1/45 + 1/48 + 1/55 + 1/56 + 1/60 + 1/63 + 1/64 + 1/65 + 1/66 + 1/70 + 1/72 + 1/78 + 1/80 + 1/84 + 1/85 + 1/88 + 1/90 + 1/91 + 1/96 + 1/99 + 1/104 + 1/110 + 1/112 + 1/119 + 1/120 + 1/130 + 1/132 + 1/135 + 1/136 + 1/150 + 1/154 + 1/156 + 1/160 + 1/165 + 1/168 + 1/170 + 1/171 + 1/175 + 1/180 + 1/182 + 1/184 + 1/189 + 1/190 + 1/195 + 1/198 + 1/200 + 1/208 + 1/210 + 1/220 + 1/225 + 1/230 + 1/238 + 1/240 + 1/260 + 1/270 + 1/272 + 1/275 + 1/288 + 1/299 + 1/300 + 1/306 + 1/320 + 1/324 + 1/325 + 1/330 + 1/340 + 1/345 + 1/368 + 1/400 + 1/405 + 1/434 + 1/459 + 1/465 + 1/468 + 1/476 + 1/480 + 1/495 + 1/496 + 1/527 + 1/575 + 1/583 + 1/672 + 1/765 + 1/784 + 1/795 + 1/810 + 1/840 + 1/875 + 1/888 + 1/900 + 1/918 + 1/920 + 1/975 + 1/980 + 1/990 + 1/1000 + 1/1012 + 1/1050 + 1/1088 + 1/1092 + 1/1100 + 1/1104 + 1/1113 + 1/1125 + 1/1196 + 1/1200 + 1/1224 + 1/1258 + 1/1309 + 1/1330 + 1/1386 + 1/1395 + 1/1425 + 1/1440 + 1/1470 + 1/1480 + 1/1484 + 1/1488 + 1/1512 + 1/1620 + 1/1650 + 1/1680 + 1/1728 + 1/1729 + 1/1800 + 1/1824 + 1/1836 + 1/1840 + 1/1848 + 1/1850 + 1/1870 + 1/1890 + 1/1950 + 1/1980 + 1/1995 + 1/2000 + 1/2016 ``` or ``` ... ``` #### Criteria 1. For first place: shortest code in bits wins 2. For second place: fastest code wins. So if a code is the shortest and fastest, the second fastest code will be given 2nd place P.S: The background definition and some rules are taken from [this](https://codegolf.stackexchange.com/q/6215) and [this](https://codegolf.stackexchange.com/q/241222) question respectively. [Answer] # JavaScript (ES6), 103 bytes, \$O(2^n)\$ Returns an empty string if there's no solution. ``` f=(n,a=o=[],p=0,q=1)=>n?f(n-1,["1/"+n,...a],p*n+q,q*n,p&&f(n-1,a,p,q))&&o.join`+`:o=p-q|o[a.length]?o:a ``` [Try it online!](https://tio.run/##ZcpBDoIwEEDRvcdg0XRgqNREFyQjByEkNAgIaWZaIa68ezVxZdy@/1f3dNvwWMJestzGlCbSjI6E2g4DVRjJAl25mTSXFtvMHrOC0RjjPj3nImLMGYNS38FhwAiglJhVFu6LvhYKZXxJ64wfed7vXSO1S4PwJn40XmY96QvA4Vfs@Y9OFUB6Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes, *O(2ⁿ)* ``` Nθ≔ΦE…X²⊖θX²θ⊕⌕A⮌⍘ι²1⁼ΠιΣ÷Πιιυ¿υ⪫⁺1/I§υ⌕EυLι⌈EυLι+ ``` [Try it online!](https://tio.run/##ZU/LTsNADLzzFaucvGJRlUqcegqUSqkoitovWLImtbRx2n2E/n1wggRCnOzxeMbj9mxDO1g/TTVfcnrL/TsGuOrNXRUjdQw78kkmB3uBo@UOoRk@Ba@N2mIbsEdO6ESgjfphFlTzL70jdpX3cMQRQ0R4shFPKRB3QEat5/WiLPRcX67Z@ghNGFxuE5CMTrmHmtOWRnL4hyG9aLLEpQ8FWatGTBPsB2JofI5QlKvCqGcbE1SpZoc3yEbNeZaXpH9F7tJZ7MToYG/Uy7V/lP4@VNxLyM00lY/Tw@i/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔ΦE…X²⊖θX²θ⊕⌕A⮌⍘ι²1⁼ΠιΣ÷Πιιυ ``` Get the powerset of `[1..n-1]` and see which sets' reciprocals sum to `1` when `1/n` is included. ``` ¿υ⪫⁺1/I§υ⌕EυLι⌈EυLι+ ``` If any were found then output the longest. 53 bytes for a version that is twice as fast because it gets the powerset of `[2..n-1]`: ``` Nθ≔ΦE⊗…X²⁻θ²X²⊖θ⊕⌕A⮌⍘ι²1⁼ΠιΣ÷Πιιυ¿υ⪫⁺1/I§υ⌕EυLι⌈EυLι+ ``` [Try it online!](https://tio.run/##ZY/bSsNAEIbvfYolV7MYkRS86lU0FiJGQvsE22SaDmxmmz3Evn2ctqKId8P3M/@hOxrfOWOXpeZTih9p3KOHSa/vyhBoYNiQjUIac4LKpb3FHraGB4TWfQpf5aohTgGmXK20ztUPrrDzOCJH@Zi0vmg1/6INcV9aC1uc0QeEZxNwFz3xAPRtlRXZ9e11SsYGaL3rUxeBBO3SCDXHimbq8Y9Ct6gkC@igIGnVimmEN0cMrZWmWfGY5erFhAhlrLnHM6RcXfpcV8r9jjzEo9iJUWPONEraP0nfgrJ7KbleluJpeZjtFw "Charcoal – Try It Online") Link is to verbose version of code. ~~71~~ 66 bytes for an algorithm that is slightly faster because it stops considering fractions once the sum exceeds `1` (I don't know how this affects the time complexity though): ``` Nθ≔⟦⟦θ⟧⟧ηF…²θF⮌η«≔⁺κ⟦ι⟧κ≔⁻Σ÷ΠκκΠκζ¿‹ζ⁰⊞ηκ¿∧¬ζ›LκLυ≔⊞OΦκμθυ»⪫⁺1/Iυ+ ``` [Try it online!](https://tio.run/##RY9PT8MwDMXP9FNYPTkiCIbEaacJBBoao4Jj1UNpvSZqm6z508MQn724oxMXK372@8WvUqWrbNlN09YcY9jH/oscDmKdbLzXjcE8H4pCgmLlYB3gR2kawnsJgxDwp9BIzhMqFr6Tq8WXddFjKyHXhZDQsv0yedOGR5@xx60JT3rUNWHmbB2rgO15l8u/wM1pdusD4I68x5OEO/4qi16hWtDUeYJ5Y2Nq3NuAJ7a9OCoDp9mRaYI6s5dnFAy4HMqc9yO5MliHz7qbHXx3L@aIEiLjf5LMaRPw1eolWLq6TSU8lj7MLAnpdSrEeppWD9PN2P0C "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ≔⟦⟦θ⟧⟧η ``` Input `n` and start with `1/n` as a required fraction. ``` F…²θF⮌η« ``` For each integer from `2` to `n-1`, loop over all of the sets so far. ``` ≔⁺κ⟦ι⟧κ≔⁻Σ÷ΠκκΠκζ ``` Create a new set containing the current integer and calculate the excess of the sum of reciprocals. ``` ¿‹ζ⁰⊞ηκ ``` If the excess is negative i.e. the sum is less than `1` then add this to the list of sets to check next iteration. ``` ¿∧¬ζ›LκLυ≔⊞OΦκμθυ ``` If the excess is zero i.e. the sum is `1` and this set is longer than any previously found set then set this as the longest found set so far. ``` »⪫⁺1/Iυ+ ``` Output the longest set found. [Answer] # Python3, 246 bytes: ``` def f(n): q,t=[([*range(2,n)],[],1-(1/n))],[] while q: d,c,r=q.pop(0) if[]==d:continue if round(r,5)==0:t+=[c];continue if(U:=r-(1/d[0]))>=0:q+=[(d[1:],c+[d[0]],U)] q+=[(d[1:],c,r)] return'+'.join(f'1/{i}'for i in max(t,key=len)+[n]) ``` [Try it online!](https://tio.run/##VY3BTsMwEETv@QrfskuWNikqQkHmL3qyfKhimxrK2lk5ggrx7SGphFRuM2@eNPlSTokfnrLMs/NBBWDsKzVS0QbMnRz51cOOGC0ZS909dFvGa6nU5ymevRoXXTkaSPS4ySlDiwuIwVitXT8kLpEnf0VK0sQOhPaodduXRpvBPv9T4NBrWV@caS3iy6KNiwbOdL2loTErt3TA5V/dLiQrEl8m4bqpN28pMoS6237HnzokUVFFVh/HLyj07i/67BkbwxbnLJELBHhErP5yt78puxZx/gU) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 89 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 11.125 bytes ``` ṗ't?=;Ė'∑1=;t\+j ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJSPSIsIiIsIuG5lyd0Pz07xJYn4oiRMT07dFxcK2oiLCIiLCIzIl0=) +~3 bytes due to reading the specs Me when when fraction type automatically. Powerset is sorted by length by default, so the last item is guaranteed to be the longest. [Answer] # Excel, 168 bytes, \$O(2^n)\$ ``` =LET( a,SEQUENCE(,A1), b,IF(MOD(INT(SEQUENCE(2^A1,,0)/2^(a-1)),2),1/a,), IFERROR(TEXTJOIN("+",, "1/"&TOCOL(1/TAKE(FILTER(b,TAKE(b,,-1)*(MMULT(b,TOCOL(a^0))=1)),-1),2)) ,"") ) ``` Input in cell `A1`. [Answer] # [Scala](http://www.scala-lang.org/), 345 bytes Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/265633/110802) in Scala. Golfed version. [Try it online!](https://tio.run/##ZVFNSwMxEL3vrxiKh4SuaVfQw5YUlCoKCn7QU5GSbtIazSbd7KxaZX97nW1BRXNIyHtvMu9N6kI5tbXlOkSEuruIIjhnCrTBi7JBtXBG3DWmMUkSFs9EwI2yHj6TBF6Vg2UOVx7l@AGj9SuQWy/Hn68qQiV3VYwdAQbwhxkd17bGtNtmVPPIeJodZmI48JyPuhKUO@5bQIrk7ck6wyrhgz8v17jh9LhjOi3SyGUltKm6LiO7ZPqXhq5ndjUxhS1JHbmoDT5QOsOO0x9C3IfGa7J9E7QRl6fXF/PpLRcYJqGh2FIOOcoizzHpkjYy7txq8WSU7jo2Y1JUfcmoNyrr0j2V50XaUKTfTGeXt@2IoSjV@9mGzUVtPwyHvO/JHU3faGLWzMpx3csGB7bHRfmynyrr9Xu83QJos4SSps9UXNU5nMaoNrO95pHnMPUWQdLXAK01oeg8W7ITzv8g2fE/6Gi4g9qk3X4B) ``` n=>{var q=Queue((2 to n-1 toList,List[Int](),1-1.0/n));var t=List[List[Int]]() while(q.nonEmpty){val(d,c,r)=q.dequeue;if(d.nonEmpty){if(BigDecimal(r).setScale(5,BigDecimal.RoundingMode.HALF_UP).toDouble==0)t=c::t val u=r-1.0/d.head;if(u>=0)q+=((d.tail,d.head::c,u));q+=((d.tail,c,r))}};(t.maxBy(_.size) :+n).sorted.map(i=>s"1/$i").mkString("+")} ``` Ungolfed version. [Try it online!](https://tio.run/##dZJRa9swFIXf/SsOYQ8ScZWk0D0YUmjpxgYtbCt9CqGo9k2iTZYT@XptGPntmWQ7SdfRJ9u63zn36vjWubZ6vzfluvKMOn6pvLKWcjaVU2XD@smS@t5QQ0lSPf0MBdxp4/AnAQpaYCFchq@OZYZ79sYtMW1rwG/tscnQamfi1tQ8C9w8xavXm6oJ/nIeRC0nWk557ZYkzlM42eEiPCc4g5io8chJKY8dOOv8jqbRq5O0zPPKWILYKFe5T@Wat7IfL8otRJEiT@FlUG1UQZt2CtkTZhEAZeo3QmA0irUCpgbFWjCpHBvXEJ4Nr8ArgqMXhmHyOmbZS3cgW1NrfG2WN5SbUlvhpaqJ70P8JC5SnCrqR9W4IqR6VxWkvlzdfn58@CYVV11wmE4xfj0Xh2vkyDLwv/1ORLx0Eyh/SLNQK9KFPAJxtAaXb4yBDYZTiBAHa2NTdLLYKsTXyJN@l7yjaGM@cB21Sw4jlfol/rQwGKvwfr0Vj8qSW/JKIhuii6@HVB2WlYrArYXB9BL1YDL6YAZSlb@6HRSD4SB22iX9lpZhZYX2yzrDlfd6O@u4edjaB2f4uLPrcMrWiYX42I96Oplc/Hd0PpZdm91@/xc) ``` import scala.collection.mutable.Queue object Main { def f(n: Int): String = { var q: Queue[(List[Int], List[Int], Double)] = Queue((List.range(2, n), List(), 1 - (1.0/n))) var t: List[List[Int]] = List() while (q.nonEmpty) { val (d, c, r) = q.dequeue() if (d.isEmpty) { // if d is empty, continue with the next iteration } else if (BigDecimal(r).setScale(5, BigDecimal.RoundingMode.HALF_UP).toDouble == 0) { t = c :: t } else { val u = r - (1.0/d.head) if (u >= 0) { q += ((d.tail, d.head :: c, u)) } q += ((d.tail, c, r)) } } val maxList = t.maxBy(_.length) :+ n maxList.sorted.map(i => s"1/$i").mkString("+") } def main(args: Array[String]): Unit = { println(f(6)) println(f(15)) println(f(20)) } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LæʒIå}DzOT.òÏéθ„1/ì'+ý ``` Will output nothing if there are no results. There is a bug in the filter builtin `ʒ` for decimals `1.0` (which should be 05AB1E-truthy). So the second filter `ʒ...Θ}` has been replaced with `D...Ï` for -1 byte, without changing its functionality. [Try it online](https://tio.run/##AS0A0v9vc2FiaWX//0zDpsqSScOlfUR6T1Quw7LDj8OpzrjigJ4xL8OsJyvDvf//MTU) or [verify test cases until it times out](https://tio.run/##ATwAw/9vc2FiaWX/W04@RMKpPyIg4oaSICI//0zDpsqSwq7DpX1Eek9ULsOyw4/Dqc644oCeMS/DrCcrw73/LP8). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] æ # Get the powerset of this list ʒ } # Filter this list of lists by: Iå # It contains the input-integer D Ï # Filter it further by: z # Take 1/v for each value `v` in the list O # Sum them together T.ò # Round it to 10 decimal digits to account for floating point inaccuracies # (only 1 is truthy in 05AB1E) é # After the filters: sort the remaining list by length (shortest to longest) θ # Pop and push the last/longest valid list „1/ì # Prepend "1/" in front of each integer '+ý '# And join these strings with "+"-delimiter # (after which the resulting string is output implicitly as result) ``` ]
[Question] [ *Inspired by [Is this Flow Free puzzle trivial?](https://codegolf.stackexchange.com/questions/235848/is-this-flow-free-puzzle-trivial) by [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). Lengthy chunks of this challenge are borrowed from there. This may be one step of a solution for the linked challenge, depending on chosen strategy.* ## Challenge Given an array of digits `1-9` and a padding character of your choice, output the border of the shape made by the digits (in any direction, with any starting point). ### Example Here, the padding character is `0`. ``` Input Border Output (one of possible) 00111 00### 111334442222211133 13333 ###3# 13243 #32## 13240 #32#0 23240 #3##0 22200 ###00 ``` ## Rules The input can be taken as a single string/array or a list of lines. You may also take the dimensions of the array as input. The input shape will be guaranteed to be at least 2 cells thick (so no overlapping borders) and will be interconnected (so one continuous border). You may assume only the digits 1-9 are used and choose the padding character to be either `0` or any consistent non-digit one. You may omit the trailing padding in the input and assume the array will have minimal dimensions to fit the shape (so no column or row full of `0` will be provided). Output the string/list in any convenient manner. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code per language wins! ## Test cases Here, the padding character is `0`. Outputs here start at the leftmost cell of first row, but rotations and reflections of that vector are fine. ``` 00111 13333 13243 13240 23240 22200 Output: 111334442222211133 11111 13331 12221 Output: 111111122211 00110 33333 32222 Output: 113322223333 00330 03240 13243 23243 22043 Output: 334433344232221332 0000777 0006666 0025550 0555300 8888000 9990000 Output: 7776655358899988552566 123456 789876 540032 120000 345678 987654 Output: 123456623789842456784567893157 ``` [Answer] # JavaScript (ES6), ~~116~~ 101 bytes Expects a list of strings, using any non-digit character for padding. Returns a string. ``` a=>(g=X=>+(d&=3,v=(a[y=Y+--d%2]||0)[x=X+~-d%2])?x-q|y?v+g(x,Y=y):v:g(X,d+=2))(q=a[d=Y=0].search`\\d`) ``` [Try it online!](https://tio.run/##TU9NjtowFN77FBZSG1vBEbHj/FAZVu22i9mAAGksYpiMogSSgEClPUGlbrps79HzzAV6BObZEcO8xWf5fT/vvWd91O26KXYdq@rcXDfqqtWEbNVMTXySf1RieFREL85q7jOWf@Cry2VEFyc183@4L52e2P5ynh79LTkN5@pMx8fxlsyGua84pWSv9CJXczVaBa3RzfrpcbnMH@m1MftD0RjibVqPBo3R@ZeiNA/nak1GNOjqh64pqi2hQbsri44MltWyGtBgUzef9fqJtFhN8DeEcWk6rLHC7V04oEMgbNVA6GBX7@45GEJc46ZpDGThDdH0E4LWuq7aujRBWW8JUMOeV3gRBEG9gkWPpmkN5D3XRUU8j@Ip9v7/@/Xy5zegh8fYe/n704Ow7/TKWBiGKBRQgDzqkSHeI@eMoa@HbnfoxhiUQkRRxG25D0JhePMD2vZ7tS0nRcjOYUi4OcL63@mEazgKdEIwxNz0fh/eI2eAN49dQ1jg1moDrJOxJEnsG0PBy6WUkAUo4IoUCjiUZZmVvmWBJ45BItMUqDSVkkuwwzUikjFK0ixNYiQj2IxD03ktk6TIMjK6X@IcMRfWE3GncZCJUCav "JavaScript (Node.js) – Try It Online") ### How? This algorithm starts at the leftmost non-empty cell on the first row of the grid and goes counterclockwise from there, leading to the outputs provided in the test cases in reverse order. The recursive function \$g\$ takes a position \$(X,Y)\$ and a direction \$d\$. (NB: \$Y\$ and \$d\$ are global variables. Only \$X\$ is passed explicitly.) We first look for the smallest \$q\ge0\$ such that the cell at \$(q,0)\$ is not empty and do an initial call to \$g\$ with \$(X,Y)=(q,0)\$ and \$d=0\$. Within the function \$g\$: 1. We force \$d\$ into \$[0,1,2,3]\$ by isolating the two least significant bits, and we decrement it afterwards. 2. We advance by one square to a new position \$(x,y)\$, according to the updated value of \$d\$: * \$-1\$ = north * \$0\$ = west * \$1\$ = south * \$2\$ = east 3. If we've just reached \$(q,0)\$, the border is complete. We append the last value and stop. 4. Otherwise, we do a recursive call: * If the cell at our new position is non-empty, we append the value of the cell to the final result and process the recursive call `g(x,Y=y)`. Because \$d\$ was decremented at step 1, it means that we do a 90° turn to the right. * Otherwise, we process the recursive call `g(X,d+=2)`, which means that we rollback to the previous position and do a 90° turn to the left. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ ~~53~~ 51 bytes ``` WS⟦ι⟧J⌕⭆θ¬Σι0⁰≔⁰θW¬⁼0KK«⊞υKK≦⊕θW›0§KV⁻¹θ≦⊖θ✳⊗θ0»⎚↑υ ``` [Try it online!](https://tio.run/##XY9BS8QwEIXPza8Ie5pAhbZ6sqfFVamwS2HVi3iI7bANpkmbJiqIv71OSVVwDo/J8OZ7maaTrrFSz/N7pzRyqMwQ/NE7ZU4gBK@p8fCknkXJ7kI/3Fu4UaaF6NjLAcaUH6yHY@hBCSFSvsk2pBktbKdJnQxkKR/ptQYs5usxSD0BOVNeI75SEmV9sqQOUwfhd1iyhCJWTGUahz0aj20EJivx1qH06CJu6yvT4gcshEdrDhh6aQzQj/bKhAnyZXdJ@wPv8D84Xr1TDhuvLDlseNHYwvhzX8m@2JVG6YDa6L58GFIeRDnPnOd5zvJzKtLiIipnRdSi4JzNZ2/6Gw "Charcoal – Try It Online") Link is to verbose version of code. Uses space as the padding character. Edit: Saved ~~29~~ 31 bytes by realising that the border end could be detected without deleting the interior. Explanation: ``` WS⟦ι⟧ ``` Print the input to the canvas. ``` J⌕⭆θ¬Σι0⁰ ``` Find the first digit in the first row. ``` ≔⁰θ ``` Start moving horizontally. ``` W¬⁼0KK« ``` Repeat until the border has been traversed. ``` ⊞υKK ``` Append the next border cell to the result. ``` ≦⊕θ ``` Try rotating left. ``` W›0§KV⁻¹θ≦⊖θ ``` Rotate right if necessary until a digit is found. ``` ✳⊗θ0 ``` Move in that direction, erasing the current border. ``` »⎚↑υ ``` Output the final result. [Answer] # Python3, 307 bytes ``` E=enumerate M=[(0,1),(0,-1),(1,0),(-1,0)] def f(b): d={(x,y):v for x,r in E(b)for y,v in E(r)} T=[] for x,y in d: if d[(x,y)]and any((x+X,y+Y)not in d or not d[(x+X,y+Y)]for X,Y in M):T+=[d[(x,y)]] if 0==d[(x,y)]:T+=[d[J]for X,Y in[(1,1),(-1,-1),(1,-1),(-1,1)]if(J:=(x+X,y+Y))in d and d[J]] return T ``` [Try it online!](https://tio.run/##bVI9b4MwFNz9K6wstRun8gcEEsljl0rtlKEVRRUVoCK1BhlaBVX97el7mEQZ8HDGd/fOz9jdOHy0zqSdP53ubeW@vypfDBV5tBmTQnEBuMFJCQm4wSknZVXTmr3zPaGl/WVHMfL9D61bT4/C08bRexBxOYqfsPT8j9CDzXIy20bkSwigTU3LbMrIC1fSwo2MHdfPYly/cNcOk49CDX6jcZZyzHkWL6g/8v1hbbNzTB5SpbVnZpYfrooyOJIKR5oPuJmXiudNzR729rIXn3rA7jAD4n01fHtHD6eeWrparYiUSimiDAxAHQWURAfUWkqCvl7NBUqdCwBBV0HWV3mSmCnPgKyDbC6yMZLIKTxspwNqCThZo4tVyiRJcN7CgFnHcQzFgAa6SmGARna7HVpDcXzuUpso3pIk3aXJlsQR7KuBnIyoJClBJY6mMnwWQ/v23ha@ZD2@jvk/ZdntV9Gxxg2iCRfX4LXVzedQefbUukrQ/q7vPpuB3by6Gw5vjHQe/KxmV4mcL7BqmdbLtFmmo2U6Bvr0Dw) ]
[Question] [ Sequel of [Counting valid Binary Sudoku rows](https://codegolf.stackexchange.com/q/201094/78410). ## Background Binary Sudoku, also known as [Takuzu](https://en.wikipedia.org/wiki/Takuzu), Binario, and Tic-Tac-Logic, is a puzzle where the objective is to fill a rectangular grid with two symbols (0s and 1s for this challenge) under the following constraints: 1. **Each row/column cannot have a substring of `000` or `111`, i.e. one symbol cannot appear three times in a row, horizontally or vertically.** * A row/column of `1 0 0 0 1 1` violates this rule since it contains three copies of `0` in a row. 2. **Each row/column should contain exactly as many 0s as 1s, i.e. the counts of two symbols must be the same.** * A row/column of `1 0 1 1 0 1` violates this rule since it has four 1s but only two 0s. * Some examples of rows that meet the first two requirements include: ``` [1 0 0 1] [1 1 0 0] [1 1 0 1 0 0] [1 1 0 0 1 0 0 1] ``` 3. **The entire grid cannot have two identical rows or columns.** Note that the constraint 2 enforces the grid size to be even in both dimensions. Here are some examples of completed Binary Sudoku: ``` (4x4) 1 1 0 0 0 1 1 0 1 0 0 1 0 0 1 1 (6x8) 1 1 0 1 0 1 0 0 0 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 0 0 1 1 0 0 0 0 1 0 1 1 0 1 1 0 1 1 0 0 1 0 ``` ## Challenge Given two positive integer `m` and `n`, calculate the number of distinct valid Binary Sudoku boards of width `2m` and height `2n`. (You may take the values of `2m` and `2n` as input instead of `m` and `n`.) [A253316](http://oeis.org/A253316) is the sequence for square boards. ## Test cases ``` m,n => answer ------------- 1,1 => 2 1,2 => 0 2,2 => 72 2,3 => 96 2,4 => 0 3,3 => 4140 3,4 => 51744 3,5 => 392208 4,4 => 4111116 ``` For the input `1,2`, it counts 2-by-4 boards, i.e. boards with four rows of length 2. But we can't have four distinct rows of length 2 to fill the grid (we have only 01 and 10). Therefore, by rule 3, the answer to the input `1,2` is zero. The same argument applies to the input `2,4` (4-by-8 boards). [Reference implementation in Python](https://tio.run/##jZLBboMwDIbveQrfSFjXlWyTJtTsRRCaGA1dJEiyEFStL89soKWqdtiFWPb3278T/E/8claOYxNcBybqEJ1rezCddyGmLICCZ1bj95UFd@oxKLrKc2PjBj6N5UYUMi@358a0LZdpEAIaF8CAsRAqe9T8JU3D09sG6BRgmkW2rd1gI0@yRCgVoLIHSHa7XQLWRRLP1JzPsuwuX7Kuih/fgx40WSrKkt2NrVMpcgZg9WnlSkwQh2Iirz0InCuE46JTH9x3LgDZvqmgLofa2WjsoFei1ZZjScC7AnlRTpUKLyfbq37oeO1asVdyGoYxtTsbT7riUZYbmIIMg2WeEPm6w7byXtsD0fAAxYKUYpml217/j769vSvPfMB3BXJJhi9ularv3aa05vw4tHSvI1/TKMAf4c97FuP4Cw). This can handle up to `3,5` in a minute. Note that putting `r > c` takes much more time than the same pair swapped, though the results are the same. ## Scoring and winning criterion Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest submission in bytes wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3/), ~~265~~ ~~250~~ 198 bytes ``` lambda n,m:sum(not(n>len({*s})or m>len(set(z:=[*zip(*s)]))or any(p*3in"".join(v)or v.count("1")*2-len(v)for p in'01'for v in[*s]+z))for s in P(*[[*P(*['01']*m)]]*n)) from itertools import*;P=product ``` [Try it online!](https://tio.run/##HY3NjsIwDITvPEXUC7ZhEX9CK1bdZ@BecijQiqDGjpK0EkU8e0m4jGb8zcjuGe/Cu1/np7Y8T11tL7da8dIeQ2@BJQL/dw3Di8IbxSv7TaGJMB7LikbjgAJqzKzmJzjaGS6K1UMMw5Cvw@oqPUcoNgXS9ifPB2wTcMrwfL2ZZz8kX1HQixG/LKSsTkBVRVlzTZNFrYkRZ60Xq0xsfBTpUtU68ZH@TqXzcuuvcXLepI8t7JcHxOkD "Python 3 – Try It Online") Takes as input `2n` and `2m`. Thanks to Bubbler for finding a bug in my original answer and for golfing a *massive* 52 bytes off. ## How it works: The anonymous function we define will be taking `2n` and `2m` as input, generate all binary boards with the specified dimensions and then count how many of those satisfy the restrictions. ### Generating all boards ``` ... for s in P(*[[*P(*['01']*m)]]*n)) from itertools import*;P=product ``` is generating all the boards. The `product` function from the library `itertools` can be used to generate the cartesian product of all the arguments it is given. Breaking the nested `P`s down, `P(*['01']*m)` creates a list of length `m` with `'01'`: `['01', '01', ..., '01']` and then the splat operator `*` is used to turn each element of the list into an argument to `P`, so `P(*['01']*m)` [generates all valid rows of length `m`](https://tio.run/##Dco7DoAgDADQ2Z6im8Ik0cFouAO7cfITSYQ2tQ6eHn3z41dPyt3AUkpCjz3AIZQw6i5KdN0YE5OonYJnoe1ZFYL7Y2jsXLeuXmwycJAgY8wY3AgVS8zasCnlAw). Call it `P1`. Then we have `P(*[[*P1]]*n)` which takes all valid rows and turns it into a list of all valid rows, with `[*P1]`. We then enclose such a list in another list and multiply by `n`, so that we get a list of length `n` where each value is a list of all valid rows. Then the splat operator `*` is used to provide such a list as a series of arguments to the `itertools.product` function, thus [getting all the correct-sized binary sudoku boards](https://tio.run/##PYwxDsIwDEV3n8JbG08kMCBQ7@C9ylRARCKxZczA6UMG1OXr6enp69ef0o5ntd4rLniCNjYBPEwqFr@bi7zeWKqKOV15UZPbZ3PgOEKeaZ0OccpUA3D6m5U45kwtjBsxVCwNOV0AUa00nzXsGHr/AQ). We iterate over those with `s`. ### Checking restrictions on the board Now we are left with checking the conditions imposed on the board `s` with ``` not(n>len({*s})or m>len(set(z:=[*zip(*s)]))or any(p*3in"".join(v)or v.count("1")*2-len(v)for p in'01'for v in[*s]+z)) ``` Instead of verifying if the board satisfies everything, we check if the board doesn't violate any restriction: * `n>len({*s})or m>len(set(z:=[*zip(*s)]))` checks if there are `n` unique rows, by converting the list of rows into a set; similarly we transpose `s` into `z` and check if there are `m` unique columns; * then `any(B1 or B2 for v in[*s]+z)` goes over all rows and all columns: + `B2 = v.count("1")*2-len(v)` gives 0 when the amount of `1`s is exactly half of the size of the row/column and other non-zero integers when it is not. Regardless of giving a positive or negative result, [Python will treat it as a Truthy value](https://tio.run/##K6gsycjPM7YoKPr/v0zBViEns7hEIzexQKO4pEhHIdpQRwGODIAoVlOTKzNNoUwvOb80r0RDyVBJU8tINyc1T6NM04pLQaGgKBMkHJKfr5CbmFepXwJkpKWWKxgWK2lyceG0wACOKLHg/38A). + `B1 = p*3in"".join(v) for p in'01'` builds the substrings `"000"` and `"111"` and checks if those are in the row/column ### Wrapping it up In the end, we just sum all the Truthy values that correspond to all the boards that did not violate any restrictions. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 144 bytes *Input (2n,2m)* ``` (l=Length)@Select[Tuples[{0,1},g=#],And@@Flatten[{#~Count~1==#~Count~0,Max[l/@Split@#]<3}&/@Flatten[c={#,Transpose@#},1],1]&&l/@(Union/@c)==g&]& ``` [Try it online!](https://tio.run/##PctBC4IwGIDhvxIMhsJAJY8NFkGngkA7jR3GGmswP0U/IRjzry8vBe/hvTyDxrcdNHqjs@O5CPxmweG7FJ0N1qDs1ynYRcaaNYk5ThQ7w0uIa9CIFmQk22VcAbeG89/W7K4/MlSim4JHQdTpmGj1J4ZHwvpZwzKNixUksUbtUbqL4gl@hEqYknNHFc2P2QMehJOxZW1SOX8B "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` IIP;S¬$PȧQƑ ר-ṗ$s€ÇƇZ€$⁺L ``` A dyadic Link accepting `2n` on the left and `2m` on the right (or vice-versa as it's symmetric) which yields the count. **[Try it online!](https://tio.run/##y0rNyan8/9/TM8A6@NAalYATywOPTeQ6PP3wDN2HO6erFD9qWnO4/Vh7FJBWedS4y@f///8m/00A "Jelly – Try It Online")** This will time out even for `(6,4)` (i.e. `m=2` and `n=3`)\* ### How? I imagine that if one worked out a combinatorial formula it would be much shorter (and quicker and more memory efficient!), but this entry is pure brute-force... ``` IIP;S¬$PȧQƑ - Link 1, ( no row has a run of 3 or more AND no column contains differing type counts AND all the rows are different ): a single board, B I - incremental differences (vectorises) - e.g. [-1,1,1,1] -> [2,0,0] I - incremental differences (vectorises) P - product - this will give a list which will contain a zero for any row containing a run of at least three equal items $ - last two links as a monad: S - sum (vectorises) - since we use -1 and 1: zero if the counts are equal ¬ - logical NOT ; - concatenate P - product - this will be non-zero if (no row has a run of 3 or more AND no column contains differing type counts) Ƒ - is (B) invariant under: Q - de-duplication - i.e are all the rows different? ȧ - logical AND ר-ṗ$s€ÇƇZ€$⁺L - Link: 2n, 2m × - multiply -> 2n×2m (size of board) $ - last two links as a monad: Ø- - signs = [-1,1] ṗ - Cartesian power (all lists of length 2n×2m of items -1 and 1) € - for each: s - split into slices of length 2m (i.e. into rows) $ - last two links as a monad: Ƈ - filter keep those for which: Ç - call last Link (1) as a monad € - for each: Z - transpose ⁺ - repeat the last link - i.e. check the results with rows<->columns L - length ``` --- \* I ran `m=2`, `n=3` locally and it yielded `96` as expected (after over an hour in which it hit 100% memory (16GB Ram) and slowed to a snail's pace while using disk). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~102~~ ~~81~~ 64 bytes ``` Nθ≔×θNη≔EX²η⪪⭆◧⍘ι²ηΣλθζF²≔EΦζ⬤κ›⁼№μ0№μ1⁺⊖№κμΣE²№μ׳IξEθ⭆κ§ξμζILζ ``` [Try it online!](https://tio.run/##TZDdboQgEIXv@xQTr4aEJq3du72yv9lk25hsX4Aqq6SACkO78eUtuDbKBQnnnPlmhqoVruqEnqaD7QN9BPMlHQ5sf1N4rxqLn8pIjwOHrc8Yh3bNvIsey@43GnnSOZx6rQhP5JRtZlPUR3kmfBReXlVUHHK2pINBnZBDusbIPXcOMGew4b8qTbHByKHQGr85vDkpkvIyBKE9PnXBEhoO2V0WKevzPkvUUgePz7Jy0khLsl7ykWPYMkLqkm8qr5s/REV4wgtbDocUjB@yrhcpBR1sLS94mYH/e5QxQTjXH6VtqMUxevtp2sFuuv3Rfw "Charcoal – Try It Online") Link is to verbose version of code. Takes the actual size as input. Explanation: ``` Nθ≔×θNη ``` Input the width and area. ``` ≔EX²η⪪⭆◧⍘ι²ηΣλθζ ``` Generate all possible grids of `0`s and `1`s of the given width and area. ``` F² ``` Loop over rows and columns. ``` Φζ⬤κ›⁼№μ0№μ1⁺⊖№κμΣE²№μ׳Iξ ``` Keep only those grids where each row has an equal number of `0`s and `1`s, is unique, and contains neither `000` nor `111`. ``` ≔E...Eθ⭆κ§ξμζ ``` Transpose the rows and columns so that the columns can be checked on the next pass. ``` ILζ ``` Output the number of remaining grids. Previous much faster 102-byte version: ``` NθNη≔ΦEX²θ⭆◧⍘ι²θΣλ›⁼№ι0№ι1ΣE²№ι׳Iλζ⊞υ⟦⟧FυF‹LιηFζF¬№ιλ⊞υ⁺ι⟦λ⟧ILΦEΦυ⁼LιηEθ⭆ι§νλ⬤ι›⁼№λ0№λ1⁺⊖№ιλΣE²№λ׳Iν ``` [Try it online!](https://tio.run/##bVBNT8MwDL3zK6KeHKlIUHbbqXxq0pgqwW3aIbRZG8lN13wA2p8vThdYi5ZDYj@/PNuvbIQpO4HDsNIH7za@/ZAGer68muYN5bm1qtbwrNAR8ioOUHRfFGUp63nK3pxRuh5hUa3l3sG9sPKEgkpZxiPPt4CcU/RipAhST70XaOGh89oFZnKTUPWc3iY8/gvq2aT0rlpp4Y4QYd2oykflI41beNuAT9l2R8m@Mww8Z@O7ltbSpWvXgCJ2w2PhGN9N587TBFX2K1agtwHc4o6HHrQcUUPzqDdxJ4b0Ky44b5myQOqnxpFw7la6kt@gT42JlSOGwkWzcG4W/pk1zvkoSyNbqZ2sZutc8BL/e6n55CyHYcEWw/Un/gA "Charcoal – Try It Online") Link is to verbose version of code. Takes the actual size as input. ]
[Question] [ If \$f,g\colon \mathbb{Z}\_{\geq 1} \to \mathbb{R}\$, the *Dirichlet convolution* of \$f\$ and \$g\$ is defined by \$ \qquad\qquad\qquad \displaystyle (f\*g)(n) = \sum\_{d|n}f(d)g(n/d).\$ [This question](https://codegolf.stackexchange.com/q/176100/77634) asked about computing Dirchlet convolution of functions. The identity element of the Dirichlet convolution is the function \$ \qquad\qquad\qquad\qquad\,\, e(n)=\begin{cases}1 & n=1 \\ 0 & \text{else}\end{cases}\$. If \$f\*g=e\$ then \$f\$ and \$g\$ are convolutional inverses. If \$f(1)\neq 0\$ then \$f\$ has a convolutional inverse. There is a formula for the inverse: \$\qquad \qquad \qquad \qquad\,\,\,\displaystyle g(1)=\frac{1}{f(1)}\$ \$\qquad \qquad \qquad\qquad\,\, \displaystyle g(n)=\frac{-1}{f(1)}\sum\_{\substack{d|n\\d<n}} f(n/d)g(d) \qquad \text{for $n>1$}\$. ## Task: Given a list `l` of integers, compute the convolution inverse of `l`. The output should be a list of the same length as `l`. The list `l` represents the function \$\qquad\qquad\qquad\qquad\,\, f(n) = \begin{cases} \text{The $n$th entry of l} & n < \text{len(l)} \\ 0 & \text{else} \end{cases}\$ My test cases are one-indexed because it makes sense in context. If you wish to pad the input and output with an ignored element at the beginning, or make some other modification to support zero indexing, that's fine. Most other i/o formats are probably acceptable. You may assume the output are integers. ## Test Cases ``` Input: [1, 0, 0, 0, 0, 0, 0] Output: [1, 0, 0, 0, 0, 0, 0] Input: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Output: [1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0] Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] Output: [1, -2, -3, 0, -5, 6, -7, 0, 0, 10, -11, 0, -13, 14, 15, 0] Input: [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5] Output: [1, -2, -2, 1, -2, 4, -2, 0, 1, 4, -2, -2, -2, 4, 4, 0] Input: [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12, 28, 14, 24, 24, 31, 18, 39] Output: [1, -3, -4, 2, -6, 12, -8, 0, 3, 18, -12, -8, -14, 24, 24, 0, -18, -9] Input: [1, 5, 10, 21, 26, 50, 50, 85, 91, 130] Output: [1, -5, -10, 4, -26, 50, -50, 0, 9, 130] Input: [-1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1] Output: [-1, -1, 1, -2, 1, 1, 1, -4, 0, 1, 1, 2, 1, 1, -1, -8, 1, 0, 1] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 32 bytes ``` 1i1)/Gd"GX@QtZ\3L)/)y7M)*s_G1)/h ``` [Try it online!](https://tio.run/##y00syfn/3zDTUFPfPUXJPcIhsCQqxthHU1@z0txXU6s43h0ok/H/f7ShjoKpjoKhgY6CEZBpZAbkGkCwBVDcEihmaGwQCwA) Or [verify all test cases](https://tio.run/##nVC9CsIwEN59isMtctJeYttkcxCy6CA4SLWo4KCgkx306eNdr3VwLNwl4fu7JM9L@0jnRHcyWbxO4365beujW5vMfKqNmb1OkZlbalb1e5cOhJD/VTMRdGSp2SI4hAVCgVAiVAgeITDN@SQyFhAriCXEGip/PrXazq2rG87lgEiwGpSrOk5CfZ8n2V4h63WO7duRci5oRKHXsjKeU4pc2zMeROrkQ@b6vPFb8wU). ### How it works ``` 1 % Push 1 i % Take input: f, of size L 1) % Get its first entry: f(1) / % Divide: gives 1/f(1). This is g(1). It will later be expanded into % a vector to include g(2), g(3), ... g(L) G % Push input again d % Consecutuve differences: gives a vector of L-1 numbers " % For each: this iterates L-1 times G % Push input again X@Q % Push iteration index plus 1: gives 2, 3, ..., L respectively in % each iteration. This is n in the formula for computing g(n) t % Duplicate Z\ % Divisors of n. Gives a vector with the values of d in the formula 3L) % Remove last. This corresponds to the condition d<n in the formula / % Divide. Gives a vector with n/d for d<n ) % Index. Gives a vector with f(n/d) y % Duplicate from below. Pushes a copy of g as built so far 7M % Push vector containing d for d<n, again ) % Index. Gives a vector with g(d) * % Multiply, element-wise. Gives a vector containing f(n/d)*g(d) s % Sum _ % Negate G % Push input again 1) % Get its first entry: f(1) / % Divide. This gives g(n) h % Contatenate. This attaches the newly computed g(n) to the vector % containing the previous values of g % End (implicit) % Display (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 bytes ``` ÆD,U$ị"PṖS×Ḣḣ1N;"@ JḊç@ƒİḢ,ƊḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm4tOqMrD3d1KAQ93Tgs@PP3hjkUPdyw29LNWcuDyerij6/Byh2OTjmwACusc6wKS/3UOtx@d9HDnjEdNa7IeNcxR0LVTeNQwl@twO1Ag8v//aK5oQx0FAzQUqwMWJhNBdRvpKBjrKJjoKJjqKJjpKJjrKFjoKFgC5YE2GILUARUYAlUYApUYAtUYmiE0QvQagbVDSGMY2wwmAjIZqgMiaQ6WBBlrATURZLoFRMjIAmKTERQbG0LkjC2hZphCXGYEcgDQGFMDCLYAiluC1BqDQ0UX4kfyqViuWAA "Jelly – Try It Online") I’m sure there’s a golfier way of doing this. A pair of links which is called as a monad with the list of integers as the argument. Returns a list of integers. ## Explanation ### Helper link Takes n as its left argument and the current pair of outputs for g and f as its right argument ``` ÆD | Divisors ,U$ | Pair with reversed divisors ị" | Index into lists of g and f values respectively P | Product of g and f terms Ṗ | Remove last item from list S | Sum × | Multiply by current g and f terms Ḣ | Head ḣ1 | First term (i.e. the sum of the product of the specific g and f terms above, multiplied by g(1)), still wrapped in a list N | Negate ;"@ | Concatenate to the end of the list of g terms ``` ### Main link ``` J | Sequence along list Ḋ | Remove first item ç@ƒ Ɗ | Reduce using helper link with reversed arguments and the following as a monad as the initial argument İ | Invert (the initial list of integers) Ḣ | Head , | Pair with initial list of integers Ḣ | Head (i.e. final list of g values) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` FLθ⊞υ∕∨‹ι²±ΣEυ∧∧λ¬﹪ιλ×§θ÷ιλκ§θ¹Iυ ``` [Try it online!](https://tio.run/##TYw7D8IwDIR3foVHRzJDW55iqmBB4iXBhhgiGmhESKBJEP8@uJSB4XS6u88@17I5O2lSurgGcKXsNdT4FAJ20dcYCRb6pSuF24ZH71ET5IJgo64yKNzHO67lo@VKW2Erw6MLuHZVNK7FjRB8cNB35bEMS1upNz4Jljb8XncMwU2IL/oHZVzMertG24Bz6QNGzikdjxlvBAXBgGBMMOKYE0zYhizus0lX5a0zlP9UZN1WTE@n1H@ZDw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed; on input, the 0th element is a dummy, while on output, it's a duplicate. Explanation: ``` FLθ ``` Loop over the indices of the input list. ``` ⊞υ ``` Save the results as we go. ``` ∕∨...§θ¹ ``` Each term is divided by \$f(1)\$. ``` ‹ι² ``` For the 0th and 1st terms, the numerator is simply `1`. ``` ±ΣEυ∧∧λ¬﹪ιλ×§θ÷ιλκ ``` Otherwise, multiply the terms computed so far whose index is a factor of the current index with the appropriate term from the input, and take the negated sum. ``` Iυ ``` Print the results. Alternative rearrangement, also 33 bytes: ``` I⊟Eθ⊞Oυ∕∨‹κ²±ΣEυ∧∧μ¬﹪κμ×§θ÷κμλ§θ¹ ``` [Try it online!](https://tio.run/##RY1PC4JAEMW/yhxnYTqo/TE6SV2ETKFu0WHJJSV1bXeVvv02ZtDAY5g3vzdzr6S5a9l4X5i6c7iX1mGhe8xkjy@CYrBV3isjnTY4EBzqsS4V5gaPylp8EoSC4KQe0ik8D@03x1zSlTip5aV2mOlyaPSEt0Jw4FK3ymLi0q5U7@lP2rnf6ZkhaMS3@NSfCmZP7Ly/XgOeCSKCJcGGYM1jSBBzW7HYD@LZCqfOUPhTFMy7aHu7@cXYfAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # JavaScript (ES6), ~~77 76 70~~ 69 bytes ``` a=>a.map((_,n)=>a[~n]=a.reduce(p=>p-=a[n/++d-1]*a[-d]|0,d=!n++)/a[0]) ``` [Try it online!](https://tio.run/##nZDPUsMgEMbvPgXewCxpAJOSA30RhnF2QuroVJJp1ZPjq8eltBeNl86w/Fl@@30Lr/iJp@H4Mr/LNMVx2bsF3Q7rN5w5f4Ik6OC/U3BYH8f4MYx8drtZOvRpU1VRqvCAXsbw1UB096mqxAZ9E8QyTOk0Hcb6MD3zPfcKWPNrBCHu/lI3jnUxDcwAewTWAuuAbYFZYD3h5K9yGQGKCEWIIkZ1/@oUKX1WK7O57rtrJhutCxR2e2azqb34ZW9bUtqWPvQljCp3pl@XbMszdG6PVNumhKV8n0vN2gfL8l23L6S5/AA "JavaScript (Node.js) – Try It Online") ]
[Question] [ # Introduction Big 2 is a card game popular in East Asia and South East Asia, in which 4 players are dealt 13 cards each (ie, an equal division of a standard deck without jokers). The goal is to empty your hand before any of the other players. Players take turns playing combinations of a Big 2 subset of standard poker hands until their hands are empty. When cards are played, they are considered to be in a discard pile and cannot be reused. The challenge here is to determine the fewest number of poker hands needed to completely empty a starting hand assuming that there are no other players. In other words, given 13 cards, produce a list of the poker hands that would empty your hand the fastest (ie, the fewest number of 'turns'). # Challenge Given a list of 13 cards of the format `<rank><suit>`, produce a delimited combination of Big 2 poker hands that would allow the player to empty their hands as fast as possible. Assume that the given hand can be realistically produced from a single deck of cards (ie, you won't receive 10 aces in your hand). ## Inputs * An unsorted list of 13 cards, meaning that the ranks and suits are not in any patterned/sorted order + The ranks can be any of `A,2,3,4,5,6,7,8,9,0,J,Q,K`, where '0' is a 10. You may use rank `10` in your program if that suits you better. + The suits can be any of `D,C,H,S`, which correspond to diamonds, clubs, hearts, and spades, respectively. + Sample cards would be `AD` for ace of diamonds, or `0H` for 10 of hearts. * For this example, the inputs are separated by commas, but you can delimit the string however you like, or even use an entirely different representation of a deck of cards that suits your fancy ## Outputs * A list (or some delimited string) of cards that indicate play order of your cards. For example the following output formats are valid: ``` 2H, 3D, 4H, 5C, 6S 7S, 7D, 7H 0D, JD, QD, KD, AH ``` + or `[[2H, 3D, 4H, 5C, 6S], [7S, 7D, 7H], [0D, JD, QD, KD, AH]]` + or `2H3D4H5C6S, 7S7D7H, 0DJDQDKDAH` + **or anything else that can delineate hand combinations (aka convenient inputs and outputs)** * All three sample outputs indicate that 13 cards were played in the following order: a straight from 2-6, a triplet of 7s, and then a straight from 10-A * When outputting a 5 card combination, such as for straights or full houses, the cards' ranks/suits do not have to be sorted or grouped in any way - they're mostly shown here for legibility. For example, the straight `2S3S4S5S6S` is equivalent to `6S4S2S5S3S`. (`23456 == 64253`) * The actual order of moves does not matter as cards cannot be reused anyways ## Big 2 Poker Hands In Big 2, the following poker hands are legal: * A single card * A pair of cards, meaning two cards of the same rank regardless of suit * A triplet of cards, meaning three cards of the same rank regardless of suit * A straight, a 5 card combination of consecutive ranks regardless of suit. + Straights cannot start from a jack, queen, or king (ie, the straights of ranks (regardless of suit) `JQKA2`, `QKA23`, and `KA234` are invalid) + Straights can start from any other rank + Aces can either be the high card or the low card in a straight, but it cannot appear in the middle of a straight. Namely, the only 2 valid straights that include an ace are `0JQKA` and `A2345`. * A full house, a 5 card combination made of three cards of the same rank, and 2 cards of the same, but different rank. + For example, `000QQ` is a full house with triplet 10s and a pair of queens, but the combination `000KQ` is invalid because a pair is needed to complete the triplet * A quad, a 5 card combination made of four cards of the same rank, plus any card of a different rank * A flush, a 5 card combination of 5 cards of the same suit regardless of rank * And just for completion's sake: a straight flush, a 5 card combination where the 5 cards are a straight in terms of ranks but also share the same suit. + **Note** the straight flush can be computed from either the definition of a straight or a flush, meaning its own distinct definition here isn't necessary for the completion of this challenge. # Tests **Input**: `AS,4H,6D,8C,7C,3S,5H,8D,4C,2S,0C,AD,AH` **Sample output**: `ASAHAD8D8C, 2S3S4H5H6D, 4C, 7C, 0C` OR `7C, 2S6D3S5H4H, 0C, 4C, 8C8DASAHAD` **Explanation:** Given the above input, it's possible to generate 2 distinct 5-card combination poker hands. After we play those 2 hands, we only have 3 remaining singles. Thus, the minimum amount of hands we must play is 5. Again, the output card hand combinations do not have to be sorted or played in this specific order (or even in this format) - just leaving it here for legibility. --- **Input:** `2D,0H,5S,0S,4H,AS,4C,6C,6H,KC,8H,5H,8S` **Sample output:** `5S5H, 4H4C, 0S0H, 6C6H, 8H8S, KC, AS, 2D` **Explanation:** In this case, it is faster to output 5 pairs instead of a flush (of `5H4H0H6H8H`) because the flush would create 5 dangling single cards that must be played one at a time. Playing the flush would yield 9 turns (1 for flush + 5 singles created from flush + 3 standalone singles), whereas the pair method would require 8 turns (5 turns for 5 pairs, 3 for the leftover singles) --- **Input:** `4D,4S,4H,4C,5H,5D,5C,5S,9S,9D,9H,9C,AD` **Sample output:** `4D4S4H4CAD, 5D5H5C5S9S, 9D9H9C` **Explanation:** Outputting quads using the dangling `AD` is more efficient than picking the quad's last card from another quad because we can finish off with a triplet. # Rules * Standard loopholes are forbidden * Convenient inputs and outputs are allowed * This is codegolf, so shortest code in bytes wins [Answer] # JavaScript (ES6), ~~298 ... 256~~ 253 bytes Takes input as a list of integers in \$[0..51]\$, where the suit is encoded in the 2 least significant bits and the rank in the 4 upper bits. Returns a list of lists in the same format. ``` f=(a,k=2)=>(F=(a,H=[])=>H[k]?a+a?0:O=H:a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(h=>[b=c=m=s=0,h.map(x=>(c++,b+=m!=(m|=1<<x/4),s|=1<<x%4)),b<2,b<2,,b<3|m==4111|m==31*(m&-m)|8%s<1][c]&&F(a.filter(n=>!h.includes(n)),[...H,h])))(a)?O:f(a,k+1) ``` [Try it online!](https://tio.run/##bVBNb@IwEL3zK1ykgqdxveSDFhAOQlRVtntAq/Zm@WASs7AlSRWnVSrx31mP6bKXPfh55r2ZN2P/1h/a5s3@rb2t6sKcTltBNXsVEYiUPmKcCalckslXtdCBXoxma5HNNG9M8Z4b6io6J0vOuWYIvNRv9PPMfLJOgWJSKgXc1qWhOydsRC5KYcWI7Xxx50blQcA2gSivBC2PIpzPu28JMHsOrxMAtplH/jiIj6UQSRiGeMfhDS0HtyUcJ9d2HiqZq8HgkWq@3R9a09BKpFc7vq/yw3thLK2cFa6WsZ0CAKphsZ5t8c1BCKdcN8VL/b1qiSBUNoxYBUSkpB/FyfjufjIdPf38sew7u8J06y1tgNyQhASkv3rInv/xFnr7qn2pV87PWVX/8ZAVSVMSqUuzIwYkVr3WWByvsSevK1sfDD/Uv6hb0n/XZUcAn/vCs3SZ6V7W80ZUDpfPQzZMMgd3Dw4mKwf3CDEKYxQmKCTIRciNMFoit8yGCv4aJb7q4ubrffsYhbFPUZ16QG6K6vTLTcHpDw "JavaScript (Node.js) – Try It Online") This is rather inefficient when more than 5 or 6 turns are required. The 2nd test case completes in a bit less than 2 minutes on my laptop and times out on TIO. ## How? ### Wrapper code The wrapper code invokes the search function \$F\$ for a maximum number of turns \$k+1\$. This threshold is incremented until the call is successful. We start with \$k=2\$ because we need at least 3 turns to get rid of all cards. ``` f = ( // f is the main function taking: a, // a[] = list of cards k = 2 // k = maximum number of turns, minus 1 ) => // (F = ...)(a) ? // invoke the search function F; if successful: O // return the output : // else: f(a, k + 1) // try again with k + 1 ``` ### Generating the hands In the search function, we first build the powerset of the input \$a[\:]\$: ``` a.reduce((a, x) => [ ...a, ...a.map(y => [...y, x]) ], [[]] ) ``` That is, we build all possible hands, including invalid ones made of more than 5 cards. ### Hand variables We then iterate over each hand \$h\$, and each card \$x\$ in this hand to set up the following variables: * \$c\$ is the number of cards in the hand * \$m\$ is a 13-bit rank bitmask * \$s\$ is a 4-bit suit bitmask * \$b\$ is the number of bits set in \$m\$, i.e. the number of distinct ranks in the hand ``` h.map(x => ( // for each card x in h[]: c++, // increment c b += // increment b if m != ( // the current value of m is different from m |= // the updated value of m 1 << x / 4 // where the new rank bit is set ), // s |= 1 << x % 4 // update s with the suit bit )) // end of map() ``` *Example* [![hand](https://i.stack.imgur.com/zm37b.png)](https://i.stack.imgur.com/zm37b.png) *a random hand, courtesy of [random.org](https://www.random.org/playing-cards/?cards=5&decks=1&spades=on&hearts=on&diamonds=on&clubs=on&aces=on&twos=on&threes=on&fours=on&fives=on&sixes=on&sevens=on&eights=on&nines=on&tens=on&jacks=on&queens=on&kings=on&remaining=on)* ``` c = 5 m = 0101010010000 (binary value) K J 9 6 b = 4 s = 1110 (binary value) SHD ``` ### Hand validation We finally figure out whether the hand is valid by picking the result of the relevant test from a lookup table, according to the number of cards \$c\$: * \$0\$ card: always invalid (variables are initialized to \$0\$ in this slot) * \$1\$ card: always valid (the above `map()` is performed in this slot and returns a truthy value) * \$2\$ cards: valid if \$b<2\$ (there's only one rank, which means that we have a *pair*) * \$3\$ cards: valid if \$b<2\$ (there's only one rank, which means that we have a *three-of-a-kind*) * \$4\$ cards: always invalid (undefined slot) * \$5\$ cards, valid if: + \$b<3\$ because both a *quad + another card* and a *full house* lead to \$b=2\$ (two distinct ranks in the hand) while all other patterns result in \$b\ge3\$ + OR \$m=4111\$ (1000000001111 in binary), which represents the special *straight* **A**,**2**,**3**,**4**,**5** + OR \$m\$ has 5 consecutive bits set, which means that we have a standard *straight* ``` m == 31 * (m & -m) ``` + OR \$s\$ has only one bit set, which means that we have a *flush* ``` 8 % s < 1 ``` * more than \$5\$ cards: always invalid (undefined slots) ### Recursion If the hand is valid, we do a recursive call to \$F\$ with all cards in \$h[\:]\$ removed from \$a[\:]\$. ``` F( // recursive call: a.filter(n => // keep only in a[] ... !h.includes(n) // ... the cards that do not appear in h[] ), // [...H, h] // append h[] to the list of hands ) // end ``` We know that we have reached the maximum number of turns when \$H[k]\$ is defined. If we have no more cards when this happens, it means that \$H\$ is a valid list of hands, which is saved in the output variable \$O\$ and eventually returned by the wrapper code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes ``` {æʒ€þ©Ùgyg5Qi3‹y€áË®¥ć8%šPΘ)à]æé.Δ˜I¢P ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/@vCyU5MeNa05vO/QysMz0yvTTQMzjR817KwEiS083H1o3aGlR9otVI8uDDg3Q/PwgtjDyw6v1Ds35fQcz0OLAv7/j1Yy8VDSUVAycwGR5s4g0jgYRJqCxU3AIkZgEUMDZ6VYAA "05AB1E – Try It Online") Input/output uses 1 for Ace, 10 for 10, 11 for Jack, 12 for Queen, 13 for King. Runtime is exponential in the number of possible hands, making it timeout for all test cases. The TIO link shows an 8 card input, but the algorithm would theoretically work for inputs of any size, including the specified 13. ``` # The first step is to get a list of all valid hands { # sort the input æ # all subsets of the input (aka all hands) ʒ ] # filter: €þ # get the rank of each card in the suit © # save that in the register, without popping Ù # uniquify g # length (=> number of distinct ranks in the hand) yg5Qi ] # if the hand has exactly 5 cards: 3‹ # is the number of distinct ranks < 3? (full house or quad) y€áË # are all suits of the hand equal? (flush) ®¥ # deltas of the list of ranks (restored from the register) ć8%š # mod 8 the first one (to handle the A0JQK case) PΘ # is the product equal to 1? (straight) ) # wrap those three tests in an array à # keep the hand if the maximum is 1 (one of the tests was true) # else (implicit): # keep the hand if number of distinct ranks is 1 # this catches singles, pairs, and triplets æ # get all subsets of the list of valid hands é # sort those subsets by length .Δ # find the first one such that: ˜ # deep flattened I¢ # count occurences of each card of the input in the result P # product is 1 ``` ]
[Question] [ Given a string ending in either "er", "ir", or "re" (the "infinitive"), output the full conjugation of the string as a French verb in the seven simple tenses. For each tense (in the order given below), output each subject pronoun in the following order: *je*, *tu*, *il*, *elle*, *nous*, *vous*, *ils*, *elles*; followed by a space, the verb conjugated according to that pronoun, and a newline. If the verb begins with a vowel (`aeiou`) or `h`, *je* becomes *j'* and the space is omitted. In all the examples, I will use the regular verbs *exister*, *invertir*, and *rendre* to demonstrate. French has a great many irregular verbs, which we shall ignore to make the specification and challenge easier. # The tenses ## Present tense Remove the *er/ir/re* from the infinitive and add the following endings: * *er*: *j'exist**e**, tu exist**es**, il exist**e**, elle exist**e**, nous exist**ons**, vous exist**ez**, ils exist**ent**, elles exist**ent***. * *ir*: *j'invert**is**, tu invert**is**, il invert**it**, elle invert**it**, nous invert**issons**, vous invert**issez**, ils invert**issent***. * *re*: *je rend**s**, tu rend**s**, il rend, elle rend* (no endings), *nous rend**ons**, vous rend**ez**, ils rend**ent**, elles rend**ent***. ## Imperfect Remove the *er/ir/re* from the infinitive and add the following endings: * *er* and *re*: *j'exist**ais**, tu exist**ais**, il exist**ait**, elle exist**ait**, nous exist**ions**, vous exist**iez**, ils exist**aient**, elles exist**aient***. * *ir*: *j'invert**issais**, tu invert**issais**, il invert**issait**, elle invert**issait**, nous invert**issions**, vous invert**issiez**, ils invert**issaient***. ## Simple past Remove the *er/ir/re* from the infinitive and add the following endings: * *er*: *j'exist**ai**, tu exist**as**, il exist**a**, elle exist**a**, nous exist**âmes**, vous exist**âtes**, ils exist**èrent**, elles exist**èrent***. * *ir* and *re*: *je rend**is**, tu rend**is**, il rend**it**, elle rend**it**, nous rend**îmes**, vous rend**îtes**, ils rend**irent**, elles rend**irent**.* ## Future For all verbs, add these endings directly to the infinitive (though *re* verbs drop the *e*): * *j'invertir**ai**, tu invertir**as**, il invertir**a**, elle invertir**a**, nous invertir**ons**, vous invertir**ez**, ils invertir**ont**, elles invertir**ont***. ## Conditional For all verbs, add these endings directly to the infinitive (though *re* verbs drop the *e*): * *j'invertir**ais**, tu invertir**ais**, il invertir**ait**, elle invertir**ait**, nous invertir**ions**, vous invertir**iez**, ils invertir**aient***, elles invertir**aient\***. ## Present subjunctive Remove the *er/ir/re* from the infinitive and add the following endings: * *er* and *re*: *j'exist**e**, tu exist**es**, il exist**e**, elle exist**e**, nous exist**ions**, vous exist**iez**, ils exist**ent**, elles exist**ent***. * *ir*: *j'invert**isse**, tu invert**isses**, il invert**isse**, elle invert**isse**, nous invert**issions**, vous invert**issiez**, ils invert**issent**, elles invert**issent***. ## Imperfect subjunctive Remove the *er/ir/re* from the infinitive and add the following endings: * *er*: *j'exist**asse**, tu exist**asses**, il exist**ât**, elle exist**ât**, nous exist**assions**, vous exist**assiez**, ils exist**assent**, elles exist**assent***. * *ir* and *re*: *je rend**isse**, tu rend**isses**, il rend**ît**, elle rend**ît**, nous rend**issions**, vous rend**issiez**, ils rend**issent**, elles rend**issent***. # Sample output For an *er* verb, `aller`, your output should be: ``` j'alle tu alles il alle elle alle nous allons vous allez ils allent elles allent j'allais tu allais il allait elle allait nous allions vous alliez ils allaient elles allaient j'allai tu allas il alla elle alla nous allâmes vous allâtes ils allèrent elles allèrent j'allerai tu alleras il allera elle allera nous allerons vous allerez ils alleront elles alleront j'allerais tu allerais il allerait elle allerait nous allerions vous alleriez ils alleraient elles alleraient j'alle tu alles il alle elle alle nous allions vous alliez ils allent elles allent j'allasse tu allasses il allât elle allât nous allassions vous allassiez ils allassent elles allassent ``` For an *ir* verb, `avoir`, your output should be: ``` j'avois tu avois il avoit elle avoit nous avoissons vous avoissez ils avoissent elles avoissent j'avoissais tu avoissais il avoissait elle avoissait nous avoissions vous avoissiez ils avoissaient elles avoissaient j'avois tu avois il avoit elle avoit nous avoîmes vous avoîtes ils avoirent elles avoirent j'avoirai tu avoiras il avoira elle avoira nous avoirons vous avoirez ils avoiront elles avoiront j'avoirais tu avoirais il avoirait elle avoirait nous avoirions vous avoiriez ils avoiraient elles avoiraient j'avoisse tu avoisses il avoisse elle avoisse nous avoissions vous avoissiez ils avoissent elles avoissent j'avoisse tu avoisses il avoît elle avoît nous avoissions vous avoissiez ils avoissent elles avoissent ``` For an *re* verb, `faire`, your output should be: ``` je fais tu fais il fai elle fai nous faions vous faiez ils faient elles faient je faiais tu faiais il faiait elle faiait nous faiions vous faiiez ils faiaient elles faiaient je faiis tu faiis il faiit elle faiit nous faiîmes vous faiîtes ils faiirent elles faiirent je fairai tu fairas il faira elle faira nous fairons vous fairez ils fairont elles fairont je fairais tu fairais il fairait elle fairait nous fairions vous fairiez ils fairaient elles fairaient je faie tu faies il faie elle faie nous faiions vous faiiez ils faient elles faient je faiisse tu faiisses il faiît elle faiît nous faiissions vous faiissiez ils faiissent elles faiissent ``` (These are *not* the true conjugations of the above verbs. In reality they are highly irregular.) This is code golf. The shortest submission wins. [Answer] # JavaScript (ES6), ~~507~~ 504 bytes Returns an array of 7 tenses, where each tense is an array of 8 forms. ``` (v,[a,b]=v.split(/(..)$/),g=b>'r'?2:b<'i')=>[...S='0123456'].map(x=>'je/tu/il/elle/nous/vous/ils/elles'.split`/`.map((s,n)=>(!n*/^[aehiou]/.test(a)?"j'":s+' ')+a+(x>2&x<5?g>1?'r':b:'')+[...S+'789ABCD'].reduce((p,c)=>(l=p.split(c)).join(l.pop()),'55e91D4D3D7/s//9eC0s00tBai72AA/âm5âtes/èr1/îm5îtes8r72AA9oC/55e8483/7DeDeDeB76e65ât6i46i367DeD5îtB7D8ssCn2s22t848327BDi4Di3DA/a9/4/3/8/i7en6Ass5e/4on3ez2Ai178s88t0Dai').split`/`[(n-=n>2,n-=n>5)+('0x'+'102433656777888A99CBC'[x*3+g])*6]+['sst'[~-n/2]])) ``` [Try it online!](https://tio.run/##VVLLjpswFN3PV9BR1WsPDxPeRIUoAVXqrtIsGapxiJM6IgZhQFEX/ZhZdTU/kQ9LMRm1HSH5cu7xORxfc6QjlVXH294UzY5d98kVjUZBjW2ZjJZsa94jgiwLfyTYOCTbFDpYOcvtZ@CAk7SwLOsxAXvhuJ4fQGmdaIvOSQpHRvqB8JqwumZENIMko1p4LeeWhJv5M3meNUgaYvJDH8QD@V5Q9oM3Q0msnskeUby6P8L9UuqgAdapjs6p8@n82V8d0sVqCrTcLmEi5jA6hFG83mT5FKZju6FiCLVGpbzrpH07UYWxdWy4QLXVNi3C2ADfZ/Ei93I3D4kkJGaZLW2731AeOus1ubyc/MvLFIdcfncLcnmd4OsEo07RcZORySDyIpeEOVPPJgxYoCQB9wLuBqqtJJswj6TMhCMdp1cCJ9zk3Mu5m68JjYlHXBIRHjIRrKX0GfEa4bKfzpovwkhGUW/ndBr93@kVSJiJSB1jLj7WEdhn0GFhO57rBn4QhmEURes4zjYZFOcHVz@U@CEo9QKk7KH4ZQrilCXGVzVsLdFGLUm1qhGyqZlVNwcESaKBpk@EPtUkeRJPQuE9GvHt8qihcaxkYJrz1gK@dUwy0YOhwddTy7o9q2bwyE9tzbSWyhl@GfqhY@ota8SO97wRtFbwTa/JYXscRNXzkb3zekeUBS/ncKZ5i0Zv1wsTwopQ9b8Wvrub/yzYUSFZB/gN7rng/9D0eSZ2Uzp8/QM "JavaScript (Node.js) – Try It Online") (regular verbs) [Try it online!](https://tio.run/##VVLLjpswFN3PV9BR1WsPDxPeRANRAqrUXaVZMlTjME7qiBiEAUVd9GNm1dX8RD4sxWT6GFnicu7xOTq@9oGOVFYdb3tTNM/ssksuaDQKamzLZLRkW/MeEWRZ@CPBxj7ZptDByllu74EDTtLCsqyHBOyF43p@AKV1pC06JSkcGOkHwmvC6poR0QySjOrDazm3JFzNn8jTrEHSEJMf@iDuyLeCsu@8GUpi9Uz2iOLV7QFul1IHDbBOdXRKnU@ne3@1TxerKdByu4SJmMPoEEbxepPlU5iOPQ8VQ6g1KuVdJ@3biSqMrUPDBaqttmkRxgb4PosXuZe7eUgkITHLbGnb/Yby0Fmvyfnl6J9fpjjk/KtbkPPrBF8nGHWKjpuMTAaRF7kkzJlamzBggZIE3Au4G6i2kmzCPJIyE450nF4JnHCTcy/nbr4mNCYecUlEeMhEsJbSZ8RrhMt@OGu@CCMZRb2d02n0f6dXIGEmInWMufhYR2CfQIeF7XiuG/hBGIZRFK3jONtkUJzuXH1f4rug1AuQsofipymIU5YYX9SwtUQbtSTVqkbIpmZW3ewRJIkGmj4R@lST5FE8CoV3aMTXy6OGxrGSgWnOWwv42jHJRA@GBl@OLet2rJrBAz@2NdNaKmf4eeiHjqm/rBHPvOeNoLWCb3pNDtvDIKqej@yd1zuiLHg5hzPNazR6vV6YEFaEqv@18M3N/LKATk@xA/wHjQ3/h3aUT8nw5Tc "JavaScript (Node.js) – Try It Online") (grammatical disaster using the irregular verbs suggested in the challenge) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~2051~~ 1891 bytes (UTF-8) ``` (.+)er$ je $1e0tu $1es0il $1e0elle $1e0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1ai0tu $1as0il $1a0elle $1a0nous $1âmes0vous $1âtes0ils $1èrent0elles $1èrent0je $1erai0tu $1eras0il $1era0elle $1era0nous $1erons0vous $1erez0ils $1eront0elles $1eront0je $1erais0tu $1erais0il $1erait0elle $1erait0nous $1erions0vous $1eriez0ils $1eraient0elles $1eraient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1asse0tu $1asses0il $1ât0elle $1ât0nous $1assions0vous $1assiez0ils $1assent0elles $1assent (.+i)r$ je $1s0tu $1s0il $1t0elle $1t0nous $1ssons0vous $1ssez0ils $1ssent0elles $1ssent0je $1ssais0tu $1ssais0il $1ssait0elle $1ssait0nous $1ssions0vous $1ssiez0ils $1ssaient0elles $1ssaient0je $1s0tu $1s0il $1t0elle $1t0nous avoîmes0vous avoîtes0ils $1rent0elles $1rent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1sse0tu $1sses0il $1sse0elle $1sse0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent0je $1sse0tu $1sses0il avoît0elle avoît0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent (.+)re$ je $1s0tu $1s0il fai0elle fai0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1is0tu $1is0il $1it0elle $1it0nous $1îmes0vous $1îtes0ils $1irent0elles $1irent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1isse0tu $1isses0il $1ît0elle $1ît0nous $1issions0vous $1issiez0ils $1issent0elles $1issent je ([aeiouh].+) j'$1 S`0 ``` To the point implementation. Will try to golf it down from here. [Try it online.](https://tio.run/##1ZRLSgNBEIb3fQoXIyYIYXIKD@BShAxYYoU4A92TIB4nK1dZegBzsLH6UY@WCEFc6CpVTc9X6b8/2sOIfbecLmc3q2m2uJ6Db9waLpoltOM2/oQWN6mFzSav98M2UDH0od3lEl5pUyr6Me3jOpE6DJkViwTrcGRcLAsQDREF2aGF5q5gC5WhgmTgcf8MQjzux3SWVL95Cy1tPrZnLlV8di/sWBY6eJuA1wxo3aSQOkEHYaPCNY3cyACsJqAZUafC/XkXdzrn01cXAnDKgYmUJDNjWai0wYJjq3dIH9tLTK0j3XDOupVgyggZIPgQDJy@Z3RNzl0GBkk7lwkcS4HnRgZgNQHNiDpt7s/4391uOB5EwtSphZWDaqAIKP6pfmqflU/dq9RT81Q89c5qZ62rpDPOfVHOGieSqCNxSVKGczL@9hq/sHOIGV7qn9CjfXMPJ@x7pPwTPRZ/5K1jKkOVqUgjWmzUM6xEw/9s2m@@bShqoXnbDvq2qVlYq4XWLazlym20anbXAQ7bp3sSza2vmqW7XbXTonFN@/E@dbTfOxIYvSPRPDh4wTDSGvY78CMt00U9ePgE) **Explanation:** Handle all words ending with `er`, with a `0` as line separator: ``` (.+)er$ je $1e0tu $1es0il $1e0elle $1e0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1ai0tu $1as0il $1a0elle $1a0nous $1âmes0vous $1âtes0ils $1èrent0elles $1èrent0je $1erai0tu $1eras0il $1era0elle $1era0nous $1erons0vous $1erez0ils $1eront0elles $1eront0je $1erais0tu $1erais0il $1erait0elle $1erait0nous $1erions0vous $1eriez0ils $1eraient0elles $1eraient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1asse0tu $1asses0il $1ât0elle $1ât0nous $1assions0vous $1assiez0ils $1assent0elles $1assent ``` Handle all words ending with `ir`, with `0` as line separator: ``` (.+i)r$ je $1s0tu $1s0il $1t0elle $1t0nous $1ssons0vous $1ssez0ils $1ssent0elles $1ssent0je $1ssais0tu $1ssais0il $1ssait0elle $1ssait0nous $1ssions0vous $1ssiez0ils $1ssaient0elles $1ssaient0je $1s0tu $1s0il $1t0elle $1t0nous avoîmes0vous avoîtes0ils $1rent0elles $1rent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1sse0tu $1sses0il $1sse0elle $1sse0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent0je $1sse0tu $1sses0il avoît0elle avoît0nous $1ssions0vous $1ssiez0ils $1ssent0elles $1ssent ``` Handle all words ending with `re`, with `0` as line separator: ``` (.+)re$ je $1s0tu $1s0il fai0elle fai0nous $1ons0vous $1ez0ils $1ent0elles $1ent0je $1ais0tu $1ais0il $1ait0elle $1ait0nous $1ions0vous $1iez0ils $1aient0elles $1aient0je $1is0tu $1is0il $1it0elle $1it0nous $1îmes0vous $1îtes0ils $1irent0elles $1irent0je $1rai0tu $1ras0il $1ra0elle $1ra0nous $1rons0vous $1rez0ils $1ront0elles $1ront0je $1rais0tu $1rais0il $1rait0elle $1rait0nous $1rions0vous $1riez0ils $1raient0elles $1raient0je $1e0tu $1es0il $1e0elle $1e0nous $1ions0vous $1iez0ils $1ent0elles $1ent0je $1isse0tu $1isses0il $1ît0elle $1ît0nous $1issions0vous $1issiez0ils $1issent0elles $1issent ``` Replace all `je` followed by a vowel or 'h' with `j'`: ``` je ([aeiouh].+) j'$1 ``` And finally split on zeroes, which basically replaces all `0`s with newlines: ``` S`0 ``` After which the result is output implicitly. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~488~~ 276 bytes ``` F⪪§⪪”}∨>↓⁷8lυW!M\ηX↨%]ν÷g×D\﹪3}Þ1Xζ÷S¹.m×K⦄}.}◧TI¡νυOA×∨´TE…8λ→Y×⁶⁰⟦αLi↓↶⎚⦃ω>◧‴κv≦|≕…K⊕Yλ⎇&✳⍘ςθA⪪@₂)¦Hg@»‽H2.⁵÷-⁸n¬u⊘¡″βEN≡x↔÷Wyⅈ(J\`﹪◨⁸||kU_ ←%Zσ¤«⊟Q§!χ⁰⸿¤:\`α´↖±↔5À⊗I¡o⊞⁵cp✳ιg«“/_$↖↧↧⪫,↗A”¶¶⌕er§θ±²¶F⁶F⎇›№aehiou§θ⁰κ⟦j'⟧⁺⪪§⪪”↶↥ζ⊟pW↔,⦄≡WA→÷⪫$Aⅉ⟦v⎇” 궦 «λ…θ⁻Lθ²⭆§⪪ι κ§⁺âèîμ⌕AEIμ⸿ ``` [Try it online!](https://tio.run/##jZTBbhMxEIbP9ClGvnRXChLiwIVTFBUUiaJK7Y1wsFI3meJ6U9tbtSBehhMnXiIPFv4ZezcBRdAoHnv9z878366T5drGZWf9bnfTRWouN55zM83zcO0e65Vx5BI56gLiV3IhL4LlRGVkYhEYiuWqkYVC0zvcNs0IZ1EFFyEhJAkYWjBKSSyrrlqNGZFLEmtWbVD9jH1L15QcSZCeslBZZnGGfUlaYCvRs0mwLV8IgsKCwgVFSAQEHIohFAVC3Q8hUwFQ//@0z2Kf1f48y6LIxT6P9veOUqoJBzpmqxn76Vit/9Kx4LHwIWDo7YLIhZGVbx9RonCygnIcO4xQw/IY1jPYzYSM8Jt2Qu84XONQRuwNB/V@Qh/dymbXvG7x0WTTtqRn@k2dr1wMNj4176NDZmxmXR9wuq1bc9f/WeyV1PiC8cncnprPE7rwfTr@47h1lHtij/fqvaPQ9YkeJLBPZS@JeTK1oikQsgGD305eXESGDd@@HZazp6V3s3W3ESfnHND5gwurvG7ucaMAjqmXGdPq3G7@csWHHQdJGcz2x/bn9hcs3Y2Pcno21@vDymYRDa6@43@B8b53Lx/8bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⪪§⪪”...”¶¶⌕er§θ±²¶ ``` A very long compressed string is split into paragraphs, each paragraph representing the endings for a particular verb ending. The appropriate ending is selected depending on the second last letter in the verb. The paragraph is split into lines representing the endings for each tense in turn. The tenses are then looped over. ``` F⁶ ``` Loop over the three persons and their plurals. ``` F⎇›№aehiou§θ⁰κ⟦j'⟧⁺⪪§⪪”↶↥ζ⊟pW↔,⦄≡WA→÷⪫$Aⅉ⟦v⎇” 궦 « ``` Loop over the pronouns for those persons (third person has two genders), but special-casing `["j'"]` where necessary. ``` λ ``` Print the pronoun. ``` …θ⁻Lθ² ``` Print the verb stem. ``` ⭆§⪪ι κ§⁺âèîμ⌕AEIμ ``` Print the suffix, but translate `AEI` to `âèî` as Charcoal can't compress accented letters. ``` ⸿ ``` Start a new line. ]
[Question] [ # Task You should write a program that when a button is pressed, it outputs a different sound for each key. The keys that you will use are: ``` 1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm ``` The notes begin at `C` and each key above adds one semitone. Lets make it slightly easier for you though. You can choose between 2 similar tasks, > > 1) Output a different note when a key is pressed that continues until another key is pressed. This program runs indefinitely > > > 2) Take a string as input that only contains the characters above that will output each note for exactly 1 second (0.05 second variation allowed) > > > # Input 1. A key being pressed 2. A single string containing only the symbols above # Output 1. A single musical note that sounds until another key is pressed 2. A series of notes, each one 1 second long # Notes ``` Letter | Note -------+------- 1 | C ! | C# 2 | D " | D# 3 | E 4 | F $ | F# 5 | G % | G# 6 | A ^ | A# 7 | B 8 | C * | C# 9 | D ( | D# 0 | E q | F Q | F# w | G W | G# e | A E | A# r | B t | C <-- middle C T | C# y | D Y | D# u | E i | F I | F# o | G O | G# p | A P | A# a | B s | C S | C# d | D D | D# f | E g | F G | F# h | G H | G# j | A J | A# k | B l | C L | C# z | D Z | D# x | E c | F C | F# v | G V | G# b | A B | A# n | B m | C ``` # Rules * You may choose between the tasks but please say which one in your answer * You are given a ±0.05 second variation in task 2 * Each symbol along increments the tone by 1 semitone. * The individual notes are shown above * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins This was originally taken from [here](https://codegolf.meta.stackexchange.com/a/12519/69279) with [caird coinheringaahing's](https://codegolf.meta.stackexchange.com/users/66833/caird-coinheringaahing) consent [Answer] # Python 3, ~~154~~ 140 bytes ``` from winsound import* for i in input():Beep(int(65.406*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.find(i)/12)),999) ``` I chose the second task type. The loop passes through each character and looks for the index of this element in the string. This index is the number of semitone up from Low C ('1'). Calculation of the desired frequency is made by this [formula](https://en.wikipedia.org/wiki/Equal_temperament#Calculating_absolute_frequencies). P.S. This [library](https://docs.python.org/3.4/library/winsound.html) works only in Windows. *-13 bytes thanks to ovs.* *-1 byte thanks to Jonathan Allan.* [Answer] # JavaScript (ES6), 247 or 230 bytes Decided to try out both options. Saved a few bytes thanks to @darrylyeo for suggesting the `with` statement. Thanks to @Кирилл Малышев for pointing out an issue with `.search()`. ## Option 1 - Keyboard Input, ~~252~~ ~~246~~ 247 bytes ``` _=>{c=new AudioContext;q=1;with(c.createOscillator())connect(c.destination),I.oninput=_=>(~(i='1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(I.value,I.value=""))&&(frequency.value=65.4*2**(i/12),q&&start(q=0)))} ``` ``` <input id=I ``` Relies on the input element receiving the actual letter typed, instead of character codes. Focus must be on the input box. ## Option 2 - String Input, ~~234~~ ~~229~~ 230 bytes ``` s=>{c=new AudioContext;with(c.createOscillator())connect(c.destination),[...s].map((c,i)=>frequency.setValueAtTime(65.4*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(c)/12),i)),start(),stop(s.length)} ``` Simply takes the string as the function parameter. ## Combined Snippet I suggest turning down your volume being running this, it can be loud. In order to stop playback, the snippet required adding `o=` inside each `with(c.createOscillator())`. ``` f= // keyboard input _=>{c=new AudioContext;q=1;with(o=c.createOscillator())connect(c.destination),I.oninput=_=>(~(i='1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(I.value,I.value=""))&&(frequency.value=65.4*2**(i/12),q&&start(q=0)))} g= // string input s=>{c=new AudioContext;with(o=c.createOscillator())connect(c.destination),[...s].map((c,i)=>frequency.setValueAtTime(65.4*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(c)/12),i)),start(),stop(s.length)} swap=_=>{keyboard=!keyboard;A.innerHTML=keyboard?"Keyboard":"String";S.style.display=keyboard?"none":"inline";window.c&&c.close();window.o&&o.stop();keyboard?f():I.oninput=null;I.value="";} keyboard=0; swap(); ``` ``` <span id="A"></span> Input:<br> <input id="I"> <button id="S" onclick="g(I.value)">Run</button><br> <button onclick="swap()">Swap</button> ``` [Answer] # [AHK](https://autohotkey.com/), 130 bytes ``` s=1!2"34$5`%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm Loop,Parse,1 SoundBeep,55*2**((InStr(s,A_LoopField,1)-10)/12),999 ``` I chose Option 2. Explanation: Storing the search string as the variable `s` was shorter than escaping that mess directly in the `SoundBeep` function. I had to escape the percent sign since that's an escape character for variable names but the rest of the string is OK as is. By default, the variable `1` is the first input parameter. Feeding that into a parsing loop without specifying a delimiter will result in each character in the input string being analyzed individually. `SoundBeep` takes in a frequency in Hz and a duration in milliseconds and plays that note for that long. The fun part was figuring out the right frequencies. Referencing the [piano key frequency table](https://en.wikipedia.org/wiki/Piano_key_frequencies) from Wikipedia and the formula on the same page, I found the shortest encoding was to use A1 as the reference note because it's frequency is the nice round 55 Hz. Since we want to start at C1, we have to adjust from A1 (the 13th note) to C1 (the 4th note). That, plus the fact that `InStr` is one-indexed, is why we subtract 10 from the result of the `InStr` function. ]
[Question] [ Given an non-negative integer \$n \ge 0\$, output forever the sequence of integers \$x\_i \ge 3\$ that are palindromes in exactly \$n\$ different bases \$b\$, where the base can be \$2 \le b le x\_i-2\$. This is basically the inverse of [OEIS A126071](https://oeis.org/A126071), where you output which indices in that sequence have the value \$n\$. It's a bit different, because I changed it so you ignore bases \$b = x\_i-1, \: x\_i, \: x\_i+1\$, since the results for those bases are always the same (the values are always palindromes or always not). Also, the offset is different. \$x\_i\$ is restricted to numbers \$\ge 3\$ so that the first term of the result for each \$n\$ is [A037183](https://oeis.org/A037183). Note that the output format is flexible, but the numbers should be delimited in a nice way. **Examples:** ``` n seq 0 3 4 6 11 19 47 53 79 103 137 139 149 163 167 ... 1 5 7 8 9 12 13 14 22 23 25 29 35 37 39 41 43 49 ... 2 10 15 16 17 18 20 27 30 31 32 33 34 38 44 ... 3 21 24 26 28 42 45 46 50 51 54 55 56 57 64 66 68 70 ... 4 36 40 48 52 63 65 85 88 90 92 98 121 128 132 136 138 ... 5 60 72 78 84 96 104 105 108 112 114 135 140 156 162 164 ... 10 252 400 420 432 510 546 600 648 784 800 810 816 819 828 858 882 910 912 1040 1056 ... ``` So for \$n=0\$, you get the output of [this challenge](https://codegolf.stackexchange.com/questions/91131/non-palindromic-numbers) (starting at \$3\$), because you get numbers that are palindromes in `n=0` bases. For \$n=1\$, \$5\$ is a palindrome in base \$2\$, and that's the only base \$2 \le b \le (5-2)\$ that it's a palindrome in. \$7\$ is a palindrome in base \$2\$, and that's the only base \$2 \le b \le (7-2)\$ that it's a palindrome in. Etc. --- Iff your language does not support infinite output, you may take another integer `z` as input and output the first `z` elements of the sequence, or all elements less than `z`. Whichever you prefer. Please state which you used in your answer if this is the case. [Related](https://codegolf.stackexchange.com/q/69707/34718) [Answer] # Mathematica, ~~80~~ 71 bytes *Thanks to JungHwan Min for saving 9 bytes!* ``` Do[#!=Length[i~IntegerReverse~Range[2,i-2]~Cases~i]||Echo@i,{i,3,∞}]& ``` (`∞` is the three-byte character U+221E.) Pure function taking a nonnegative integer as input. `i~IntegerReverse~Range[2,i-2]` creates a list of the reversals of the number `i` in all the bases from `2` to `i-2`; then `Length[...~Cases~i]` counts how many of these reversals are equal to `i` again. `#!=...||Echo@i` halts silently if that count is not equal to the input, and echoes `i` if it is equal to the input. That procedure is embedded in a straightforward infinite loop. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing). ``` ṄµbḊŒḂ€S’⁼³µ¡‘ß ``` **[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4bmEwrVi4biKxZLhuILigqxT4oCZ4oG8wrPCtcKh4oCYw5////8w "Jelly – TIO Nexus")** - the online interpreter will timeout at 60 seconds then flush it's output (unless it has a cached copy), offline it will print each in turn. ### How? Evaluates numbers from `n` up, printing them if they are in the sequence. Note that the first number in any output will be greater than `n` since otherwise the range of `b` is not great enough, so there is no need to seed the process with `3`. Also note that the number of palindromes from base **2** to **xi-2** inclusive is just one less than the number of palindromes from base **2** to **xi**. ``` ṄµbḊŒḂ€S’⁼³µ¡‘ß - Main link: n ¡ - repeat... Ṅ - ...action: print (the CURRENT n) µ µ - ...number of times: this monadic chain: Ḋ - deueue -> [2,3,4,...,n] b - n converted to those bases ŒḂ€ - is palindromic? for €ach S - sum: counts the 1s ’ - decrement: throw away the truthy base n-1 one ⁼³ - equals input: Does this equal the ORIGINAL n? ‘ - increment n ß - calls this link as a monad, with the incremented n. ``` [Answer] # Pyth, 21 19 18 bytes ``` .V3IqQlf_IjbTr2tbb ``` This should work in theory. It works properly if I substitute the infinite loop for any finite one (e.g. `JQFbr3 50*`bqJlf_IjbTr2tb` for 3 up to 50, try [here](http://pyth.herokuapp.com/?code=Fbr3+50IqQlf_IjbTr2tbb&input=0&debug=0)), but the Pyth interpreter doesn't know when or how to print literally infinite output. Explanation: ``` .V3IqQlf_IjbTr2tbb .V3 increase b infinitely, starting from 3 r2Tb range of integers including 2 to b - 2 lf length of elements retained if: jbT b in that base _I is invariant under reversal qQ check if the length is equivalent to the input I b output b if so ``` [Answer] # [Perl 6](https://perl6.org), 90 bytes ``` ->\n{->{$_=++($ //=2);$_ if n==grep {($/=[.polymod($^b xx*)])eq[$/.reverse]},2..$_-2}...*} ``` [Try it](https://tio.run/nexus/perl6#PU7dasIwFL7PU3yMMhpr0@QkaStSn2J36mSz2Sio7ayKUvrs7ihskMA53@859wGXXG3n4szTW@hPc7G/4XXb1gHVPV2sDkO6GKJNlSRxhCyrSM6jDZovHKrq@xg6DHGUVUvVtbvbvq3j6P0T1@tErmX4WUaZOoZLOPZhPU5JqWiT0qiUmoz3r/YogF1zCH0seVL7jy6eqG27/4yzVZ1k8okkE6l2TX@SQqQLxFg1h@58miIJ1y5sT6GGxMD2pk/rELrdDY/T46dKLt//ZetnyhR/@xQvw1M0olpg@IPHFzHeNQALhxzGwMzgCniLYgajLYwthGGBR4ESjBFDMA5EIAvygpg1GsbDcEIBU4I0qIDVsEZYpsmA2JGDSjiC83A5vIY3wj3KczgNV8ITcovco@THbVp4pnONglCUKB1mXKEdf27TpeBePoETNftJ/wI "Perl 6 – TIO Nexus") ``` -> \n { # sequence generator ->{ # using a code block with no parameter $_ = # set the default scalar to the value being tested ++( # preincrement $ # anonymous state variable //= 2 # initialized to 2 ); # the anonymous state var maintains its state # only for this current sequence # every time the outer block gets called it is created anew $_ # return the current value if # if the following is true n == grep # find all that match the following code { # convert the current value to the base being tested # store as an Array in $/ ($/ = [ .polymod($^b xx*) ] ) eq # is string equal to: (shorter than eqv) [ $/.reverse ] }, 2 .. $_ - 2 # from the list of bases to test } ... # keep using that code block to produce values * # indefinitely } ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~134~~ 132 bytes ``` for((x=3;;x++)){ c=$1 for((b=x-1;--b>1;)){ s=`bc<<<"for(y=$x;y;y/=$b)y%$b"` t=`tac<<<"$s"` [ "${s#$t}" ]||((c--)) } ((c))||echo $x } ``` [Try it online!](https://tio.run/nexus/bash#HYpBCsMgEEX3cwqxU3AIUmyX4/QipWCVlu4CNQslenabZPffe3985p8xRW7MZZqIVkiCDg4bpVjH1sa7471kCTF57/Veq2DhyvUiGKmeMeoAi4TldTwwb/hQGtd8wqVr9WzNmGQtEXTYFlFr7/SdFRboY4zrHw "Bash – TIO Nexus") Input is passed as an argument. The output is on stdout. If you run this normally, it will display one number at a time in the infinite sequence. If you try this in TIO, it will display as much of the output as it has generated when it times out at 60 seconds. [Answer] # Python 2, 132 bytes ``` B=lambda n,b:[]if(n<1)else B(n/b,b)+[n%b] n=input() x=3 while 1: if sum(B(x,b)==B(x,b)[::-1]for b in range(2,x-1))==n:print x x+=1 ``` [**Try it online**](https://tio.run/nexus/python2#JcyxDoIwEIDhmT7FLSZtgNjq1lAHXoMw9GKrF8tJCsS@PWKc/uXLv/cu@QnvHrhBO4wUJXdGhbQE6CWfsUFVD3zCUbAjnrdVKlHcVXyelAIYKyqKsGyT7GU5rHP/Dta2ZozvDAjEkD0/grw0pTXqMGznTLxCEVWpndl/j3IzWmuLOfjXrr8) The TIO program has a footer added so you don't have to wait 1 minute for the program to time out before seeing the output. ]
[Question] [ Given a string n, create a pyramid of the string split into pieces relative to the current row. The first row contains the string unmodified. The second row contains the string separated into halves by a pipe. The third row separates it by thirds... And so on. The length of each substring, where l is the length of string n is equal to floor(l/n) Characters left over are put in their own substring. The last row used is the first one where substrings are 2 in length. **Test Cases:** Input: Hello, world. Output: ``` Hello, world. Hello,| world|. Hell|o, w|orld|. Hel|lo,| wo|rld|. He|ll|o,| w|or|ld|. ``` --- Input: abcdefghij Output: ``` abcdefghij abcde|fghij abc|def|ghi|j ab|cd|ef|gh|ij ``` --- Input: 01234567890abcdef Output: ``` 01234567890abcdef 01234567|890abcde|f 01234|56789|0abcd|ef 0123|4567|890a|bcde|f 012|345|678|90a|bcd|ef 01|23|45|67|89|0a|bc|de|f ``` --- # Extra rules: * You can write a full program or a function, whichever uses less code. * Input will always be at least 4 characters in length. * You MUST use line breaks if your language supports them. If not possible, replace line breaks with `:` * Input will always be printable ASCII. * Minus 100% if your program solves P vs. NP. --- # Leaderboard: ``` var QUESTION_ID=104297,OVERRIDE_USER=62384;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Perl, 46 + 1 = 47 bytes Run with the `-n` flag ``` say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2 ``` [Try it online!](https://tio.run/nexus/perl#@1@cWKlQrK9XrWJbq2Fvq6epr6JWo59epFCekZmTqqFia1upr6@frK@traKjqWv0/7@BoZGxiamZuYWlQWJSckpq2n9dX1M9A0OD/7p5AA "Perl – TIO Nexus") ### Code breakdown ``` -n #Reads input into the $_ variable say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2 y///c #Transliteration. Implicitly operates on $_, replacing every character with itself and counting replacements #y///c effectively returns the length of $_ /++$, #Increments $, (which starts off at 0) and divides the length of $_ by $, $== #Stores the result of this division into $= #$= forces its contents to be an integer, so it truncates any decimal ( )-2 #Returns 0 if $= is equal to 2 while #Evaluates its RHS as the condition. If truthy, evaluates its LHS. s/ / /gr #Substitution. Implicitly operates on $_. #Searches for its first argument and replaces it with its second argument, repeating until it's done, and returns the new string. $_ is not modified. .{$=} #Looks for a string of $= characters... (?=.) #...that is followed by at least one non-newline character, but does not include this character in the match... $&| #...and replaces it with itself followed by a pipe character. say #Output the result of the substitution. ``` [Answer] ## Pyth, 16 bytes ``` Vh/lQ3j\|cQ/lQhN V # For N in range(1, \/ ) h/lQ3 # 1+lenght(input)/3 j\| # join with '|' cQ # chop input in /lQhN # lenght(input)/(N+1) pieces ``` [try here](https://pyth.herokuapp.com/?code=Vh%2FlQ3j%5C%7CcQ%2FlQhN&input=%2701234567890abcdef%27&debug=0) [Answer] ## C, ~~145~~ ~~131~~ ~~128~~ 125 bytes ``` l,n,i=1,j;f(char*s){l=strlen(s);puts(s);do{n=l/++i;for(j=0;j<l;)j&&(j%n||putchar('|')),putchar(s[j++]);puts("");}while(n>2);} ``` This is a function that takes a string as its argument and prints the output to STDOUT. ``` l,n,i=1,j; // declare some variables f(char*s){ // declare the function l=strlen(s); // get the length of the string puts(s); // output the initial version, with trailing newline do{n=l/++i; // n is the number of characters per "section", // and we'll do-while n>2 to stop at the right time for(j=0;j<l;) // loop through the characters of the string j&&( // if j != 0, j%n|| // and j % n == 0, putchar('|')), // insert a | before this character putchar(s[j++]); // print the character puts(""); // print a newline after the loop }while(n>2);} ``` [Answer] # Pyth, 17 bytes ``` jmj\|cQ/lQdSh/lQ3 ``` ### Explanation ``` cQ/lQ Divide into equal pieces (with the last shorter) j\| Join with pipes m d Map to each row index... Sh/lQ3 ... up to the first row with substrings of length 2 j Join with newlines ``` [Answer] # Javascript, 98 Bytes ``` a=>{for(b=1;2<=a.length/b;)eval("console.log(a.match(/.{1,"+(a.length/b|0)+"}/g).join('|'))"),b++} ``` Function `x(a)`. Call using `console.log(x("ABCDEF"))` [Answer] ## JavaScript (ES6), ~~103~~ ~~101~~ ~~91~~ 84 bytes *Fixed to respect challenge requirements* ``` f=(s,n=0,p=s.length/++n|0)=>p>1?s.match(eval('/.{1,'+p+'}/g')).join`|`+'\n'+f(s,n):'' ``` Lambda `f` that takes input string as first parameter `s` and recursively prints to console the split string. Pretty straightforward: as long as the substring length, `p`, is above 1, print the string split by a '|' every `p` characters, then proceed with appending the following level. This then calls the function again with `p` being `t / n` floored, where `t` is the original string length and `n` being an incremented divider. [Answer] # Python 3, 123 bytes ``` f=lambda s:print(*['|'.join(s[i:i+n]for i in range(0,len(s),n))for n in[len(s)//i for i in range(1,len(s)//2+1)]],sep='\n') ``` At longer strings some parts will be repeated, as the formula for the length of the substring is `floor(l/n)`. For example with a string 13 chars long, the string split into 5's would be the same as the string split into 6's as `floor(13/5)==floor(13/6)`. I'm not sure if the OP expected this or if it was an oversight. [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, 60 bytes ``` z= ~/$/ (z/3+1).times{|n|puts $_.scan(/.{1,#{z/(n+1)}}/)*?|} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWN22qbBXq9FX0uTSq9I21DTX1SjJzU4ura_JqCkpLihVU4vWKkxPzNPT1qg11lKur9DXygIpqa_U1texraiFmQI1asNYjNScnX0ehPL8oJ0UPIggA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` ₌LżḭvẇUṪ\|vj⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoxMxbzhuK124bqHVeG5qlxcfHZq4oGLIiwiIiwiMDEyMzQ1Njc4OTBhYmNkZWYiXQ==) 12 with `j` flag ## Explained ``` ₌LżḭvẇUṪ\|vj⁋ ₌Lż # Push len(input) and [1..len(input)] ḭ # Floor divide the length by each number in the range vẇ # And wrap the input into chunks of each length UṪ # Uniquify the list and remove the last item (which will be the input split into chunks of length 1) \|vj # Join each list on "|" ⁋ # And join that on newlines ``` ]
[Question] [ Given an expression, your task is to evaluate it. However, your answer cannot show more digits than necessary, as this gives the impression of having more precise measurements than reality. The number of significant figures that a number has is how many digits it has when written in scientific notation, including zeros at the end if a decimal point is present. For example, `1200` has 2 significant figures because it is `1.2*10^3` but `1200.` has 4 significant figures and `1200.0` has 5 significant figures. When adding two numbers, the result should be rounded to the same number of places as the number whose least significant digit is furthest to the left. For example, `1200 + 3 = 1200` (rounded to the hundreds place since 1200 is rounded to the hundreds place), `1200.01 + 3 = 1203`, and `4.59 + 2.3 = 6.9`. Note that `5` rounds up. This same rule applies to subtraction. `0` is rounded to the ones place. Note that adding and subtracting do not depend on the number of significant digits. For example, `999 + 2.00 = 1001` because 999 is rounded to the ones place and 2.00 is rounded to the hundredths place; the one rounded to fewer places is 999, so the result, 1001.00, should be rounded to the ones place as well. Similarly, 300 + 1 - 300 is exactly equal to 1, but 300 is rounded to the hundreds place, so the final result should also be rounded to the hundreds place, giving 0. 300. + 1 - 300. would equal 1 on the other hand. When multiplying or dividing two numbers, round to the number of significant digits of the number with the least significant digits. For example, `3.839*4=20` because the exact value, `15.356`, rounds to `20` since `4` has only one significant figure. Similarly, `100/4=30` since both numbers have one significant figure, but `100./4.00=25.0` since both numbers have 3 significant figures. `0` is defined to have 1 significant figure. Expressions will only contain `*`, `/`, `+`, and `-`, (and parentheses). Order of operations should be followed and results should be rounded after *every* operation. If parentheses are left out in a string of additions or subtractions or a string of multiplications and divisions, then round after all operations are completed. For example, `6*0.4*2 = 5` (one significant figure), while `0.4*(2*6)=0.4*10=4` and `(6*0.4)*2=2*2=4`. **Input**: A string, with an expression containing `()*/+-` and digits. To simplify things, `-` will only be used as a subtraction operator, not to signify negative numbers; answers, however, could still be negative and would require `-` as a prefix. **Output**: The result of the expression, evaluated and rounded to the correct number of digits. Note that `25` is incorrect for `25.0`. **Test cases**: ``` 3 + 0.5 --> 4 25.01 - 0.01 --> 25.00 4*7*3 --> 80 (4*7)*3 --> 90 (8.0 + 0.5)/(2.36 - 0.8 - 0.02) --> 5.7 6.0 + 4.0 --> 10.0 5.0 * 2.0 --> 10.0 1/(2.0 * (3.0 + 5.0)) --> 0.06 0.0020 * 129 --> 0.26 300 + 1 - 300 --> 0 0 - 8.8 --> -9 3*5/2*2 --> 20 ``` Edge case: Consider the problem of `501*2.0`. The exact value is `1002`. Printing `1002` gives too many significant figures (4, when we need 2) but `1000` gives too few (1, when we need 2). In this case, your program should print `1000` anyway. This source explains significant digits as well: <http://www.purplemath.com/modules/rounding2.htm> [Answer] # Java 11, ~~1325~~ ~~1379~~ ~~1356~~ ~~1336~~ 1290 bytes ``` import java.math.*;String c(String s)throws Exception{String r="",T=r,a[],b[],z="\\.";int i=0,l,A[],M=0,m=s.length(),j,f=0,q=m;if(s.contains("(")){for(;i<m;){var c=s.charAt(i++);if(f<1){if(c==40){f=1;continue;}r+=c;}else{if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){r+="x"+s.substring(i);break;}T+=c;}}return c(r.replace("x",c(T)));}else{for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length];i<l;f=b.length>1&&(j=b[1].length())>f?j:f)M=(j=(b=a[i++].split(z))[0].length())>M?j:M;for(b=a.clone(),i=0;i<l;A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++)for(q=(j=b[i].replace(".","").length())<q?j:q,j=a[i].split(z)[0].length();j++<M;)b[i]=0+b[i];double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+""),p;for(int x:A)m=x<m?x:m;m=m==M&R%1==0&(int)R/10%10<1&(j=(r=R+"").split(z)[0].length())>m?j-q>1?q:j:R>99?m:R%10==0?r.length()-1:m<1?1:m;R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue();r=(m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R)+"";l=r.length()-2;r=(r=f<1?r.replaceAll(z+"0$",""):r+"0".repeat(f)).substring(0,(j=r.length())<m?j:r.contains(".")?(j=r.replaceAll("^0\\.0+","").length())<m?m-~j:m+1:m);for(i=r.length();i++<l;)r+=0;return r.replaceAll(z+"$","");}} ``` +54 bytes to fix the edge case `501*2.0` (gave result `1002` before, but now correct `1000`). I now understand why this challenge was unanswered for almost two years.. >.> This challenge has more special cases than the Dutch language, which is saying something.. Java is certainly not the right language for these kind of challenges (or any codegolf challenge for that matter.. ;p), but it's the only language I know good enough to even attempt a difficult challenge like this. Input format as `String` without spaces (if that is not allowed, you can add `s=s.replace(" ","")` (+19 bytes) at the top of the method). [**Try it online.**](https://tio.run/##pVdtb9s4Ev7eX8EKtwEpyTT15tpWGCObNXA9rPcWdnqHQ5IFZIdO5JVkR5LTpEHu893fvD/SG1KiLSk9oLht0ZqiZp55ZoYzQ22ix6i3uf39a5zutnmJNvBM06i8p2aI4E@/j36NYH@7RuW9QMvnUvRW231WvlslUVGgWRRnL@8QKsqojFfo66LM4@wOrXC9KEh5n28/F2j6tBK7Mt5mL/WbnBuGfclzO7q6sZfw7ws3rq@pEcZZiWLO7MQ@h90ZrFJe0ERkd@U9JvbGXsPWA0/DeI0LutpmJXAosIENQl7W2xyH8WkakpfHKEcr0FzdR/l5iWPLIlJlfeqQF/hdce4zUOBOKDHibC/C19ziq/BVJIXQIs7JJc3FLolW4jxJsHH1G74xbMMgB0acdyVIR4K8AK7xZFgFLfbLQvmPYxIucxH9Hr5eKqOvuSj3eQahyzUcBh17hS8JITUp6V4EPhW7JC7B1PW1dX3du742@zcGsc95Jj4jiN9VwqPa@g1EIwnXfFk/nzknJ3jDl1fOzZHf2XqyGa/JjMMbvOTRFQTrpjbyhZAr1pSdgewslExAkq6SbSYgLZAxZen8Kr4B9PimkRlqkMmm2tQwPWesnpuBY@af2nGzZc6koQeOa/1DZGgnxKcPQOvB3kjyR@pN5uHGsk5nIZE4nFnyJ7zd7peJQHMVuJ/UA5ZLWQZPtFjl8a6kC/Uzze7iTMyiLLoTOSb0TtRbPz7/EqXA6C8L4CMeowQXxAJu9k4FSR7np/E5SfnTaTp5GqdhylPOZyfzHxzO2YkUIPO@w35w2Kkjc4NzPpcA3/SCnKWTTe/hzJk8jDfj@dloNEnHAMUAa5I345ueOhP4P6yc@zG@@0ms4hTozQnNoYRvlaczqPULyJR4KjGen7JJbz6eE1BNJQQhtArR36JkD2kOc47T09kJ3nGpSHfbz9hh9qwHkuDC2Xyi3MHz/o6YOwACP8KEN3i5EiLnUIWTvJn9L5bBqvSPc1ga8p2ISrwGCseiYTbEJ29kHYIxzjtHTYk0D9ZvDBoLs7onJgUf/7kZp5Z0tMpVAzuEwwfnmUDpsrCuzS7jijDU7leEdhAm6IB1I3zcxrcoBU51I7y6id52wnd1h70URYlWUSEKtM63qeq00LUSSUUg8QQms0hqjJVGCeLYcFzGLM@wkVoBC4kESw/1zpCLTpCPMGPMI/JZiiDsko4@Zc4BwmtAwL7UGrxF8RD2myg@DUaWSxXIgI5qjAEdjqSCBwCuQqKjjvnRSOoBcWmdMUdbhyXsauVAWpdiyr7kAnoEXgwUrcMbqYYWv04vPp7/jC7OF1OEc1HskxJV6UTRcvsooDXu9nqraLLxIJZOz6vo6GCyKgoOmPOkOUcaVlsQS6ejTit9qvzRzlDtx1HfqyCx19KnQ29k@lLXPaQyoF4wqNyuzbpdu@A27ft1FN2Aal03aAXQ12GSIh3TA5NR33QlQFBr@3So/Xa16aBjWSph1xwQqehrs@YAcTglWrsKnyKtzjmSWvDMwaX6kDp1XlvgWJEiFSsNrvZA1aX@kZ1COcC7pquxnbfY31dt5fFtIVbdovMsRoMmK48GLTZdV2TEnZ4sNJ2ido58XWJUHo86RaxbZOYHU1XYUCsPG07Wjg67hwODGqn0RloPtmQIh60QeY0Mecz0QGLEWhKjN9hD6KcQCtLHUPwDcHAonXTVcQjoB02zkgLAIQ3qjKswwaPsB3XamgjyANHAP3YPXTJNDVDvOwo3oIPBgFKKmuhAoNNtBkAEqqBqNocykcuWoixTECV1xfpUd5eqbP5Ih4G0mu73MQiODNw/ygD9/c//kNqTZteQSWMmhjZvSVsqaWBgcDjTal9mDbWTxppJY@ZQCTmDNx64Rw@G2oPB/@uBMuf0FQBHkqdub1jOikNTlW86zQ22mMtMxx1VLrraRVgGyrkPao5QOUuaSG4X6ZsD4nvHA@sN6VAq9vSAlButvtEbqRpcTGcfe@0IZeIOZv@jaM8rM@i7VX9sDIx2T2gPDd39prfQ5GR/a55N5hzP5vEuATHRZejXc5gguIu7h2EcVE4HehjrWQw9ecZ9G4GsjWY958whNiq2aClW2xQ6q7SCsKJyAVT@Z3/@iKLbWwEXqedCJOu3t5@a87fvPxUrT7N6ewNyTexYLrH8yvGD20rckp3Ia/fJ5qTxLDmMauET@Hucde0@6ZmqMVrYoSaGIU/g2lP1Sf/QzWshdbydwaGe9GE8Vh3oS1qD9ohr9G8w4jNpQQ5C@XOYszVcQxiQLZ81BP02Ivjx@k7lpXmpVY7V3/CqUm1UP8FFFSamuCXVxbbMn6sF0gJ1sXP4xlWaJGy/3@XyY4lXsJaB/vPvfyHDqrS0qP6kSriSPl7XE7iue0GoduFrGxlH9OeiFCnd7kuq3iYZrqTwe02Ziod9lBR1OyIT4@MvF3@dz6cXl2g@XXz6@fI9Wtxv98ktuo@gQy2FyICZ1h4bi08XF9PF4r1BaquvcILL1T0@XPaRIC9tPiLPD3yMT5kGQ7C/zVEVIQiGYdXhIGNpUuOr5Lx@/S8) ### Explanation: *Sorry for the long post.* ``` if(s.contains("(")){ for(;i<m;){ var c=s.charAt(i++); if(f<1){ if(c==40){ f=1; continue;} r+=c;} else{ if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){ r+="x"+s.substring(i); break;} T+=c;}} return c(r.replace("x",c(T)));} ``` This part is used for input containing parenthesis. It will get the separated parts and use recursive-calls. * `0.4*(2*6)` becomes `0.4*A`, where `A` is a recursive call to `c(2*6)` * `(8.3*0.02)+(1.*(9*4)+2.2)` becomes `A+B`, where `A` is a recursive call to `c(8.3*0.02)` and `B` a recursive call to `c(1.*(9*4)+2.2)` → which in turn becomes `1.*C+2.2`, where `C` is a recursive call to `c(9*4)` --- ``` for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length]; i<l; f=b.length>1&&(j=b[1].length())>f?j:f) M=(j=(b=a[i++].split(z))[0].length())>M?j:M; ``` This first loop is used to fill the values `M` and `k`, where `M` is the largest integer-length regarding significant figures and `k` the largest decimals-length. * `1200+3.0` becomes `M=2, k=1` (`12, .0`) * `999+2.00` becomes `M=3, k=2` (`999, .00`) * `300.+1-300.` becomes `M=3, k=0` (`300, .`) --- ``` for(b=a.clone(),i=0; i<l; A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++) for(q=(j=b[i].replace(".","").length())<q?j:q, j=a[i].split(z)[0].length(); j++<M;) b[i]=0+b[i]; ``` This second loop is used to fill the arrays `A` and `b` as well as value `q`, where `A` is the amount of significant figures, `b` hold the integers with leading zeroes to match `M`, and `q` is the lowest length disregarding dots. * `1200+3.0` becomes `A=[2, 5] (12, 00030)`, `b=[1200, 0003.0]`, and `q=2` (`30`) * `999+2.00` becomes `A=[3, 5] (999, 00200)`, `b=[999, 002.00]`, and `q=3` (both `999` and `200`) * `300.+1-300.` becomes `A=[3, 3, 3] (300, 001, 300)`, `b=[300., 001, 300.]`, and `q=1` (`1`) * `501*2.0` becomes `A=[3, 4] (501, 0020)`, `b=[501, 002.0]`, and `q=2` (`20`) --- ``` double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+"") ``` Uses a JavaScript engine to eval the input, which will be saved in `R` as double. * `1200+3.0` becomes `R=1203.0` * `999+2.00` becomes `R=1001.0` * `300.+1-300.` becomes `R=1.0` --- ``` for(int x:A) m=x<m?x:m; ``` This sets `m` to the smallest value in the array `A`. * `A=[2, 5]` becomes `m=2` * `A=[3, 5]` becomes `m=3` * `A=[3, 3, 3]` becomes `m=3` --- ``` m=m==M // If `m` equals `M` &R%1==0 // and `R` has no decimal values (apart from 0) &(int)R/10%10<1 // and floor(int(R)/10) modulo-10 is 0 &(j=(r=R+"").split(z)[0].length())>m? // and the integer-length of R is larger than `m`: j-q>1? // If this integer-length of `R` minus `q` is 2 or larger: q // Set `m` to `q` instead : // Else: j // Set `m` to this integer-length of `R` :R>99? // Else-if `R` is 100 or larger: m // Leave `m` the same :R%10==0? // Else-if `R` modulo-10 is exactly 0: r.length()-1 // Set `m` to the total length of `R` (minus the dot) :m<1? // Else-if `m` is 0: 1 // Set `m` to 1 : // Else: m; // Leave `m` the same ``` This modifies `m` based on multiple factors. * `999+2.00 = 1001.0` & `m=3,q=3` becomes `m=4` (because `m==M` (both `3`) → `R%1==0` (`1001.0` has no decimal values) → `(int)R/10%10<1` (`(int)1001.0/10` becomes `100` → `100%10<1`) → `"1001".length()>m` (`4>3`) → `"1001".length()-q<=1` (`4-3<=1`) → so `m` becomes the length of the integer-part `"1001"` (`4`)) * `3.839*4 = 15.356` & `m=1,q=1` stays `m=1` (because `m==M` (both `1`) → `R%1!=0` (`15.356` has decimal values) → `R<=99` → `R%10!=0` (`15.356%10==5.356`) → `m!=0` → so `m` stays the same (`1`)) * `4*7*3 = 84.0` & `m=1,q=1` stays `m=1` (because `m==M` (both `1`) → `R%1==0` (`84.0` has no decimal values) → `(int)R/10%10>=1` (`(int)84/10` becomes `8` → `8%10>=1`) → `R<=99` → `R%10!=0` (`84%10==4`) → `m!=0` → so `m` stays the same (`1`)) * `6.0+4.0 = 10.0` & `m=2,q=2` becomes `m=3` (because `m!=M` (`m=2, M=1`) → `R<=99` → `R%10==0` (`10%10==0`) → so `m` becomes the length of the total `R` (minus the dot) `"10.0".length()-1` (`3`)) * `0-8.8 = -8.8` & `m=0,q=1` becomes `m=1` (because `m!=M` (`m=0, M=1`) → `R<=99` → `R%10!=0` (`-8.8%10==-8.8`) → `m<1` → so `m` becomes `1`) * `501*2.0 = 1001.0` & `m=3,q=2` becomes `m=2` (because `m==M` (both `3`) → `R%1==0` (`1001.0` has no decimal values) → `(int)R/10%10<1` (`(int)1001.0/10` becomes `100` → `100%10<1`) → `"1001".length()>m` (`4>3`) → `"1001".length()-q>1` (`4-2>1`) → so `m` becomes `q` (`2`)) --- ``` R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue(); ``` Now `R` is rounded based on `m`. * `1001.0` & `m=4` becomes `1001.0` * `0.258` & `m=3` becomes `0.26` (because `abs(R)<1`, `m-1` (`2`) instead of `m=3` is used inside `MathContext`) * `-8.8` & `m=1` becomes `-9.0` * `1002.0` & `m=2` becomes `1000.0` --- ``` m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R; ``` This modifies the integer part of `R` if necessary. * `300.+1-300. = 1.0` & `m=3,M=3` stays `1.0` (because `m>=M` → so `R` stays the same (`1.0`)) * `0.4*10 = 4.0` & `m=1,M=2` stays `4.0` (because `m<M` → `(10^(M-m))/10<=R` (`(10^1)/10<=4.0` → `10/10<=4.0` → `1<=4.0`) → so `R` stays the same (`4.0`)) * `300+1-300 = 1.0` & `m=1,M=3` becomes `0.0` (because `m<M` → `(10^(M-m))/10>R` (`(10^2)/10>1.0` → `100/10>1.0` → `10>1.0`) → so `R` becomes `0.0` because of `int(R/(10^(M-m)))*(10^(M-m))` (`int(1.0/(10^2))*(10^2)` → `int(1.0/100)*100` → `0*100` → `0`) --- ``` r=(...)+""; // Set `R` to `r` as String (... is the part explained above) l=r.length()-2; // Set `l` to the length of `R` minus 2 r=(r=k<1? // If `k` is 0 (no decimal values in any of the input-numbers) r.replaceAll(z+"0$","") // Remove the `.0` at the end : // Else: r+"0".repeat(f) // Append `k` zeroes after the current `r` ).substring(0, // Then take the substring from index `0` to: (j=r.length())<m? // If the total length of `r` is below `m`: j // Leave `r` the same :r.contains(".")? // Else-if `r` contains a dot (j=r.replaceAll("^0\\.0+","").length())<m? // And `R` is a decimal below 1, // and its rightmost decimal length is smaller than `m` m-~j // Take the substring from index 0 to `m+j+1` // where `j` is this rightmost decimal length : // Else: m+1 // Take the substring from index 0 to `m+1` : // Else: m); // Take the substring from index 0 to `m` ``` This sets `R` to `r` as String, and modifies it based on multiple factors. * `1203.0` & `m=4,k=2` becomes `1203.` (because `k>=1` → so `r` becomes `1001.000`; `r.length()>=m` (`8>=4`) → `r.contains(".")` → `r.length()>=m` (`8>=4`) → substring from index `0` to `m+1` (`5`)) * `6.9` & `m=2,k=2` stays `6.9` (because `k>=1` → so `r` becomes `6.900`; `r.length()>=m` (`5>=2`) → `r.contains(".")` → `r.length()>=m` (`5>=2`) → substring from index `0` to `m+1` (`3`)) * `1.0` & `m=3,k=0` becomes `1` (because `k<1` → so `r` becomes `1`; `r.length()<m` (`1<3`) → substring from index `0` to `r.length()` (`1`)) * `25.0` & `m=4,k=4` becomes `25.00` (because `k>=1` → so `r` becomes `25.00000`; `r.length()>=m` (`8>=4`) → `r.contains(".")` → `r.length()>+m` (`8>=4`) → substring from index `0` to `m+1` (`5`)) * `0` & `m=1,k=0` stays `0` (because `k<1` → so `r` stays `0`; `r.length()>=m` (`1>=1`) → `!r.contains(".")` → substring from index `0` to `m` (`1`)) --- ``` for(i=r.length();i++<l;) r+=0; ``` This puts trailing zeroes back again to the integer part if necessary. * `r="12"` & `R=1200.0` becomes `r="1200"` * `r="1"` & `R=10.0` becomes `r="10"` * `r="8"` & `R=80.0` becomes `r="80"` --- ``` return r.replaceAll(z+"$",""); ``` And finally we return the result, after we've removed any trailing dots. * `1203.` becomes `1203` * `5.` becomes `5` --- Can definitely be golfed by a couple hundred bytes, but I'm just glad it's working now. It already took a while to understand each of the cases and what was being asked in the challenge. And then it took a lot of trial-and-error, testing and retesting to get to the result above. And while writing this explanation above I was able to remove another ±50 bytes of unused code.. ]
[Question] [ I have a list, `l` and a function `f`. `f` is not strictly increasing or decreasing. How can I find the item in the list whose `f(item)` is the smallest? For example, let's say the list is: ``` l = [1, 2, 3, 4] ``` and `list(f(x)for x in l)` is: ``` [2, 9, 0, 3] ``` `f(3)` is smaller than f of any of the other ones, so it should print "3". What's the shortest way to do this? I initially tried: ``` min(f(x) for x in l) ``` But this gives `0`, not `3`. If I was shooting for readability, not brevity, I would do: ``` index = 0 smallest = f(l[0]) for i in range(len(l)): value = f(l[i]) if value < smallest: smallest = value index = i ``` This is fine, but horrendous for code-golf. Even if it was golfed ``` i,s=0,f(l[0]) for x in range(len(l)): v=f(l[x]) if v<s:s,i=v,x ``` This is a bad solution. The shortest solution I can think of is: ``` g=[f(x)for x in l];print(l[g.index(min(g))]) ``` (44 bytes) How can I golf this down further? [Answer] ## Use `key` property of `min` As @vaultah said, use `min(l,key=f)`. `min(l,key=f)` takes the minimum of `f(i)` for `i` in `l`. It is also possible to apply this to `max`, and `sorted`. For example, `max(l,key=f)` is the maximum of `f(i)` for `i` in `l`. For `sorted`, the usage would be: `sorted(l,key=f)`. ]
[Question] [ When I was a child, I used to play this game a lot. ### Rules There are two players (let's call them A and B), and each player uses his hands as guns. There are three possible moves: 1. Hands up to load ammunition to your gun. Each gun starts empty. Loading increases the ammunition by one. 2. Hands pointing to the other player to shoot. This decreases the ammunition by one. You must have at least one unit of ammo to shoot. 3. Crossed arms to protect yourself from a shot. Both players move simultaneously. If both players shoot at the same time, the bullets hit each other, and the game continues. The game ends when one player shoots while the other is loading ammunition. Shooting and empty gun is considered *cheating*. If a player cheats while the other one performs a legal action, the cheater loses immediately. If both players cheat at the same time, the game continues. Cheating attempts do not decrease ammunition, so it can never be negative. ### Challenge Given the moves made by players A and B, output which player won the game: `1` for player A, `-1` for player B, and `0` for a draw. You can use any other triple of return values, but you need to state in your answer which ones you use. The game may: * end without having to process all moves; * not end with the given moves, and thus it is considered a draw. The input can be taken: * as strings * as arrays/lists of integers * in any other way that does not pre-process the input Full program or functions allowed. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins! ### Test cases ``` A: "123331123" B: "131122332" -----^ Player B shoots player A and wins. Output: -1 ``` ``` A: "111322213312" B: "131332221133" -------^ Player B cheats and loses. Output: 1 ``` ``` A: "1333211232221" B: "1213211322221" ----------^^ Both players cheat at the same time. The game continues. Output: 0 ``` ``` A: "12333213112222212" B: "13122213312232211" | || ^---- Player A shoots player B and wins. ^-------^^------ Both players cheat at the same time. The game continues. Output: 1 ``` [Answer] # Jelly, ~~33~~ ~~32~~ 24 bytes ``` Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ ``` This prints **5** instead of **-1**, and **7** instead of **1**. [Try it online!](http://jelly.tryitonline.net/#code=WsOmJTEuwrswJCvCpVw-LeKAmMW8WuG4hTNGZjUsN-G4og&input=&args=W1sxLCAyLCAzLCAzLCAzLCAxLCAxLCAyLCAzXSwgWzEsIDMsIDEsIDEsIDIsIDIsIDMsIDMsIDJdXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=WsOmJTEuwrswJCvCpVw-LeKAmMW8WuG4hTNGZjUsN-G4ogpEw4figqw&input=&args=WzEyMzMzMTEyMywgMTMxMTIyMzMyXSwgWzExMTMyMjIxMzMxMiwgMTMxMzMyMjIxMTMzXSwgWzEzMzMyMTEyMzIyMjEsIDEyMTMyMTEzMjIyMjFdLCBbMTIzMzMyMTMxMTIyMjIyMTIsIDEzMTIyMjEzMzEyMjMyMjExXQ). ### How it works ``` Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ Main link. Argument: A (digit list array) Z Zip; group corresponding digits. æ%1. Map the digits in (-1.5, 1.5]. This replaces [1, 2, 3] with [1, -1, 0]. \ Cumulatively reduce the pairs by doing the following. »0$ Take the maximum of the left value and 0, i.e., replace a -1 with a 0. +¥ Add the modified left value to the right value. This computes the available ammo after each action. An ammo of -1 indicates a cheating attempt. >- Compare the results with -1. ‘ Increment. And unilateral cheating attempt is now [1, 2] or [2, 1], where 1 signals the cheater and 2 the winner. żZ Pair each result with the corr., original digits. ḅ3 Convert each pair from base 3 to integer. This maps [1, 2] and [2, 1] to 5 and 7. F Flatten the resulting, nested list. f5,7 Discard all but 5's and 7's. Ḣ Grab the first element (5 or 7). If the list is empty, this returns 0. ``` [Answer] # Pyth, ~~48~~ ~~46~~ ~~49~~ 47 bytes ``` .xhfT|M.e,-FmgF.b/<dhkY2S2Q?}b_BS2-FbZ.b,NYCQ)0 ``` [Try it here!](http://pyth.herokuapp.com/?code=.xhfT%7CM.e%2C-FmgF.b%2F%3CdhkY2S2Q%3F%7Db_BS2-FbZ.b%2CNYCQ%290&input=%5B%5B1%2C+2%2C+3%2C+3%2C+3%2C+1%2C+1%2C+2%2C+3%5D%2C%5B1%2C+3%2C+1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+2%5D%5D&test_suite=1&test_suite_input=%5B%5B1%2C+2%2C+3%2C+3%2C+3%2C+1%2C+1%2C+2%2C+3%5D%2C+%5B1%2C+3%2C+1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+2%5D%5D%0A%5B%5B1%2C+1%2C+1%2C+3%2C+2%2C+2%2C+2%2C+1%2C+3%2C+3%2C+1%2C+2%5D%2C+%5B1%2C+3%2C+1%2C+3%2C+3%2C+2%2C+2%2C+2%2C+1%2C+1%2C+3%2C+3%5D%5D%0A%5B%5B1%2C+3%2C+3%2C+3%2C+2%2C+1%2C+1%2C+2%2C+3%2C+2%2C+2%2C+2%2C+1%5D%2C+%5B1%2C+2%2C+1%2C+3%2C+2%2C+1%2C+1%2C+3%2C+2%2C+2%2C+2%2C+2%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+3%2C+3%2C+2%2C+1%2C+3%2C+1%2C+1%2C+2%2C+2%2C+2%2C+2%2C+2%2C+1%2C+2%5D%2C+%5B1%2C+3%2C+1%2C+2%2C+2%2C+2%2C+1%2C+3%2C+3%2C+1%2C+2%2C+2%2C+3%2C+2%2C+2%2C+1%2C+1%5D%5D&debug=0) Thanks to @isaacg for saving ~~2~~ 4 bytes! Takes input as a 2-tuple with the list of the moves of player A first and the moves of player B second. Output is the same as in the challenge. ## Explanation ### Short overview * First we group the moves of both players together, so we get a list of 2-tuples. * Then we map each of those tuples to another 2-tuple in the form `[cheating win, fair win]` with the possible values `-1, 0, 1` for each of it, to indicate if a player won at this point (`-1, 1`) or if the game goes on (`0`) * Now we just need to get the first tuple which is not `[0,0]`, and take the first non-zero element of it which indicates the winner ### Code breakdown ``` .xhfT|M.e,-FmgF.b/<dhkY2S2Q?}b_BS2-FbZ.b,NYCQ)0 # Q = list of the move lists .b,NYCQ # pair the elements of both input lists .e # map over the list of pairs with # b being the pair and k it's index m Q # map each move list d .b 2S2 # map over [1,2], I can't use m because it's # lambda variable conflicts with the one from .e <dhk # d[:k+1] / Y # count occurences of 1 or 2 in this list -F # (count of 1s)-(count of 2s), indicates cheating win ?}b_BS2 # if b is (1,2) or (2,1) -Fb # take the difference, indicates fair win Z # else 0, no winner yet , # pair those 2 values |M # For each resulting pair, take the first one if # its not zero, otherwise the second one fT # filter all zero values out .xh # try to take the first value which indicates the winner )0 # if thats not possible because the list is empty # output zero to indicate a draw ``` [Answer] # Python, 217 bytes ``` def f(A,B): x=y=0;c=[-1,1,0] for i in range(len(A)): a=A[i];b=B[i] for s in[0,1]: if(a,b)==(2,1):return c[s]*c[x<1] if(a,b)==(2,3)and x<1:return-c[s] x-=c[a-1];x+=x<0;a,b,x,y=b,a,y,x return 0 ``` **Explanation**: Takes A and B as lists of integers. Simply goes through each pair of moves, adds or subtracts 1 if needed and returns when someone cheats or wins. Does the same thing twice using another for loop, once for A's move and once for B's move. Adds 1 if x goes below 0 to -1. [Answer] ## Java, ~~226~~ ~~212~~ ~~200~~ ~~196~~ 194 bytes *-14 bytes by re-ordering logic* *-12 bytes thanks to [Mr Public](https://codegolf.stackexchange.com/users/47302/mr-public) pointing out how to use a ternary operation for the shooting logic* *-4 bytes by cramming load logic into one short-circuiting if* *-2 bytes because `==1` === `<2` when input can only be `1`,`2`,`3`* ``` (a,b)->{for(int m=0,n=0,w,v,r=0,i=0,x;i<a.length;){w=a[i];v=b[i++];x=w==2?m<1?r--:m--:0;x=v==2?n<1?r++:n--:0;if(r!=0)return r;if(w<2&&++m>0&v==2)return -1;if(v<2&&++n>0&w==2)return 1;}return 0;} ``` Usage and indented version: ``` static BiFunction<Integer[], Integer[], Integer> game = (a,b) -> { for(int m=0,n=0,w,v,r=0,i=0,x;i<a.length;) { w=a[i];v=b[i++]; // shoot x=w==2?m<1?r--:m--:0; x=v==2?n<1?r++:n--:0; if(r!=0)return r; // load if(w<2&&++m>0&v==2)return -1; if(v<2&&++n>0&w==2)return 1; } return 0; }; public static void main(String[] args) { System.out.println(game.apply(new Integer[] {1,2,3,3,3,1,1,2,3}, new Integer[] {1,3,1,1,2,2,3,3,2})); System.out.println(game.apply(new Integer[] {1,1,1,3,2,2,2,1,3,3,1,2}, new Integer[] {1,3,1,3,3,2,2,2,1,1,3,3})); System.out.println(game.apply(new Integer[] {1,3,3,3,2,1,1,2,3,2,2,2,1}, new Integer[] {1,2,1,3,2,1,1,3,2,2,2,2,1})); } ``` Not so straightforward implementation of the game rules anymore, but simple. Each cycle, does these operations: * Load moves into temp variables * If player shot + without ammo: bias cheate`r` towards losing + with ammo: decrement ammo * If cheate`r` is not `0`, return the value because someone cheated * If player reloaded + increment ammo + if other player shot, return loss `x` is a dummy variable used to make the compiler let me use a ternary expression. [Wait, Java is SHORTER than Python?](https://codegolf.stackexchange.com/a/76152/51825) ]
[Question] [ ### Introduction [I Ching](https://en.wikipedia.org/wiki/I_Ching) is an ancient divination text and the oldest of the Chinese classics. It uses a type of divination called cleromancy, which produces apparently random numbers. The basic unit of the Zhou yi is the [hexagram](https://en.wikipedia.org/wiki/List_of_hexagrams_of_the_I_Ching) (卦 guà), a figure composed of six stacked horizontal lines (爻 yáo). Each line is either broken or unbroken. The received text of the Zhou yi contains all 64 possible [hexagrams](https://en.wikipedia.org/wiki/List_of_hexagrams_of_the_I_Ching) The [King Wen sequence](https://en.wikipedia.org/wiki/King_Wen_sequence) present the 64 hexagrams, grouped into 32 pairs. For 28 of the pairs, the second hexagram is created by turning the first upside down (i.e. 180° rotation). The exception to this rule is for symmetrical hexagrams that are the same after rotation. Partners for these are given by inverting each line: solid becomes broken and broken becomes solid. > > > ``` > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ > ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ > 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 > > ``` > > ### Request The goal of this is to create a little tool that compute pair for a given hexagram value. * For translating this into binary, I use: `broken line = 0, unbroken line = 1`, so *`hexagram Number 1`* has *`binary value 63`*. * The tool take exactly one argument, a number between 1 to 64, as hexagram pair request and produce two exagram containing requested number and his *oposite* (explanation: if arg is odd, the output must contain hexagram from *arg* and *arg + 1*, but if arg is even, the output must contain hexagram from *arg - 1* and *arg*). * The tool have to *rotate* by 180° requested hexagram while **not symetric**, **or** invert them when **symetric**. * No map are authorized except this one, wich could be stored in any form you'll find usefull ``` { 1:63, 3:34, 5:58, 7:16, 9:59, 11:56, 13:47, 15: 8, 17:38, 19:48, 21:37, 23: 1, 25:39, 27:33, 29:18, 31:14, 33:15, 35: 5, 37:43, 39:10, 41:49, 43:62, 45: 6, 47:22, 49:46, 51:36, 53:11, 55:44, 57:27, 59:19, 61:51, 63:42 } ``` This map hold *binary* value of each 1st exagram from pairs. So for each pair, 1st has to be taken from this map, but second have to be computed conforming to previous rule. * Ouput must contain two hexagram and his numbers. Sample: ``` iChingHexaPair 1 ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ 1 2 iChingHexaPair 14 ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ 13 14 ``` * Standard loophole applies * Please avoid non-free language or post output for full test cases. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in **characters** wins. ### Shortest by language ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = document.referrer.split("/")[4]; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 0; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//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 "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Python 2, ~~65~~ 61 Generates unicode I-Ching hexagram pairs ``` def t(a): b=a+a%2 for c in b-1,b: print unichr(19903+c),c ``` (saved 4 thanks to @Sherlock9) Example input and output: ``` >>> t(1) ䷀ 1 ䷁ 2 >>> t(14) ䷌ 13 ䷍ 14 ``` [Answer] # Python 2, ~~252~~ ~~245~~ 244 Now including binary computation (saving 8 chars thanks to @Sherlock9): ``` d='?":\x10;8/\x08&0%\x01\'!\x12\x0e\x0f\x05+\n1>\x06\x16.$\x0b,\x1b\x133*' k=lambda l:'\n'.join("{:06b}".format(l)).replace('1',u'▄▄▄▄▄▄▄').replace('0',u'▄▄▄ ▄▄▄') def t(a): j=a+a%2-1;m=ord(d[j/2]);b=k(m);r=b[::-1];print b,j,'\n\n',r if r!=b else k(63-m),j+1 ``` Example input and output: ``` >>> t(1) ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ 1 ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ 2 >>> t(3) ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ 3 ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ 4 ``` [Answer] # Pure bash 252 ``` u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s:1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>>1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2] ``` with 2 more linebreak: ``` u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s :1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>> 1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2] ``` Tests: ``` for k in 1 15 28 34;do set -- $k;echo request: $k; u=(▅▅▅{' ',▅}▅▅▅);m=_yWgXUL8CMB1Dxief5HaN@6mKAbIrjPG;s=$[($1-1)/2];r=$[64#${m:s :1}];for i in {0..5};do echo ${u[(r>>i)&1]} ${u[((r>>5)%2==r%2)&((r>>4)%2==(r>> 1)%2)&((r>>3)%2==(r>>2)%2)?1^(r>>i)&1:(r>>(5-i))&1]};done;echo $[s*2+1] $[s*2+2] done;echo $[s*2+1] $[s*2+2]; done request: 1 ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ 1 2 request: 15 ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ 15 16 request: 28 ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ 27 28 request: 34 ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ ▅▅▅ ▅▅▅ ▅▅▅▅▅▅▅ 33 34 ``` ]
[Question] [ When dealing with long numbers when code golfing, getting the length of your code down can be difficult, so do you have any tips for making a number shorter and easier to manage? For example, the following Pyth code prints "Hello world", but at 44 bytes, that is unsatisfactory: ``` Vcjkj85942000775441864767076 2 7=k+kCiN2)k ``` So how would I shorten the long number, `85942000775441864767076`? [Answer] Perfect timing for this question. @isaacg just added a new feature today, that allows to shorten such numbers immensely. The basic technique is to convert the number to base 256 and convert it to chars. You can do this using the code [`++NsCMjQ256N`](http://pyth.herokuapp.com/?code=%2B%2BNsCMjQ256N&input=85942000775441864767076&debug=0). You can then use the resulting string in combination with `C`, which does exactly the opposite (convert chars to int and interpret the result as base-256 number). So you get 13 chars: [`C"2ìÙ½}ü¶d"`](https://pyth.herokuapp.com/?code=C%22%122%C3%AC%C3%99%C2%BD%07%7D%C3%BC%C2%B6d%22&debug=0). Some of the chars are unprintable. But notice that I said 13 CHARS, not bytes. If I copy the chars and count the with <https://mothereff.in/byte-counter>, it says 13 chars and 18 bytes. This is due the character encoding of chars, which is UTF-8 by default. And UTF-8 only allows 2^7 different 1-byte character. Every char `c` with `ord(c) > 127` actually gets stored using two bytes instead of one. And here come's @isaacg's new [feature](https://github.com/isaacg1/pyth/commit/2e86169ad3bde67d40bfe1a831d1a9b469f28e44) into play. He changed the default code-format from UTF-8 to iso-8859-1. iso-8859 can represent 256 characters with only 1 byte. So now you can actually reach 13 BYTES. This is only possible with the [standard compiler](https://github.com/isaacg1/pyth) though, this doesn't work in the online compiler. First you want to convert the number to hex-values by using this script: [`jdm.[2.Hd"0"jQ256`](http://pyth.herokuapp.com/?code=jdm.[2.Hd%60ZjQ256&input=85942000775441864767076&debug=0). This gives you `12 32 ec d9 bd 07 7d fc b6 64`. Afterwards copy those numbers into your code-file using a hex-editor (e.g. hexedit for linux). [![hexedit demonstration](https://i.stack.imgur.com/ecJ4F.png)](https://i.stack.imgur.com/ecJ4F.png) Notice: * Obviously you remove the `"` at the end, if the string is the last part of the code. * This only works if there is no `34` (the byte `22`) in the base-256 representation of you numbers, since this is the `"` char and will end the string. Escaping works though (`5C 22`). * Btw, when you open a file with a hex-editor you will likely see the byte `0A` or `0d 0a` at the end, which you can remove. This only indicates the end of the line. ]
[Question] [ Write a function (such as `placeAt`) that takes an array of non-negative integers and an index that is a non-negative integer. It should place a 1 at the given index, possibly shifting other entries by one spot to vacate that spot, with 0's standing for empty spots. * If the entry at the desired index is 0, fill it with a 1. * Otherwise, look for the nearest 0 to the left of the index. Shift entries one spot left into that 0 to make room, then fill the index with a 1. * If there's no 0 to the left, do the same going right. * If neither is possible (i.e. if there is no 0), return the array unchanged. The items are 0-indexed. Function name can be anything you want. Examples: (Letters stand for any positive integer values.) ``` [a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, c, d, 0] place 2 is 0, just fill [a, b, 0, c, d, 0] placeAt 3 // output [a, b, c, 1, d, 0] place 3 is filled, shift items left [a, b, 0, c, d, 0] placeAt 0 // output [1, a, b, c, d, 0] place 0 is filled, can't shift left, shift items right [a, b, 0, c, d, 0] placeAt 1 // output [a, 1, b, c, d, 0] place 1 is filled, can't shift left, shift items right [0, a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, 0, c, d, 0] place 2 is filled, shift items left [0, a, b, 0, c, d, 0] placeAt 4 // output [0, a, b, c, 1, d, 0] place 4 is filled, shift items left (notice you keep shifting up until a 0) [0, 2, 0, 2] placeAt 3 // output [0, 2, 2, 1] place 3 is filled, shift items left ``` This is a code golf challenge. The shortest entry at the end of 9 days wins. [Answer] # JavaScript (ES6), 85 Test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go) (I found this without looking at any of the other answers, now I see it's very similar to rink's. Yet quite shorter. Probably I won't get many upvotes for this one) ``` F=(a,p,q=~a.lastIndexOf(0,p)||~a.indexOf(0))=>(q&&(a.splice(~q,1),a.splice(p,0,1)),a) // Ungolfed U=(a,p)=>{ q = a.lastIndexOf(0, p) if (q < 0) q = a.indexOf(0) if (q >= 0) { a.splice(q, 1) a.splice(p, 0, 1) } return a } // TEST out=x=>O.innerHTML+=x+'\n'; [ [['a', 'b', 0, 'c', 'd', 0], 2, ['a', 'b', 1, 'c', 'd', 0]] // place 2 is 0, just fill , [['a', 'b', 0, 'c', 'd', 0], 3, ['a', 'b', 'c', 1, 'd', 0]] // place 3 is filled, shift items left , [['a', 'b', 0, 'c', 'd', 0], 0, [1, 'a', 'b', 'c', 'd', 0]] // place 0 is filled, can't shift left, shift items right , [['a', 'b', 0, 'c', 'd', 0], 1, ['a', 1, 'b', 'c', 'd', 0]] // place 1 is filled, can't shift left, shift items right , [[0, 'a', 'b', 0, 'c', 'd', 0], 2, ['a', 'b', 1, 0, 'c', 'd', 0]] // place 2 is filled, shift items left , [[0, 'a', 'b', 0, 'c', 'd', 0], 4, [0, 'a', 'b', 'c', 1, 'd', 0]] // place 4 is filled, shift items left (notice you keep shifting up until a 0) , [['a', 'b', 'c', 'd'], 2, ['a', 'b', 'c', 'd']] // impossible , [[0, 2, 0, 2], 3, [0, 2, 2, 1]]] // place 3 is filled, shift items left .forEach(t=>{ i=t[0]+'' r=F(t[0],t[1])+'' k=t[2]+'' out('Test ' + (r==k?'OK':'Fail') +'\nInput: '+i+' '+t[1]+'\nResult:'+r+'\nCheck: '+k+'\n') }) ``` ``` <pre id=O></pre> ``` [Answer] # Julia, 122 bytes Just a naïve implementation of the spec to get things started. ``` f(x,i)=(i+=1;x[i]==0?(x[i]=1):i>2&&x[i-1]==0?(x[i-1]=x[i];x[i]=1):i<length(x)-1&&x[i+1]==0?(x[i+1]=x[i];x[i]=1):error();x) ``` Ungolfed: ``` function placeAt(x::Array, i::Int) # Make i 1-indexed i += 1 # Shift and modify the array as necessary if x[i] == 0 x[i] = 1 elseif i > 2 && x[i-1] == 0 x[i-1], x[i] = x[i], 1 elseif i < length(x)-1 && x[i+1] == 0 x[i+1], x[i] = x[i], 1 else error() end # Return the modified array x end ``` [Answer] ## JavaScript (ES6), 98 bytes Pretty much the same approach as [my CoffeeScript answer](https://codegolf.stackexchange.com/a/54726/22867) but I'm short-circuiting to the extreme in order to save a `return` statement: ``` f=(a,x)=>(~($=a.lastIndexOf(0,x))||~(_=a.indexOf(0,x)))&&a.splice(~$?$:_,1)&&a.splice(x,0,1)&&a||a ``` ### Explanation To easier explain, I have rearranged my code a bit: ``` // Declare function f with two arguments: array and position f = (a, x) => { // Take the part of the array from beginning to x and find the last 0 $ = a.lastIndexOf(0, x) // Find the first 0 after position x _ = a.indexOf(0, x); // indexOf returns -1 if they aren't found // ~1 == 0 so I am checking if either $ or _ is truthy (zeros were found) if (~$ || ~_) // If zeros were found in the left, use that. // Otherwise use the found zero in the right. // Delete it from the array // Array.prototype.splice will return an array which evaluates to truthy // and continues execution with the && // Insert value 1 at position x, deleting 0 elements // The last value is returned return a.splice(~$ ? $ : _, 1) && a.splice(x, 0, 1) && a else // No zeros were found so just return the original // In the golfed code the if would have evaluated to false to cut into the || part return a } ``` [Here's some information](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-Circuit_Evaluation) on JS short-circuit evaluation. ### Demo At the moment this demo only works in Firefox and Edge due to use of ES6: ``` f=(a,x)=>(~($=a.lastIndexOf(0,x))||~(_=a.indexOf(0,x)))&&a.splice(~$?$:_,1)&&a.splice(x,0,1)&&a||a // Snippet stuff console.log = x => O.innerHTML += x + '\n'; console.log(f(['a', 'b', 0, 'c', 'd', 0], 2)) console.log(f(['a', 'b', 0, 'c', 'd', 0], 3)) console.log(f(['a', 'b', 0, 'c', 'd', 0], 0)) console.log(f([0, 'a', 'b', 0, 'c', 'd', 0], 2)) console.log(f([0, 'a', 'b', 0, 'c', 'd', 0], 4)) console.log(f(['a', 'b', 0, 'c', 'd', 0], 2)) console.log(f(['a', 'b', 0, 'c', 'd', 0], 1)) ``` ``` <pre id=O></pre> ``` [Answer] # Ruby, 208 bytes ``` def f(a,i) x=a.take(i).rindex(0);y=a[i+1..-1].index(0) if a[i]==0 a[i]=1 elsif !x.nil? a.delete_at(x);a.insert(i,1) elsif !y.nil? a.delete_at(y+i+1);a.insert(i,1) end a end ``` [Answer] # Haskell, 119 bytes ``` e=elem 0 r=reverse f=(g.).splitAt g(a,y@(x:b))|e(x:a)=r(h(x:r a)1)++b|e y=a++h y 1|1<2=a++y h(0:r)n=n:r h(a:r)n=n:h r a ``` Usage example: ``` *Main> mapM_ (print.uncurry f) [ (2,[2,3,0,4,5,0]), (3,[2,3,0,4,5,0]), (0,[2,3,0,4,5,0]), (1,[2,3,0,4,5,0]), (2,[0,2,3,0,4,5,0]), (4,[0,2,3,0,4,5,0]), (3,[0,2,0,2]), (2,[2,3,4,5]) ] [2,3,1,4,5,0] [2,3,4,1,5,0] [1,2,3,4,5,0] [2,1,3,4,5,0] [2,3,1,0,4,5,0] [0,2,3,4,1,5,0] [0,2,2,1] [2,3,4,5] ``` How it works: Split the input list at the given position into left part `a`, the element at the position itself `x` and right part `b`. If there's a `0` in `a++x`, make room up to first `0` in the reverse of `a++x`. If there's a `0` in `x++b`, make room there. If there's no `0` at all, combine all parts unchanged to get the original list again. [Answer] ## CoffeeScript, 96 bytes ``` f=(a,_)->a.splice((if~($=a.lastIndexOf 0,_)then $ else a.indexOf 0),1);a.splice(_,0,1)if 0in a;a ``` [Answer] # Python 2, 102 bytes ``` def f(a,i): x=(a[i-1::-1]+a[i:]+[0]).index(0) if x<len(a):del a[(x,i-x-1)[x<i]];a[i:i]=[1] return a ``` Calculates the index of the zero to be removed by concatenating the list reversed up to the insertion index with the part after the index in normal order, then finding the index of the first zero. A zero is added to the end to avoid `ValueError` exceptions when no zero is found. Then just delete, insert and return. [Answer] # R, 87 bytes ``` f=function(a,i)if(0%in%a)append(a[-abs(min((b=which(a==0))*(1-(b<=i+1)*2)))],1,i)else a ``` Explanation ``` function(a,i) if(0%in%a) # as long as a 0 exists append( # append 1 after i a[ -abs( # remove absolute of min index min( # minimum of adjusted index (b=which(a==0))* # index of all 0's (1-(b<=i+1)*2) # multiple -1 if <= i ) ) ] ,1 ,i ) else # otherwise return untouched a ``` Tests ``` > f(c(2, 3, 0, 4, 5, 0) , 2) [1] 2 3 1 4 5 0 > f(c(2, 3, 0, 4, 5, 0) , 3) [1] 2 3 4 1 5 0 > f(c(2, 3, 0, 4, 5, 0) , 0) [1] 1 2 3 4 5 0 > f(c(2, 3, 0, 4, 5, 0) , 1) [1] 2 1 3 4 5 0 > f(c(0, 2, 3, 0, 4, 5, 0) , 2) [1] 2 3 1 0 4 5 0 > f(c(0, 2, 3, 0, 4, 5, 0) , 4) [1] 0 2 3 4 1 5 0 > f(c(0, 2, 0, 2) , 3) [1] 0 2 2 1 > ``` [Answer] # C#, 265 bytes **Golfed (265 Characters)** ``` static void placeAt(String[]Q,int P){int I;if(Q[P]=="0"){Q[P]="1";}else{I=Array.IndexOf(Q,"0");if(I>=0){if(I<P){for(int i=I;i<=P;i++){Q[i]=(i==P)?"1":Q[i+1];}}else if(I>P){for(int i=I;i>=P;i--){Q[i]=(i==P)?"1":Q[i-1];}}}}foreach(String s in Q)Console.Write(s+" ");} ``` **With white spaces and indentations** ``` static void placeAt(String[] Q, int P) { int I; if(Q[P] == "0") { Q[P] = "1"; } else { I = Array.IndexOf(Q, "0"); if (I >= 0) { if (I < P) { for (int i = I; i <= P; i++) { Q[i] = (i == P) ? "1" : Q[i + 1]; } } else if (I > P) { for (int i = I; i >= P; i--) { Q[i] = (i == P) ? "1" : Q[i - 1]; } } } } foreach (String s in Q) Console.Write(s + " "); } ``` **Whole Program** ``` using System; class FillZero { static void placeAt(String[] Q, int P) { int I; if(Q[P] == "0") { Q[P] = "1"; } else { I = Array.IndexOf(Q, "0"); if (I >= 0) { if (I < P) { for (int i = I; i <= P; i++) { Q[i] = (i == P) ? "1" : Q[i + 1]; } } else if (I > P) { for (int i = I; i >= P; i--) { Q[i] = (i == P) ? "1" : Q[i - 1]; } } } } foreach (String s in Q) Console.Write(s + " "); } static void Main() { String[] X = {"a", "b", "0", "c", "d", "0"}; placeAt(X , 1); } } ``` **Test Cases** [![enter image description here](https://i.stack.imgur.com/vhtwz.png)](https://i.stack.imgur.com/vhtwz.png) [Answer] # C, 154 bytes ``` p(a,l,i,c)int*a;{for(c=i;c+1;c--){if(!a[c]){for(;c<i;c++)a[c]=a[c+1];return a[i]=1;}}for(c=i;c<l;c++){if(!a[c]){for(;c>i;c--)a[c]=a[c-1];return a[i]=1;}}} ``` Passes the given test cases, **a** is the pointer to the array, **l** is the length of the array (I hope this doesn't break the brief), **i** is the index for the insert and **c** is used internally. Could possibly be improved by combining the left and right search for loops. ## Example ``` int main(int argc, char * argv[]) { int a[] = {0, 2, 0, 2}; p(a, 4, 3); } ``` ## Ungolfed Straight forward, and not really any tricks beyond K&R style declaration. ``` p(a,l,i,c) int *a; { /* Search left from i (also handles a[i] == 0) */ for (c=i;c+1;c--) { if (!a[c]) { /* Shift items left until i */ for (;c<i;c++) a[c]=a[c+1]; return a[i]=1; } } /* Search right from i */ for (c=i;c<l;c++) { if(!a[c]) { /* Shift items right until i */ for(;c>i;c--) a[c]=a[c-1]; return a[i]=1; } } } ``` ]
[Question] [ # The game [Nim](https://en.wikipedia.org/wiki/Nim) is a mathematical strategy game, where 2 players take turns taking items from distinct heaps. On your turn, you must take at least one item, and you may take as many as you want, provided that you only take from one heap. The player that takes the last item wins! This is a solved game. Before I go into the strategy, you can try playing it online [here](http://www.goobix.com/games/nim/). # The Strategy The winning strategy is explained very clearly and simply here at this [link.](http://www.archimedes-lab.org/How_to_Solve/Win_at_Nim.html) I will explain it using a little bit more technical terms. The way to win this game, is to always take as many items as possible so that the [binary-digital-sum](https://en.wikipedia.org/wiki/Digital_sum_in_base_b) is always 0. Consider the following board: ``` * * * * * * * * * * * * * * * 1 2 3 4 5 ``` To find the binary-digital-sum of this board, you must: 1. Convert the number in each row to binary. So we have 001, 010, 011, 100 and 101. 2. Add all the numbers together, and ignore any carrying. ``` 001 010 011 100 +101 ---- 001 ``` You can also bitwise-xor each number, and this will achieve the same result. Now, if the sum in this current configuration is 001, then this is not (yet) a winning board. But you can make it a winning board! If we take one item off of columns 1, 3 or 5, the sum will be 0. This is a winning board, which means that, provided you don't make a mistake, the next player to move will lose. So you must always end your turn with a winning board. Lets say you take one item off of column 5. Now the board looks like this: ``` * * * * * * * * * * * * * * 1 2 3 4 5 ``` As long as you don't screw up, you have a guaranteed win. There is nothing your opponent can do to stop you. Lets say he takes all of the items from column 5. ``` * * * * * * * * * * 1 2 3 4 5 ``` Where would you go next? Don't scroll down yet, and try to figure it out for yourself. --- Right now, the sum is 100. The best move (and only winning move) would be to take everything from column 4. That would leave the board like this: ``` * * * * * * 1 2 3 4 5 ``` and the sum like this ``` 001 010 +011 ---- 000 ``` that means that you are in a winning board! Yay! # The Challenge You must write a program or function that, given a nim board, will return a winning move, or a [falsey](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey?answertab=votes#tab-top) value if there is no winning move. Your input: * Will be your languages native list format, where each item in the list corresponds to the number of items in a given column. For example, the input {4, 2, 1, 0, 3} corresponds to the following nim board: ``` * * * * * * * * * * 1, 2, 3, 4, 5 ``` * (optional) The number of rows. (For languages like C/C++ where this is not known from the list itself.) Your output: * Can go to STDOUT or be returned from the function * Must be two numbers, 1) the column we are removing from (Remember that the columns are 0-indexed) and 2) the number of items to remove from that row. This could be a 2-item array, a string of the two numbers, etc. Keep in mind that the answer might be more than 2 digits long, so returning the string "111" is not valid because it isn't clear if this means "Remove one item from column eleven" or "Remove eleven items from column one". "1,11" or "11,1" would both be acceptable. * If there is no answer, return or print a falsy value. If your langauge can only return one type of variable (again, like C/C++), a negative number for the column, or 0 or less for the number to remove would both be acceptable falsey values. * If the column number or number to remove are too large, this is seen as an invalid output. # Sample Inputs/Outputs `[1, 2, 3, 4, 5]` ---> `[0, 1]` or `[4, 1]` or `[2, 1]` `[1, 3, 5, 6]` ---> `[0, 1]` or `[1, 1]` or `[2, 1]` `[1, 2, 0, 0, 5]` ---> `[4, 2]` `[1, 2, 3]` ---> `ERROR` If you choose to do a function instead of full program, then you must write a full program to demonstrate the function in action. This will not count towards your full score. Also, programs are expected to run in a reasonable amount of time. I'm not planning to enter any excessively large inputs, so as long as your program isn't doing a brute force search over the entire game tree, you should be fine. As usual, this is code-golf, so [standard loop-holes apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), and answers are counted [in bytes.](https://mothereff.in/byte-counter) # Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` var QUESTION_ID=52356;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table> ``` [Answer] # Pyth, ~~33~~ ~~22~~ ~~21~~ ~~20~~ 19 bytes ``` eS.e*<JxxFQbb,k-bJQ ``` [You can try it in the online compiler here.](http://pyth.herokuapp.com/?code=eS.e%2A%3CJxxFQbb%2Ck-bJQ&input=%5B1%2C2%2C3%2C4%2C5%5D&debug=0) Thank you to Jakube for removing 12 bytes and Maltysen for removing an additional byte! This prints a winning move from the current position. If there are no winning moves, it doesn't print anything. I used the algorithm on [wikipedia](https://en.wikipedia.org/wiki/Nim#Mathematical_theory). Here is the breakdown: ``` .e Q While enumerating every element in the input: J Assign variable J to: xFQ Every element of the input bitwise xor'ed together, x b bitwise xor'ed with the current element of the input , Create a tuple containing: k The index of the current element, and -bJ the difference between the current element and J *<J b Put that tuple into a list if J < b, otherwise put an empty tuple S Sort the list e Print the last element of the list ``` [Answer] # Pyth, 23 bytes ``` eSs.em*,kd!xxxFQb-bdSbQ ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=eSs.em*%2Ckd!xxxFQb-bdSbQ&input=%5B1%2C+2%2C+0%2C+0%2C+5%5D&debug=0) This iterates over all possible moves and even does sorting. Therefore it has a time-complexity of `O(N*log(N))` and a memory complexity of `O(N)`, where `N` is the sum of the input list or the number of items. Because of the bad time complexity, this might not be a valid answer. Though it solves all games, that you can play in real life with real objects, instantly. ### Explanation: ``` implicit: Q = input list .e Q map each (index k, item b) of Q to: m Sb map each d of [1, 2, ..., b] to: ,kd the pair (k, d) * multiplied by xFQ xor of all numbers in Q x b xor with b x -bd xor with b-d ! not (1 if xor==0 else 0) So the input [1, 2, 0, 0, 5] gives [[[]], [[], []], [], [], [[], [4, 2], [], [], []]] s add all lists to one big list S sort Now it looks like this: [[], [], [], [], [], [], [], [4, 2]] e pick the last element and print ``` [Answer] # CJam, ~~21~~ 20 bytes Saved a byte compared to original version, and error handling also works now: ``` l~__:^f^.-_:g1#_@=S\ ``` [Try it online](http://cjam.aditsu.net/#code=l~__%3A%5Ef%5E.-_%3Ag1%23_%40%3DS%5C&input=%5B1%202%200%200%205%5D) Input is a CJam array, e.g.: ``` [1 2 3 4 5] ``` If no solution is found, it prints `-1 0`, which meets my understanding of the output requirements. Explanation: ``` l~ Get input. __ Make two copies for following operations. :^ Reduce with xor operator, producing xor of all columns. f^ xor all input values with the result. For each column, this calculates the value that the column would have to change to make the overall xor zero. Consider this the "target values". .- Subtract the target values from the input values. _:g Per element signum of difference between target value and input value. 1# Find index with value 1, which is the first positive value. _@= Get the value at the index. S\ Put a space between index and value. ``` [Answer] # Ruby, 95 ``` ->(a){r=[false,c=0] a.each{|e|c^=e} a.each_index{|i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0} r} ``` I wrote 2 separate anonymous functions. The first, assigned to `f` in the program below, **prints** all solutions, and the second `g` (corresponding to the score above, as it is both shorter and more compliant with the spec) **returns** only the solution which requires removing the greatest number. in both cases, the digit sum is totalized in `c`. Then the array is looped over and the expression `n=a[i]-(c^a[i])` is used to calculate the number of counters to be removed (obviously this can only be done if it exceeds zero). in `f`, all possible solutions are printed (if `c` is found to be `0`, `error` is printed without looping.) I was surprised to see that the different piles can require quite different numbers of counters to be removed. in `g` the output array `r` is only updated if the number of counters to be removed exceeds the previous number. the array r=`[pile index, number to be removed]` is returned. If there is no solution, the number of counters to be removed is always zero, `r` remains unchanged, and the initial value of r=`[false,0]` is returned. Minor savings are possible if `false` can be changed to for example`"!"` and if any valid solution rather than the largest one can be returned (by deleting `&&n>r[1]`.) **Formatted in test program** ``` f=->(a){ c=0 a.each{|e|c^=e} c<1?(p "error"):(a.each_index{ |i|(n=a[i]-(c^a[i]))>0?(p"#{i},#{n}"):0 }) } g=->(a){ r=[false,c=0] a.each{|e|c^=e} a.each_index{ |i|(n=a[i]-(c^a[i]))>0&&n>r[1]?(r=[i,n]):0 } r } #Change the following two lines according to the number of values youj want to use for testing. t=[rand(15),rand(15),rand(15),rand(15)] #Generate some random numbers for testing. t=[gets.to_i,gets.to_i,gets.to_i] #User input. Delete this line if you want to test with random numbers. print t,"\n" f.call(t) puts g.call(t) ``` [Answer] ## Mathematica, 73 bytes ``` {f=BitXor;p=Position[#,x_/;BitAnd[x,a=f@@#]==a][[1,1]],(n=#[[p]])-n~f~a}& ``` [Answer] # JavaScript (ES6), 54 bytes Returns either the pair `[column, number]` or *false* ``` a=>a.some((n,i)=>r=(n-=n^eval(a.join`^`))>0&&[i,n])&&r ``` [Try it online!](https://tio.run/##hY49C8IwEIZ3f8VNIYGk33VLNmeha0hpqKmk1ERS6d@PrYNQVIQbXo73nudGvei5D/b@YM5fTBx41FzoZPY3g7GjlnAROHaMu9YsesI6Gb11XdsRIjKEpKVOEYRC7L2b/WSSyV/xgGVOoaBQUqgo1IoQSFNgjAmQGYVcgQ8gq3cqtnT4RKz3NYWjAoDviPwvYt1nr9l/sbqLH/Vy0@2Np6Y5N/EJ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.some((n, i) => // for each value n at position i in a[]: r = ( // save the result of the iteration in r n -= // subtract from n: n ^ eval(a.join`^`) // n XOR (all values in a[] XOR'ed together) ) > 0 // if the above value is positive: && [i, n] // yield the solution [i, n] and exit the some() loop // (otherwise: yield false and go on with the next value) ) && r // end of some(); return r ``` ]
[Question] [ *This is one of several [challenges](http://meta.codegolf.stackexchange.com/a/2007/21682) left for the community by [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies).* The curve that an idealised hanging rope or chain makes is a [catenary](http://en.wikipedia.org/wiki/Catenary). ![A chain forming a catenary](https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Kettenkurve_0400.JPG/400px-Kettenkurve_0400.JPG) [Image](https://commons.wikimedia.org/wiki/File:Kettenkurve_0400.JPG) by Bin im Garten, via Wikimedia Commons. Used under the [CC-By-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/deed.en) licence. Write a program that will draw a catenary, as an image, in quadrant 1 of the plane given two points *(x1,y1)*, *(x2,y2)*, and the "rope length" *L*. *L* will be greater than the distance between the two points. You must also draw axes on the left and bottom sides of the image (400x400 px min) for scale. Only draw the quadrant from x and y in range 0 to 100. (You may assume the points are in range.) Dots, or something similiar, should be drawn at the *(x1,y1)*, *(x2,y2)* endpoints to distinguish them. **The curve should only be drawn in the space between these points.** [Answer] # Python + NumPy + Matplotlib, 1131 Just to get us started, here's an attempt that uses no knowledge of calculus or physics other than the fact that the catenary minimizes the energy of a chain. Hey, my algorithm may not be efficient, but at least it's not implemented efficiently either! ``` import math import random import numpy as np import matplotlib.pyplot as plt length, x0, y0, x1, y1 = input(), input(), input(), input(), input() chain = np.array([[x0] + [length / 1000.]*1000, [y0] + [0.] * 1000]) def rotate(angle, x, y): return x * math.cos(angle) + y * math.sin(angle), -x * math.sin(angle) + y * math.cos(angle) def eval(chain, x1, y1): mysum = chain.cumsum(1) springpotential = 1000 * ((mysum[0][-1] - x1) ** 2 + (mysum[1][-1] - y1) ** 2) potential = mysum.cumsum(1)[1][-1] return springpotential + potential def jiggle(chain, x1, y1): for _ in xrange(100000): pre = eval(chain, x1, y1) angle = random.random() * 2 * math.pi index = random.randint(1,1000) chain[0][index], chain[1][index] = rotate(angle, chain[0][index], chain[1][index]) if( pre < eval(chain, x1, y1)): chain[0][index], chain[1][index] = rotate(-angle, chain[0][index], chain[1][index]) jiggle(chain, x1, y1) sum = chain.cumsum(1) x1 = 2 * x1 - sum[0][-1] y1 = 2 * y1 - sum[1][-1] jiggle(chain, x1, y1) sum = chain.cumsum(1) plt.plot(sum[0][1:], sum[1][1:]) plt.show() ``` [Answer] # BBC Basic, 300 ASCII characters, tokenised filesize 260 ``` INPUTr,s,u,v,l:r*=8s*=8u*=8v*=8l*=8z=0REPEATz+=1E-3UNTILFNs(z)/z>=SQR(l^2-(v-s)^2)/(u-r)a=(u-r)/2/z p=(r+u-a*LN((l+v-s)/(l-v+s)))/2q=(v+s-l*FNc(z)/FNs(z))/2MOVE800,0DRAW0,0DRAW0,800CIRCLEu,v,8CIRCLEr,s,8FORx=r TOu DRAW x,a*FNc((x-p)/a)+q NEXT DEFFNs(t)=(EXP(t)-EXP(-t))/2 DEFFNc(t)=(EXP(t)+EXP(-t))/2 ``` Emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> This has obviously been solved before, so the first thing I did was look what others have done. The equation of a catenary centred at the origin is simply `y=a*cosh(x/a)`. It becomes slightly more complicated if it is not centred at the origin. Various sources say that if the length and endpoints are known the value for `a` must be determined numerically. There is an unspecified parameter `h` in the wikipedia article. So I found another site and basically followed the method here: [http://www.math.niu.edu/~rusin/known-math/99\_incoming/catenary](http://www.math.niu.edu/%7Erusin/known-math/99_incoming/catenary) BBC Basic does not have `sinh` and `cosh` built in, so I defined two functions at the end of the program to calculate them using `EXP` coordinates for lefthand point must be supplied before righthand point, OP confirmed this is OK. Length is given last. Values can be separated by commas or newlines. **Ungolfed code** ``` INPUT r,s,u,v,l REM convert input in range 0-100 to graphic coordinates in range 0-800 r*=8 s*=8 u*=8 v*=8 l*=8 REM solve for z numerically z=0 REPEAT z+=1E-3 UNTIL FNs(z)/z>=SQR(l^2-(v-s)^2)/(u-r) REM calculate the curve parameters a=(u-r)/2/z p=(r+u-a*LN((l+v-s)/(l-v+s)))/2 q=(v+s-l*FNc(z)/FNs(z))/2 REM draw axes, 800 graphics units long = 400 pixels long (2 graphics units per pixel) MOVE 800,0 DRAW 0,0 DRAW 0,800 REM draw markers at end and beginning of curve (beginning last, so that cursor is in right place for next step) CIRCLE u,v,8 CIRCLE r,s,8 REM draw curve from beginning to end FORx=r TOu DRAW x,a*FNc((x-p)/a)+q NEXT REM definitions of sinh and cosh DEF FNs(t)=(EXP(t)-EXP(-t))/2 DEF FNc(t)=(EXP(t)+EXP(-t))/2 ``` ![enter image description here](https://i.stack.imgur.com/d1vdc.png) [Answer] # Python 2.7 + matplotlib, 424 Run as ``` python thisscript.py [length] [x0] [y0] [x1] [y1] ``` If I can assume that x0 is always smaller than x1 character count reduces to **398** ``` from numpy import * from pylab import * from scipy.optimize import * import sys c=cosh l,p,q,u,w=map(float,sys.argv[1:]) if p>u: p,q,u,w=u,w,p,q h=u-p v=w-q a=brentq(lambda a:(2.*h/a*sinh(0.5*a))**2-l**2-v**2,1e-20,600) b=brentq(lambda b:c(a*(1.-b))-c(a*b)-a*v/h,-600/a,600/a) r=linspace(p,u,100) plot([p,u],[q,w],'ro') plot(r,h/a*c(((r-p)/h-b)*a)-h/a*c(a*b)+q,'k-') gca().set_xlim((0,100)) gca().set_ylim((0,100)) show() ``` The magic number 600 you see appearing in some places is due to the fact that cosh(x) and sinh(x) start overflowing around x=710 (so 600 to keep some margin) > > Basically I solve the problem in the frame where the catenary goes > trough (0,0) and (x1-x0,(y1-y0)/(x1-x0)) and then remap to the original > frame. This improves the numerical stability **a lot**. > > > ]
[Question] [ # Menu Shortcuts Traditionally, user menus are accessible by keyboard shortcuts, such as `Alt + (a letter)`, or even simply hitting the letter when all textboxes are unfocused ([gmail](https://support.google.com/mail/answer/6594?hl=en) style). # Your task Given the menu entries as an input, your task is to grant each menu entry a proper shortcut letter. Write a function or a program that accepts a set of words - the menu entries (as an array of strings, or your language equivalent), and returns a dictionary, or a hashmap, from a single letter to a menu entry. You can either use a parameter and return a value, or use the STDIN and output your results to STDOUT. You are **not** allowed to assume a global/scope variable is already populated with the input. # Algorithm to determine the proper letter * Basically it's the first available letter of the word. See assumptions and examples below. * In case all entry's letters are not available, the shortcut will be `(a letter) + (a number)`. Which letter you pick from the entry is arbitrary. The number should start from 0 and be incremented by 1 - such that all shortcuts are unique. See third example below. # Assumptions * The input will be a Set, i.e. no repetitions, every entry is unique. * Length of the input can be any non-negative integer (up to MAX\_INT of your language). * Case sensitivity: Input is case-sensitive, (but will stay unique when ignoring case). The results should contain the original entries with their original casing. However, the output shortcut letters are not case-sensitive. * All input words will not end with numbers. * No "evil input" will be tested. "Evil input" is such that you have to increment the counter of a certain letter more than 10 times. # Examples Examples below are in JSON, but you can use your language equivalent for an array and a Dictionary, or - in case you're using STD I/O - any readable format for your input and output (such as csv, or even space-separated values). 1. ``` Input: ['File', 'Edit', 'View', 'Help'] Output: {f:'File', e:'Edit', v:'View', h:'Help'} ``` 2. ``` Input: ['Foo', 'Bar', 'FooBar', 'FooBars'] Output: {f:'Foo', b:'Bar', o:'FooBar', a:'FooBars'} ``` 3. ``` Input: ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba'] Output: {a:'a', b:'b', a0:'aa', b0:'bb', q:'bbq', b1:'bbb', b2:'ba'} ``` # Winning conditions Shortest code wins. Only ASCII is allowed. [Answer] # Javascript (*ES6*) 106 105 100 This function takes input as an an array and outputs a javascript object. ``` f=i=>i.map(a=>{for(b of c=a.toLowerCase(d=0)+d+123456789)d<!o[e=b>=0?c[0]+b:b]&&(o[d=e]=a)},o={})&&o ``` Results: ``` f(['File', 'Edit', 'View', 'Help']); // {"f":"File","e":"Edit","v":"View","h":"Help"} f(['Foo', 'Bar', 'FooBar', 'FooBars']); // {"f":"Foo","b":"Bar","o":"FooBar","a":"FooBars"} f(['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']); // {"a":"a","b":"b","a0":"aa","b0":"bb","q":"bbq","b1":"bbb","b2":"ba"} ``` Ungolfed / Commented: ``` f=i=>{ o={}; // initialize an object for output i.map(a=> // loop through all values in input for(b of c=a.toLowerCase(d=0)+d+123456789) // loop through all characters of the string with 0123456789 appended to the end // and initialize d as 0 to be used as a flag e=b>=0?c[0]+b:b // if b is a number, set e to the first character + the number, otherwise b if(d<!o[e]) // if the flag hasn't been triggered and o doesn't have a property e o[d=e]=a // then store the value at e and trigger the d flag ) return o // return the output object } ``` [Answer] # Python 2.x - 176 170 157 114 bytes Very simple approach, but someone has to kick the game going. ``` r={} for i in input():a=list(i.upper());r[([c for c in a+[a[0]+`x`for x in range(10)]if c not in r])[0]]=i print r ``` --- ``` Edit 1: Reversed the checking operation and made it set the result only once. Edit 2: Removed branching. Edit 3: Removed unnecessary dictionary. (thanks to the added assumption) ``` Examples: ``` Input: ['File', 'Edit', 'View', 'Help'] Output: {'H': 'Help', 'V': 'View', 'E': 'Edit', 'F': 'File'} Input: ['Foo', 'Bar', 'FooBar', 'FooBars'] Output: {'A': 'FooBars', 'B': 'Bar', 'O': 'FooBar', 'F': 'Foo'} Input: ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba'] Output: {'A': 'a', 'B': 'b', 'Q': 'bbq', 'A0': 'aa', 'B0': 'bb', 'B1': 'bbb', 'B2': 'ba'} ``` I think the only required explanation is the ungolfed code. (This actually is the original version) ``` items = input() # ['File', 'Edit', 'View', 'Help'] chars = map(chr,range(65,91)) numbers = {}.fromkeys(chars,0) result = {} for item in items: try: key = [c for c in item.upper() if c in chars][0] # causes an exception when no items match result[key] = item chars.remove(key) except: key = item[0].upper() result[key+`numbers[key]`] = item numbers[key] += 1 print result ``` [Answer] # JavaScript (ECMAScript 6) - 107 Characters ``` f=a=>(o={},p={},[o[[c for(c of l=w.toLowerCase())if(!o[c])][0]||(k=l[0])+(p[k]=p[k]+1|0)]=w for(w of a)],o) ``` **Explanation:** ``` f=a=>( o={}, // The dictionary to output p={}, // Stores record of numbers appended after duplicate // menu keys [ // Use array comprehension for each word w of input a (unmatchedCharacters =[c // Use array comprehension for each character c of for(c of l=w.toLowerCase()) // the lower case of word w but only get if(!o[c]) // those characters which are not already a key in o. ], key=unmatchedCharacters[0] // Take the first of those characters || // Or if all characters are already in o (k=l[0]) // Take the first character of the lower-case word +(p[k]=p[k]+1|0), // concatenated with the increment of the digit stored // in p (or zero). o[key]=w) // Set o to map from this key to the word for(w of a) ], o) // return o ``` **Tests:** ``` f(['File', 'Edit', 'View', 'Help']); {f: "File", e: "Edit", v: "View", h: "Help"} f(['Foo', 'Bar', 'FooBar', 'FooBars']); {f: "Foo", b: "Bar", o: "FooBar", a: "FooBars"} f(['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']); {a: "a", b: "b", a0: "aa", b0: "bb", q: "bbq", b1: "bbb", b2: "ba"} ``` [Answer] ## PHP >= 5.4 - 149 characters According to PHP's standards *(insert sniggers here)*, the input isn't valid JSON as it uses `'` instead of `"`, so I've been a bit cheeky and I'm using the Input as an actual variable declaration: ``` <? $i = ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']; $c=[];foreach($i as$w){foreach(str_split($w) as$j)if(!$c[$j]){$x=$j;goto f;}$n=0;do{$x=$w[0].$n++;}while($c[$x]);f:$c[$x]=$w;}echo json_encode($c); ``` Using the examples: ``` Input: ['File', 'Edit', 'View', 'Help'] Output: {"F":"File","E":"Edit","V":"View","H":"Help"} Input: ['Foo', 'Bar', 'FooBar', 'FooBars'] Output: {"F":"Foo","B":"Bar","o":"FooBar","a":"FooBars"} Input: ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba'] Output: {"a":"a","b":"b","a0":"aa","b0":"bb","q":"bbq","b1":"bbb","b2":"ba"} ``` Un-golfified it's pretty basic: ``` <? $i = ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']; $c = []; foreach($i as $w) { foreach(str_split($w) as $j) if(!$c[$j]) { $x = $j; goto f; } $n = 0; do { $x = $w[0] . $n++; } while($c[$x]); f: $c[$x] = $w; } echo json_encode($c); ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~91~~ 83 bytes ``` $r=@{} $args|%{$r[($_|% *wer|% t*y|%{$c=$_;,''+0..9|%{$c+$_}|?{!$r.$_}})[0]]=$_} $r ``` [Try it online!](https://tio.run/##XVHRTsIwFH3fV1xDsQzGgo@GNC4mGv0BX4hZOriDxbKNtYhk27fjbYsK9qHn3HNPz21y6@qAjd6gUieWg4D2xBqRtH3AZLPW3bBlzWLE0m4IYzISmPHRqkvB0nnE@WQWx/dOmLC07x7aG9bExPpwMXt/JxMlNac@CJJRAHSiUdLmgj8XCvkcUPCnVWGIfQr@VuCB2EbwF1Q17yPwNkJnInQWQmcIrwKrit5mgj/KhkjlFM/lD9c@k5wEtuerK6YvYumh9KGZjZlR6WoimVV2FndWubPMmSyTbo60oZm9pKeZv3cefCVpXAgdDKF1Yxl@1bg0uIqAbbHcvxrcaloLS327Qb1XhoRb2lby63DN0bkbf@DRb86XLIUp7v6i7XrC6NoeKyzXZvPPeNEJYVpWZlmVRhalBpZLpdGNHZxzutzAAPblstrSvwyYTaFBFSWCqWBV6FrJI3irDvrTNw "PowerShell – Try It Online") It throws an exception if a proper shortcut not found. Unrolled: ``` $result=@{} $args|%{ $shortcuts = $_|% toLower|% toCharArray|%{ $c=$_ ,''+0..9|%{$c+$_}|?{!$result.$_} # output shortcuts are not exist in the result } $properShortcut = $shortcuts[0] # throws an exception if a proper shortcut not found $result[$properShortcut]=$_ } $result ``` [Answer] # PHP, 153 bytes ``` for($c=[];$w=trim(fgets(STDIN));$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);}print_r($c); ``` run with `php-r '<code>' <<EOF` + Enter + `<word1>`+Enter + `<word2>`+Enter + ... + `EOF`+Enter working on argv for **155 bytes**: ``` $c=[];foreach($argv as$i=>$w)if($i){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w;}print_r($c); ``` run with `php -r '<code>' <word1> <word2> ...` (-13 bytes with a defined global: `foreach($i as$w)` instead of `foreach($argv as$i=>$w)if($i)`) ]
[Question] [ To solve the [Halting Problem](https://en.wikipedia.org/wiki/Halting_problem) you are given a description of a program, and must determine whether or not it will ever finish. You can never do this for all programs. Yet for programs like (in [brainf\*\*\*](http://esolangs.org/wiki/Brainfuck)): ``` > ``` It obviously will halt, and for programs like: ``` +[] ``` It obviously will not. Your challenge is to "solve" the halting problem for as many programs as possible. These programs will not use `.` or `,`, and will not have input or output. You will be given a description of the program and must output either "Halts", "Does not halt", or "Unknown". When your program outputs "Halts" or "Does not halt", you have solved the input program. Here are some requirements. 1. It must solve at least an infinite amount of programs. 2. For every program it solves, its solution must be correct. 3. You may only output 1 of the 3 above choices. 4. You may assume that the running computer has infinite time and memory, so [XKCD 1266](http://xkcd.com/1266/) would not work (the tape is unlimited). 5. No external resources. 6. You may not use a [programming language that can actually solve the halting problem](http://esolangs.org/wiki/Category%3aUncomputable). You may have a non-code-golfed side program that takes a string that is a program, and generates some sort of abstract syntax tree of it if you like. Note, that isn't really scoring per se, but how to determine if one program beats another. 1. If program A solves an infinite number of programs that B doesn't, but B only solves finite or no programs that A solves, A automatically wins. 2. Otherwise, the program with the fewest characters wins. Do not count white space or comments, so do not obfuscate your code. Tip: Timers won't work. You see, for any time T and given machine, there is an N, such that all programs longer than that have to take more than T time. This means that a timer can only achieve the solution of a finite number of programs, and, as you can see above, solving a finite number of programs doesn't help. [Answer] ## Python, ungolfed spaghetti code Oh dear. ``` def will_it_halt(instructions): tape_length = 1 LOOP_BOUND = 1000 registry = [0] * tape_length pos = 0 jumpbacks = [] reached_states = set() pos_instructions = 0 while True: letter = instructions[pos_instructions] if letter == "+": registry[pos] = (registry[pos] + 1) % 256 elif letter == "-": registry[pos] = (registry[pos] - 1) % 256 elif letter == ">": pos += 1 if pos >= tape_length: registry += [0]*tape_length tape_length = len(registry) elif letter == "<": pos -= 1 if pos <= 0: registry = [0]*tape_length+registry tape_length = len(registry) pos += tape_length elif letter == "[": if registry[pos] == 0: nests = 1 while nests: pos_instructions += 1 if instructions[pos_instructions] == "[": nests += 1 elif instructions[pos_instructions] == "]": nests -= 1 if jumpbacks == []: reached_states.clear() else: jumpbacks.append(pos_instructions-1) elif letter == "]": stripped_registry = [str(x) for x in registry if x != 0] translated_pos = pos - (len(registry) - len(stripped_registry)) state = (translated_pos, pos_instructions, ".".join(stripped_registry)) if state in reached_states: return "Does not halt" elif len(reached_states) > LOOP_BOUND: return "Unknown" else: reached_states.add(state) pos_instructions = jumpbacks.pop() pos_instructions += 1 if pos_instructions >= len(instructions): break return "Halts" ``` Pretty brute-forcey solution to the problem: just run the bf code. We assume the tape length is arbitrarily long and that individual cells wrap at 256. At the end of every loop, we store the state of the tape with a set. States are of the form (our position on the tape, our position on the instructions, what the tape looks like with leading 0's stripped). If we store the same state twice, then we're somewhere in an infinite loop, so the program does not halt. If we store over 1,000 states, then cut losses and return unknown. Once we leave a loop we check to see if we aren't in any larger loops. If not, we're never seeing any of the previous states ever again (at the very least, the instruction position will always be different!) so we can clear the set of states. This should accurately determine any BF program who's loops aren't longer than 1,000 iterations, as well as many programs that repeat a state before 1,000 iterations in a loop. Not all of them, though: something like "{1 million +'s here}[-]>+[+-]" eventually repeats a state, but the [-] loop passes 1,000 iterations first. Some examples: ``` >+>->+>- ``` No loops, so it reaches the end and halts. ``` +[+] ``` Loop ends after 256 iterations, so it reaches the end and halts. ``` +[+-] ``` Eventually repeats the state (0,5,"1"), so it does not halt. ``` +[->+] ``` This doesn't repeat any states but the loop never ends, so it should print "unknown". But the program kind of cheats here. Instead of storing the position on the tape, it adds an offset between the original registry and the stripped one. If all a loop does is translate the tape by some spaces, then it will continue translating it indefinitely (like a life glider), so we can say it does not halt. ``` +[>+] ``` Doesn't translate, doesn't repeat any states, prints unknown. ``` +++++++++++[-] ``` This does halt, but it would print "unknown" if LOOP\_BOUND was 10. There's a couple of ways to make this smarter. You could obviously increase LOOP\_BOUND to reduce the number of unknowns. You could have smarter handling of nested loops. You could probably do something fancy with BB numbers and the size of loops to better detect if something should halt, but I'm not good enough at CS nor at Python to be able to do that yet. [Answer] ## GolfScript (23 chars, infinite correct answers) ``` '[]'&! # 0 if there are brackets, so Unknown # 1 if there are no brackets, so no looping, so definitely halts 'UnknownHalts'7/= ``` [Answer] ## Awk A small extension in power from the two examples. If a program contains no loops at all, hence no decisions, it is still obviously determined to halt. Since we're assuming validity of the program, we also assume brackets are balanced and thus need only search for one or the other of the brackets. ``` BEGIN{RS=""} !/\[/{print "Halts"; exit} END{print "Unknown"} ``` For the second, it must check first if the loop runs at all, so we must simulate the straight-line code preceding the loop. Then, if the loop returns to the same cell (ie. number of `>`s is equal to the number of `<`s within the loop), and it performs no incs or decs at this cell (ie. for any position-balanced prefix of the balanced loop body, there are no instances of `+` or `-` before the next `<` or `>`, then the cell is unmodified). Implementing this part may take me more time. Ooh, wait, for the first part of checking if the loop runs at all, we can take this same idea and search the pre-loop program for balanced *suffixes* and insist that there be a `+` or `-` (unbalanced). [Answer] ## Haskell Here is a really simple example answer. Feel free to include it in your answers (since you including multiple tests in an answer is a good idea.) ``` main=do p<-getLine if take 3 p == "+[]" then putStr "Does not halt" else putStr "Unknown" ``` It basically sees if there is a loop in the beginning. If that exact loop doesn't occur in the beginning, it just gives up. It doesn't even work for `++[]`. It does solve an infinite number of programs though, and it is always correct when it solves it. ]
[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 6 years ago. [Improve this question](/posts/10700/edit) This is a common puzzle many of you have solved manually. Now this is the time to write an algorithm to solve the same. There are equal number match sticks lined up in two different side facing each other's direction. There is a single empty space between them. Say something like the following figure (if total number of match sticks are 4). ![enter image description here](https://i.stack.imgur.com/l4dQD.png) Each stick can either slide one step in forward direction (if the immediate front space is free), or it can be jumped over one stick in their front, and land into the free space (if that space is free). The move in reverse direction is not possible (even the space is free). No reverse jump is also allowed. Only one move is allowed in one step. Now, you have to write an algorithm to find the minimum steps required using which all the left hand side match sticks will land in right hand side and all the right hand side match sticks will land in left hand side. For ex: If there are total 2 match sticks (1 in each side) then steps will be: ![enter image description here](https://i.stack.imgur.com/XJaMb.png) Note: In the above figure the left side stick been moved first. Another solution exists when the right side stick moves first. But for this problem, you have to give only one solution and that is also assuming that the left side stick moves first. The following figure describes the moves with 4 match sticks (2 in each side): ![enter image description here](https://i.stack.imgur.com/o9j2D.png) Note: In the above figure the left side stick been moved first. Another solution exists when the right side stick moves first. But for this problem, you have to give only one solution and that is also assuming that the left side stick moves first. [Assumption: The input can be any even number between 02 to 14 (i.e. 1 to 7 match sticks in each side). For inputs outside this range, you do not need to do any validation, neither need to provide any error message. Note: In the output, each step is separated by a '|' (pipe) character. COBOL programmers should always assume PIC 9(2) as input size & may also assume the output to be fixed maximum length 450 characters, padded with spaces at right.] --- Sample Input: ``` 02 ``` Sample Output: ``` 01To02|03To01|02To03| ``` --- Sample Input: ``` 04 ``` Sample Output: ``` 02To03|04To02|05To04|03To05|01To03|02To01|04To02|03To04| ``` --- Sample Input: ``` 06 ``` Sample Output: ``` 03To04|05To03|06To05|04To06|02To04|01To02|03To01|05To03|07To05|06To07|04To06|02To04|03To02|05To03|04To05| ``` [Answer] ## APL 129 The code below takes screen input and outputs to the screen in the format specified: ``` n←n,n++\1↓z←(⌽z),((¯1*~2|n)×n⍴2),z←⌽∊(¯1*2|⍳n)ר1,((⍳(n←.5×⍎⍞)-1)⍴¨2),¨1⋄(∊(((¯2↑¨'0',¨⍕¨n),¨⊂'To'),¨(¯2↑¨'0',¨⍕¨n-z)),¨⊂'|')~' ' ``` A good third of the code is taken up formatting the output. The logic is complete by the occurrence of the ⋄ symbol in the code. Below is the result for an input of 08 as a check: ``` 04To05|06To04|07To06|05To07|03To05|02To03|04To02|06To04|08To06|09To08|07To09|05To07|03To05|01To03|02To01|04To02|06To04|08To06|07To08|05To07|03To05|04To03|06To04|05To06| ``` [Answer] ## Javascript 178 174 161 `prompt`s for `n` then `alert`s answer. (No `0` padding) **Latest:** ``` t=1+(m=prompt(s=i='')/2);for(z=Math.abs;i++<m*2;)for(j=m-z(m-i),s+=(t+=a=(m%2^z(m+.5-i)%2-.5)*-2+1)+'To'+(t-a)+'|';j--;)s+=(t+=a=i%2*4-2)+'To'+(t-a)+'|';alert(s) ``` **2:** ``` z=Math.abs;t=m=prompt(o=[])/2;t++;for(s=i='';i++<m*2;)for(j=m-z(m-i),o.push((z(m+.5-i)%2-.5)?-1:1);j--;)o.push(i%2?2:-2);o.map(function(a){s+=(t+=a)+'To'+(t-a)+'|'});alert(s) ``` **1:** ``` t=m=prompt(o=[])/2+1;for(s=i='';++i<m;)for(j=i,o.push(i%2?-1:1);j--;)o.push(i%2?2:-2);o.concat(o.slice().reverse().slice(m-1)).map(function(a){s+=(t+=a)+'To'+(t-a)+'|'});alert(s) ``` This uses the concept that the pattern is mirrored: ``` Key R='Jump Right' r='Shift Right' L='Jump Left' l='Shift Left' m='Move' j='Jump' ``` So, where `n=2`, the pattern of movement is: ``` rLr mjm ``` Which equates to ``` +1 -2 +1 ``` This pattern repeats like so (`n=8`) ``` rLlRRrLLLlRRRRlLLLrRRlLr mjmjjmjjjmjjjjmjjjmjjmjm +1 -2 -1 +2 +2 +1 -2 -2 -2 -1 +2 +2 +2 +2 -1 -2 -2 -2 +1 +2 +2 -1 -2 +1 ``` We can notice a few patterns here: 1. Movement alternates between left and right 2. The number of movements in a particular direction increases from 1 to `n/2`, which repeats 3 times, then decreases back to 1. 3. The type of movement alternates between shifting and jumping, the number of shifts in a row being a constant `1`, and the number of sequential jumps increasing from 1 to `n/2` then decreasing back to 1. 4. The summation of the movements is always 0. (Not sure if this is actually relevant) `n=14`: ``` rLlRRrLLLlRRRRrLLLLLlRRRRRRrLLLLLLLrRRRRRRlLLLLLrRRRRlLLLrRRlLr mjmjjmjjjmjjjjmjjjjjmjjjjjjmjjjjjjjmjjjjjjmjjjjjmjjjjmjjjmjjmjm ``` Sample output: `f(2)`: ``` 1To2|3To1|2To3| ``` `f(8)`: ``` 4To5|6To4|7To6|5To7|3To5|2To3|4To2|6To4|8To6|9To8|7To9|5To7|3To5|1To3|2To1|4To2|6To4|8To6|7To8|5To7|3To5|4To3|6To4|5To6| ``` `f(40)`: ``` 20To21|22To20|23To22|21To23|19To21|18To19|20To18|22To20|24To22|25To24|23To25|21To23|19To21|17To19|16To17|18To16|20To18|22To20|24To22|26To24|27To26|25To27|23To25|21To23|19To21|17To19|15To17|14To15|16To14|18To16|20To18|22To20|24To22|26To24|28To26|29To28|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|12To13|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|31To30|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|10To11|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|33To32|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|8To9|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|35To34|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|6To7|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|37To36|35To37|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|5To7|4To5|6To4|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|38To36|39To38|37To39|35To37|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|5To7|3To5|2To3|4To2|6To4|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|38To36|40To38|41To40|39To41|37To39|35To37|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|5To7|3To5|1To3|2To1|4To2|6To4|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|38To36|40To38|39To40|37To39|35To37|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|5To7|3To5|4To3|6To4|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|38To36|37To38|35To37|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|5To7|6To5|8To6|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|36To34|35To36|33To35|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|7To9|8To7|10To8|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|34To32|33To34|31To33|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|9To11|10To9|12To10|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|32To30|31To32|29To31|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|11To13|12To11|14To12|16To14|18To16|20To18|22To20|24To22|26To24|28To26|30To28|29To30|27To29|25To27|23To25|21To23|19To21|17To19|15To17|13To15|14To13|16To14|18To16|20To18|22To20|24To22|26To24|28To26|27To28|25To27|23To25|21To23|19To21|17To19|15To17|16To15|18To16|20To18|22To20|24To22|26To24|25To26|23To25|21To23|19To21|17To19|18To17|20To18|22To20|24To22|23To24|21To23|19To21|20To19|22To20|21To22| ``` Here's some pseudo code to demonstrate the method: ``` var mid=cursor=N/2,delta cursor++ // the cursor is where the empty space is. for(i=0; i++<N;){ delta = (mid%2^abs(mid+.5-i)%2-.5)*-2+1; // 1 or -1 print((cursor+delta) + 'To' + cursor + '|') cursor+=delta for(j=mid-abs(mid-i);j--;) { delta = i%2*4-2 // 2 or -2 print((cursor+delta) + 'To' + cursor + '|') cursor+=delta } } ``` [Answer] # C - 216 213 My solution is based on two facts: 1. The "to" field is the "from" field of the previous move (since you always create an empty slot in the space you move from, and ou always move to an empty slot) 2. There is a very regular pattern to the distances and directions that are moved. For the first 3 test cases, they are: `1 -2 1` `1 -2 -1 2 2 -1 -2 1` `1 -2 -1 2 2 1 -2 -2 -2 1 2 2 -1 -2 1` With that in mind I basically just wrote a program to produce and continue that pattern. I'm pretty sure there must be a really beautiful and much more elegant recursive way to write this, but I haven't figured it out yet: ``` #include <stdio.h> int main(int argc, const char *argv[]) { int upper_bound = atoi(argv[1]) / 2; int len; int from; int to = upper_bound + 1; int direction = 1; int i; for(len = 1; len <= upper_bound; ++len){ for(i = len-1; i >=0; --i){ from = to - direction*(1 + (i!=0)); printf("%02dTo%02d|",from,to); to = from; } direction*=-1; } for(i=1; i < len; ++i){ from = to - direction*2; printf("%02dTo%02d|",from,to); to = from; } direction*=-1; for(--len; len >= 0; --len){ for(i = 0; i < len; ++i){ from = to - direction*(1 + (i!=0)); printf("%02dTo%02d|",from,to); to = from; } direction*=-1; } return 0; } ``` And golfed (even though this was a code-challenge, not golf): ``` #define B {F=T-D*(1+(i!=0));printf("%02dTo%02d|",F,T);T=F;}D*=-1; L,F,T,D,i;main(int U,char**A){U=atoi(A[1])/2;T=U+1;D=1;for(L=1;L<=U;++L){for(i=L-1;i>=0;--i)B}for(i=1;i<L;++i)B for(--L;L>=0;--L){for(i=0;i<L;++i)B}} ``` ``` #define B {F=T-D*(1+(i!=0));printf("%02dTo%02d|",F,T);T=F;}D*=-1; L,F,T,D,i;main(int U){scanf("%d",&U);U/=2;T=U+1;D=1;for(L=1;L<=U;++L){for(i=L-1;i>=0;--i)B}for(i=1;i<L;++i)B for(--L;L>=0;--L){for(i=0;i<L;++i)B}} ``` [Answer] # Mathematica This approach builds a `Nest`ed sequence of the size and direction of the moves, formatted as `{fromPosition,toPosition}`, beginning with position `n`, where `n` refers to the number of match pairs. It then `Fold`s the sequence into a function that begins with move `{n, n+1}`. ``` z@n_:=(p=1;h@t_:=Append[{Table[2 (-1)^t,{t}]},{(-1)^(t+1)}]; k=Join[Reverse@Drop[#,n],#]&[Flatten@Nest[Prepend[#,h[p++]]&,{},n]]; Fold[Append[#,{#[[-1,1]]-#2,#[[-1,1]]}]&,{{n,n+k[[1]]}},Rest@k]) ``` --- ``` z[1] ``` > > {{1, 2}, {3, 1}, {2, 3}} > > > --- ``` z[4] ``` > > {{4, 5}, {6, 4}, {7, 6}, {5, 7}, {3, 5}, {2, 3}, {4, 2}, {6, 4}, {8, > 6}, {9, 8}, {7, 9}, {5, 7}, {3, 5}, {1, 3}, {2, 1}, {4, 2}, {6, > 4}, {8, 6}, {7, 8}, {5, 7}, {3, 5}, {4, 3}, {6, 4}, {5, 6}} > > > --- ``` z[7] ``` > > {{7, 8}, {9, 7}, {10, 9}, {8, 10}, {6, 8}, {5, 6}, {7, 5}, {9, 7}, {11, 9}, {12, 11}, {10,12}, {8, 10}, {6, 8}, {4, 6}, {3, 4}, {5, 3}, {7, 5}, {9, 7}, {11, 9}, {13, 11}, {14, 13}, {12, 14}, {10, 12}, {8, 10}, {6, 8}, {4, 6}, {2, 4}, {1, 2}, {3, 1}, {5, 3}, {7, 5}, {9, 7}, {11, 9}, {13, 11}, {15, 13}, {14, 15}, {12, 14}, {10, 12}, {8, 10}, {6, 8}, {4, 6}, {2, 4}, {3, 2}, {5, 3}, {7, 5}, {9, 7}, {11, 9}, {13, 11}, {12, 13}, {10, 12}, {8, 10}, {6, 8}, {4, 6}, {5, 4}, {7, 5}, {9, 7}, {11, 9}, {10, 11}, {8, 10}, {6, 8}, {7, 6}, {9, 7}, {8, 9}} > > > --- **Visualizing the Swaps** `r`, `b`, and `o` are images or a red match, a blue match, and no match, respectively. ![matches](https://i.stack.imgur.com/fKbkm.png) The following formats the output from `z` to display the swaps with matches. ``` swaps[n_]:=FoldList[Grid[{Permute[#[[1,1]],Cycles[{#2}]],Range[2n+1]}]&, Grid[{Join[Table[r,{n}],{o},Table[b,{n}]],Range[2n+1]}],z[n]] swapMatches[n_]:=Grid[Partition[swaps[n],2,2,1,""],Dividers->All] ``` `swaps` produces a list of states by using the ordered pairs of `z` as commands to permute the initial list and subsequent lists. ``` swaps[1] ``` ![swaps1](https://i.stack.imgur.com/8QBGX.png) `swapMatches` displays the states in a grid. ``` swapMatches[2] ``` ![swaps2](https://i.stack.imgur.com/0CZ9W.png) ``` swapMatches[3] ``` ![swaps3](https://i.stack.imgur.com/5Ti3o.png) [Answer] ## Javascript 191 ``` function f(N) { n=N>>=i=c=a='1';n++ s=z='0' for(k=b='34';i<N;k=i%2?a+=z+z:b+='44',i++)c=k+c t='' i=N*(N+1)/2 l=2*i+N for(;l;n+=(i>=1?r=c[i-1]:i<=-N?c[-i-N]:k[1])-2,t+=(s=n>9?'':z)+n+a+'|',--l,--i)a='To'+s+n return t } ``` Characters counted using `grep =|tr -d \ |wc -c` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/9035/edit) Your goal is to write a super-secret program which launches another (independent) program. You don't have to provide the payload in your answer, it can be any program name your program will launch. However, the challenge is to keep this behavior a secret. Upon casual inspection of the code, it should be impossible or very hard to notice that your program actually executes a foreign program. Bonus if this "hidden feature", once discovered, can reasonably be explained away as an unintentional bug. This is why the code has to be as clear as possible, and everything should have an alibi for being there, otherwise someone inspecting your code might become suspicious. Remember, this is **not** a code-golf, but an [underhanded](http://underhanded.xcott.com/) contest. * Your code has to be clear and readable. * The causes of the change have to be hidden. Even if discovered, they should look more like bugs than malice. You should provide an explanation, best in spoiler. > > like this > > > **The winner will be selected as the highest voted answer not sooner than 10 days after the first valid answer.** Yes, I know it's subjective, but this is the only criteria adequate for underhanded contests. Voters should value the standard "underhanded" qualities, like how clear the code is and how well hidden the reason is. I made this competition for compiled languages, but you can also use interpreted languages if you find two different notable interpreters for it. [Answer] ## Tcl Simple. ``` proc main {} { set fd [open filenames.txt] while {[gets $fd line] ne ""} { set other [open $line w] puts $other [clock format [clock seconds]] } } main ``` > > [Ilmari Karonen](https://codegolf.stackexchange.com/questions/9035/underhanded-launcher/12183?noredirect=1#comment23618_12183) is right: > > If you supply a filename with a `|` as first character, it will treat the rest as command. IIRC for Perl it has to be at the end. > > > [Answer] # JavaScript ``` if(document.location.href = 'http://www.example.com') foo(); ``` > > "document.loaction.href = 'http;//www.example.com'" sets the page location to "http;//www.example.com" instead of testing for the page location to be "http;//www.example.com". > > > It's an interpretted language, so here are two interpretters: SpiderMonkey and Google Chrome. ]
[Question] [ ## Summary The aim of this challenge is to write a *tenacious* program. This is a stateful program designed to output a given string, but for which, if the program is aborted at any point during the writing of the string, rerunning the program will continue where it left off, writing only the characters that have not been written so far. Specifically, the goal of this challenge is to output the string `01` using a tenacious program. ## Background I once conjectured that with *n* cits, any string up to length 2(*n*-*k*) could be ouptut by a tenacious program, for some small fixed *k*. I'm now leaning toward thinking the goal can't be achieved :-( This challenge, therefore, was designed to determine whether tenacious programs that output nontrivial strings are possible. `01` appears to be the shortest nontrivial goal string, and so is the subject of this challenge. **Current status**: So far there are no correct answers, but it has been proven that 2 cits are not enough. ## Data storage In order to store information across multiple runs of the program, you have access to a number of *cits*, bits made out of [non-volatile memory](https://en.wikipedia.org/wiki/Non-volatile_memory); these are persistent, stateful bits that can have the value **0**, **1**, or **undefined**. They have the value **0** before the first execution of the program. If the program is aborted midway through writing a cit, that cit's value becomes **undefined** (unless the value being written to the cit was the value previously stored there), and will remain undefined until the program writes a **0** to the cit (and is not aborted midway through the write). Reading an **undefined** cit will (unpredictably) produce **0** or **1** (maybe different for each read), and your program must function correctly regardless of what values are read from **undefined** cits. Each cit used by your program has a distinct address, which is an integer (you may choose how many cits are used, and what their addresses are). In order to read and write from the cits, you may assume that you have access to two functions: a function that takes a constant integer (representing the address of a cit), and returns a value read from that cit; and a function that takes an integer (representing the address of a cit) and a boolean (representing the value of a cit), and writes the value to the cit. These functions are guaranteed return in finite time (unless the program is aborted while they are running). You may choose the names of this functions as appropriate for the language you are using. If the language uses identifiers as function names, the recommended names are `r` to read, `w` to write. ## Output Due to the possibility that the program will be aborted during output, output from this challenge works a little differently from normal. Output may only be done a character at a time. You have access to a function that produces output in the following way: its argument is 0, 1, 2, or 3; if the given argument is the same as the argument to the previous call of the function (even in a previous execution of the program), or is 0 and no output has ever been produced, then the function does nothing. Otherwise, it outputs `0` if given an argument of 0 or 2, or `1` if given an argument of 1 or 3. You may choose the name of this function as appropriate for the language you are using. If the language uses identifiers as function names, the recommended name is `p`. ## Requirements Write a program with the following properties: * The only state used by the program between runs is a number of cits (as defined above); all other storage used by the program must be initialised to a fixed value at the start of each run. * The program will terminate in finite time, unless aborted. * If all the cits used by the program start with value **0**, and then the program is run, aborted after an arbitrary length of time (which could occur at any moment during the program's execution, even while writing a cit or writing output), run again, aborted after another arbitrary length of time, and this process is repeated until the program terminates naturally, then (no matter what timing was used for the aborts) the combined output from all the program executions will be `01`. * The program is single-threaded, making no use of parallelism or concurrency (this is required for the abort behaviour to be well-defined). (More generally, a "tenacious program" is any program with the properties above, with `01` replaced with any arbitrary string. But this challenge is just about writing a tenacious program to output `01`.) Alternatively, a proof that such a program is impossible is also considered a valid submission to this challenge. You may alternatively write a function instead of a program, but it is only allowed to store state between calls via using cits; it cannot look at any of the state of the program that called it. ## Example Here's an example of a C program that fails to solve the challenge: ``` // uses one cit with address 3 #include "hal.h" // assumed to define r(), w(), p() int main(void) { // entry point, no parameters or input if (r(3)==0) // cit 3 read as 0, that is state 0 or undefined w(3,0), // write 0 to cit 3, to ensure it's defined p(2); // put 2 with output '0' initially w(3,1), // mark we have output '0' p(1); // put 1 with output '1' } // halt ``` To see why this doesn't work, imagine that the first run of the program is aborted during `w(3,1)`: this outputs `0`, and causes cit 3 to become **undefined**. Then imagine that the second run happens to read the undefined cit as **1**, and is aborted after `p(1)` completes (but before the program ends); at this point, the output is `01`. The cit is still **undefined**, because writing **1** to an **undefined** cit does not define it (only writing **0** can define it). A third run of the program might now happen to read the undefined cit as **0**, thus causing `0` and `1` to be output again. This produces the output `0101`, which is not `01`. ## Checking the validity of your solution **@hammar** has written a checker that determines whether a given solution is valid (and/or explains why a particular solution isn't valid). To check your own solutions, or to see how it works, you can [Try it online!](https://tio.run/##rVhbT9tIFH73rzhKkRhvkyzhZVeoRkvb9LKipSpUfUgjMMmEjPCtHhvCFn47e86ZGV/iAO1qkdrYM@c25/qNl6G@lFF0/2PwDA4PPr79cvB2DG8PXp9oeDa48zwVZ2lewKs0KfI0Gn5Ik3AO4nopE3/zplt8HRbh8FDpwmutfAgzEPif71a/l2GkFkrO6/1QA/60@Y5lAQL/e4iP9pEPfzwvkdfFTSbhlSreJ3O5goAe4X1SeABzmasrlVyAGH/vw1E@78PxMr3G08xRDhEeF2EhkQd/zyNJbHALXxLNr09L@JSnF3kYQwjopZwYPsuizBPY28O1wX5NgFsvVTKnjZoJCUSL7NxvvSHTp7IgHjKssSN8VhWyvOroDQJz/q@5wtOtkWwSdZheENlxkdNZ13ffhVHRNBwXPS2/Y/SyEWS76D4@Gr6Ib6zCvO7i6w29Wp@IFdz4PqUS@TeZSXhTJrMizSvBzomLuCHbaBJWSDbycbkh4yDLIjULC3UlO3KyMqfgGlZ6H8GL3/abYllJQ5rJ@XU5udHdkCT29wPfHtzmwrHUWqVEZZ@Q7AfMVKFtBDQu9CEti8zEdIKRmPJaFOqiDjQvLdHnksP7Mk0jXLp7KhfHV5J5A06McR1zI/KWUmlcvXBqHJezGdq6gZa3D86x@OQmUZgvY5st/P6OrR0/WjBcppRoAUwEG9tnr/hTz5st5eyynWKNVGVH8fsR5Z4hzixlAhdpGEGAumehllDIJESn34BwFPv7bJ9vCNMFUgKcMFlaaiDBGBE8zWECvZOlrEQrbaUh2bDHbO@TK2xFc9Ca2OYpL8LD/MrQD2G8CuMMOwymXSkx0/Z6lnWR5h9OQfyjMpiMhsMpivZhC74J1QcRpRd90L7fUob5WEYyr94q5VvQ@1wm8KwHz5@DRq@DoqdeH81WhcLDa2p3e8AEqDgObQNMQD8gHCuRzKt0DC0fBxASH9BEJOZKMawY34ZFuTTlKeGPP2E72Pa8vEw6XdDVDgUbJ8bNuYSwT8nSd1uYJcTo2sDKB82J9HepC1j1YTIlR1ki7j8rWBgidpzIR1hn@E9jA3kxAKJb8ak5a/KRSwwWeAPGlHyXmMhbET7pXR9z3SzaVytJLLC1oegpi/iYFkvbRyfCvlTKrYlU7u1DCB9PIbhI8TzcN/BAyLPtTysP6220wLULDb8HQBNPY6NxiwFx2yYTuAdNR5is4CxO52ewO4W7KsBA9Ys2yvxaoSP4DyU6b2M3RFPYUOerKE0vy4ymLO6AsJY6/9lJujKnr8IjTFMijvbpfOMzN3N/mg2tXpH7Jzt9GE2tV83AY2ofhIa/qsyynTgwP3c@H6fl@XZHdBpTqlrsbay0IcWto6g@HaCOs5VUNU8rKTTvAGuS3PpdM8oWlbQ9PTMjxPzVBgRQZjgApCNDRGSKmhU04mxkV9uBiaZA21hfFcEH/wS6@tR3b1S2JmQ7T7Bh4rvwcidr4Ksn2KyCU7@hbeRVfM53j7rg//aAO7T/Cx5Yd9wve2DU9sCTbJu1cY2YWdhpPHaEt4oMs9TikABO8lJSkoKRQoM81hcbBDE2wK31Kieo7qqRsKYFSY3VDcgpwAnKo2sdP6HSNnYKOAj92uA3YYTBvWtdEbS5Hmi@ltSwxl0E/EcBTMOSppihjLPiBvfral1D3ExqflmNt9ZBeT8mOEniFji8vqpi@VouwjKim1CVcEQde16d7F1FJrPbSnWDQzFtQ2ZDOz9tsRFzSc3FUsfQEVDV0GZ2xNMy79DGFqmeOIgWNGDYbYWtOIWag/9RVOlkdcBjhRqduprWATSDHOF8wZdJE0hUX6ck4Yq6L3PZETGnb9FGLTXHmvl@2wgn40ppRYk6mTbd0NkWQvfRXhxAsEfQ0HMjmwyOZXyOgKumDlq8WlfUFrXybCcSul67KFUMhDu1gQpCbxP85EG7Z/Uj9DnFemNE4oCP86Seel0sEVQhJRx4JXNqtsIgNSfVNHNDVXcFvkSae4/brAf5GrhplLx9uKtssQt8bMcWcNg3mmtJzpT@lMuFWh0tzgyx1wTL9XW8Ya29DK2BapTZm1Ajs5h7XsYZl0lS4yZC6FOYGN0NuqMGdOtNe84GA7xrG1pXqY4lFqaDkIZqxlSI0OnLDiLyAUH4Qq6KNescdjATkwnstGRBGwelgWqCm4SP4KwxgXo5Acn6XrLiQ8EiT2Nuas0rS1ewwcTdQUeCyUUNuV3mNqyrrSPm6zzFOHXMKtKfMKoN8tpyHS65XipsstdISb3rv@lx43TD4XG1S2/n@EZnmXLAVKoiXeeRmxc2fdZzgSBvgvc4mJjEwpKup5g7PVPe4q2TcflwmAwImbsssoxu9ijKw7VTO5IaLmIBfemBsfio@nTSLbxWxThjacizBuHuQabcQNQuF9Vtyuz56J7MfFhzVV59FbO6aNsUdxFeUp1vmSrFu65E67cBb7medz8YwIhc0jdzRmnYGXlxqAjomG8Y0n4UGNlbjOe5FXtrnZEn@RLGLt7xjTOpe1Aj26GObb8LECDroWyVFDJPUN95HiazpfnMYO5FVoZFq3TmXfvtrxcukGsTb5ezvTKy3yhH9/f/Ag "Haskell – Try It Online"). ## Victory condition The program that achieves the requirements above using the fewest cits wins. In the case of a tie, programs which make fewer writes to cits per program execution are considered better (with the worst case more important than the best case); if there is still a tie, the shortest program (not counting the declarations of the provided functions) wins. [Answer] While I don't have a solution nor a proof of impossibility, I figured I'd post my test harness for anyone wanting to play around with this, as I've pretty much given up at this point. It's an implementation of the HAL modelling programs as a Haskell monad. It checks for tenacity by doing a breadth-first search over the possible sessions to check for sessions which either 1. have halted once without producing the correct output, or 2. have produced an output that is not a prefix of the desired one (this also catches programs producing infinite output). ``` {-# LANGUAGE GADTs #-} module HAL where import Control.Monad import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set newtype CitIndex = Cit Int deriving (Eq, Ord, Show) data CitState = Stable Int | Unstable deriving (Eq, Ord, Show) data Program a where Return :: a -> Program a Bind :: Program a -> (a -> Program b) -> Program b Put :: Int -> Program () Read :: CitIndex -> Program Int Write :: CitIndex -> Int -> Program () Log :: String -> Program () Halt :: Program () instance Monad Program where return = Return (>>=) = Bind data Session = Session { cits :: Cits , output :: [Int] , lastPut :: Int , halted :: Bool } deriving (Eq, Ord, Show) data Event = ReadE CitIndex Int | PutE Int | WriteSuccessE CitIndex Int | WriteAbortedE CitIndex Int | LogE String | HaltedE deriving (Eq, Ord, Show) type Log = [(Event, Cits)] check :: Program () -> Int -> [Int] -> IO () check program n goal = case tenacity (program >> Halt) goal of Tenacious -> putStrLn "The program is tenacious." Invalid ss -> do putStrLn "The program is invalid. Example sequence:" forM_ (zip [1..] ss) $ \(i, (log, s)) -> do ruler putStrLn $ "Run #" ++ show i ++ ", Initial state: " ++ formatState n s ruler mapM_ (putStrLn . formatEvent n) log where ruler = putStrLn $ replicate 78 '=' run :: Program a -> Session -> [(Maybe a, Log, Session)] run (Return x) s = [(Just x, [], s)] run (Bind x f) s = do (r1, l1, s1) <- run x s case r1 of Just y -> [(r2, l1 ++ l2, s2) | (r2, l2, s2) <- run (f y) s1] Nothing -> [(Nothing, l1, s1)] run (Put x) s = [(Just (), [(PutE x, cits s)], s')] where s' | lastPut s /= x = s { lastPut = x, output = output s ++ [x `mod` 2] } | otherwise = s run (Read cit) s = case lookupCit cit (cits s) of Stable x -> [(Just x, [(ReadE cit x, cits s)], s)] Unstable -> [(Just x, [(ReadE cit x, cits s)], s) | x <- [0, 1]] run (Write cit x) (s @ Session { cits = cits }) = [(Just (), [(WriteSuccessE cit x, completed)], s { cits = completed }), (Nothing, [(WriteAbortedE cit x, aborted )], s { cits = aborted })] where state = lookupCit cit cits completed = updateCit cit newState cits where newState = case (x, state) of (0, _) -> Stable 0 (1, Unstable) -> Unstable (1, Stable _) -> Stable 1 aborted = updateCit cit newState cits where newState = case (x, state) of (0, Stable 0) -> Stable 0 (0, _) -> Unstable (1, Stable 1) -> Stable 1 (1, _) -> Unstable run (Halt) s = [(Just (), [(HaltedE, cits s)], s { halted = True })] run (Log msg) s = [(Just (), [(LogE msg, cits s)], s)] newSession :: Session newSession = Session { cits = initialCits , output = [] , lastPut = 0 , halted = False } newtype Cits = Cits (Map CitIndex CitState) deriving (Eq, Ord, Show) initialCits = Cits (Map.empty) lookupCit :: CitIndex -> Cits -> CitState lookupCit cit (Cits m) = Map.findWithDefault (Stable 0) cit m updateCit :: CitIndex -> CitState -> Cits -> Cits updateCit index (Stable 0) (Cits m) = Cits $ Map.delete index m updateCit index newState (Cits m) = Cits $ Map.insert index newState m data Tenacity = Tenacious | Invalid [(Log, Session)] deriving (Eq, Ord, Show) tenacity :: Program () -> [Int] -> Tenacity tenacity program goal = bfs Set.empty [(newSession, [])] where bfs :: Set Session -> [(Session, [(Log, Session)])] -> Tenacity bfs visited [] = Tenacious bfs visited ((s, pred) : ss) | Set.member s visited = bfs visited ss | valid s = bfs (Set.insert s visited) $ ss ++ [(s', (l, s) : pred) | (_, l, s') <- run program s] | otherwise = Invalid $ reverse (([], s) : pred) valid :: Session -> Bool valid Session { output = output, halted = halted } | halted = output == goal | otherwise = output `isPrefixOf` goal formatState :: Int -> Session -> String formatState n s = "[cits: " ++ dumpCits n (cits s) ++ "] [output: " ++ dumpOutput s ++ "]" formatEvent :: Int -> (Event, Cits) -> String formatEvent n (event, cits) = pad (78 - n) text ++ dumpCits n cits where text = case event of ReadE (Cit i) x -> "read " ++ show x ++ " from cit #" ++ show i PutE x -> "put " ++ show x WriteSuccessE (Cit i) x -> "wrote " ++ show x ++ " to cit #" ++ show i WriteAbortedE (Cit i) x -> "aborted while writing " ++ show x ++ " to cit #" ++ show i LogE msg -> msg HaltedE -> "halted" dumpCits :: Int -> Cits -> String dumpCits n cits = concat [format $ lookupCit (Cit i) cits | i <- [0..n-1]] where format (Stable i) = show i format (Unstable) = "U" dumpOutput :: Session -> String dumpOutput s = concatMap show (output s) ++ " (" ++ show (lastPut s) ++ ")" pad :: Int -> String -> String pad n s = take n $ s ++ repeat ' ' ``` Here is the example program given by the OP converted to Haskell. ``` import Control.Monad (when) import HAL -- 3 cits, goal is 01 main = check example 3 [0, 1] example = do c <- Read (Cit 2) d <- Read (Cit c) when (0 == c) $ do Log "in first branch" Write (Cit 2) 0 Write (Cit 1) 0 Write (Cit 1) (1 - d) Write (Cit 2) 1 Write (Cit 0) 0 when (d == c) $ do Log "in second branch" Put 2 Write (Cit 2) 0 Write (Cit 0) 1 Put 1 ``` And here is the corresponding output, showing that the program is not tenacious. ``` The program is invalid. Example sequence: ============================================================================== Run #1, Initial state: [cits: 000] [output: (0)] ============================================================================== read 0 from cit #2 000 read 0 from cit #0 000 in first branch 000 wrote 0 to cit #2 000 wrote 0 to cit #1 000 wrote 1 to cit #1 010 wrote 1 to cit #2 011 wrote 0 to cit #0 011 in second branch 011 put 2 011 wrote 0 to cit #2 010 wrote 1 to cit #0 110 put 1 110 halted 110 ============================================================================== Run #2, Initial state: [cits: 110] [output: 01 (1)] ============================================================================== read 0 from cit #2 110 read 1 from cit #0 110 in first branch 110 wrote 0 to cit #2 110 wrote 0 to cit #1 100 wrote 0 to cit #1 100 aborted while writing 1 to cit #2 10U ============================================================================== Run #3, Initial state: [cits: 10U] [output: 01 (1)] ============================================================================== read 1 from cit #2 10U read 0 from cit #1 10U wrote 0 to cit #0 00U aborted while writing 1 to cit #0 U0U ============================================================================== Run #4, Initial state: [cits: U0U] [output: 01 (1)] ============================================================================== read 0 from cit #2 U0U read 0 from cit #0 U0U in first branch U0U wrote 0 to cit #2 U00 wrote 0 to cit #1 U00 wrote 1 to cit #1 U10 wrote 1 to cit #2 U11 wrote 0 to cit #0 011 in second branch 011 put 2 011 wrote 0 to cit #2 010 wrote 1 to cit #0 110 put 1 110 halted 110 ============================================================================== Run #5, Initial state: [cits: 110] [output: 0101 (1)] ============================================================================== ``` [Answer] Unless someone can find a bug in this program, I think it checks and rejects every relevant two-cit program. I argue that it suffices to consider programs which read all the cits and switch on a number formed by the set. Each branch of the switch will be a series of writes and puts. There's never any point putting the same number more than once in a branch, or putting the second output digit before the first one. (I'm morally certain that there's no point outputting the first digit other than at the start of a branch or the second digit other than at the end, but for now I'm avoiding that simplification). Then each branch has a target set of cits it wants to set, and moves towards it by setting the bits it wants to be 0 as 0, and the bits it wants to be 1 as 0 then 1; these write operations can be ordered in various ways. There's no point setting a bit to 1 unless you've already set it to 0 in that run, or it's likely a nop. It considers 13680577296 possible programs; it took a 4-core machine just under 7 hours to check them all without finding a single solution. ``` import java.util.*; // State is encoded with two bits per cit and two bits for the output state. // ... [c_2=U][c_2=1/U][c_1=U][c_1=1/U][output_hi][output_lo] // Output state must progress 0->1->2. // Instruction (= program branch) is encoded with three or four bits per step. // The bottom two bits are the cit, or 0 for output/loop // If they're 0, the next two bits are 01 or 10 for output state, or 11 for halt. // Otherwise the next two bits are the value to write to the cit. public class CitBruteForcer implements Runnable { static final int[] TRANSITION_OK = new int[]{ // Index: write curr_hi curr_lo 0, // write 0 to 0 => 0 0, // write 0 to 1 => 0 0, // write 0 to U => 0 -1, // invalid input 1, // write 1 to 0 => 1 1, // write 1 to 1 => 1 2, // write 1 to U => U -1 // invalid input }; static final int[] TRANSITION_ABORT = new int[]{ // Index: write curr_hi curr_lo 0, // write 0 to 0 => 0 2, // write 0 to 1 => U 2, // write 0 to U => U -1, // invalid input 2, // write 1 to 0 => U 1, // write 1 to 1 => 1 2, // write 1 to U => U -1 // invalid input }; private final int[] possibleInstructions; private final int numCits, offset, step; private long tested = 0; private CitBruteForcer(int numCits, int[] possibleInstructions, int offset, int step) { this.numCits = numCits; this.possibleInstructions = possibleInstructions; this.offset = offset; this.step = step; } public void run() { int numStates = 1 << numCits; int n = possibleInstructions.length; long limit = pow(n, numStates); for (long i = offset; i < limit; i += step) { // Decode as a base-n number. int[] instructions = new int[numStates]; long tmp = i; for (int j = 0; j < numStates; j++, tmp /= n) instructions[j] = possibleInstructions[(int)(tmp % n)]; Program p = new Program(numCits, instructions); if (p.test()) System.out.println("Candidate: " + i); tested++; } } public static void main(String[] args) { int numCits = 2; int numThreads = 4; int[] possibleInstructions = buildInstructions(numCits); int numStates = 1 << numCits; int n = possibleInstructions.length; System.out.println(n + " possible instructions"); long limit = pow(n, numStates); CitBruteForcer[] forcers = new CitBruteForcer[numThreads]; for (int i = 0; i < numThreads; i++) { forcers[i] = new CitBruteForcer(numCits, possibleInstructions, i, numThreads); new Thread(forcers[i]).start(); } int pc = 0; while (pc < 100) { // Every 10 secs is easily fast enough to update try { Thread.sleep(10000); } catch (InterruptedException ie) {} long tested = 0; for (CitBruteForcer cbf : forcers) tested += cbf.tested; // May underestimate because the value may be stale int completed = (int)(100 * tested / limit); if (completed > pc) { pc = completed; System.out.println(pc + "% complete"); } } System.out.println(limit + " programs tested"); } private static int[] buildInstructions(int numCits) { int limit = (int)pow(3, numCits); Set<Integer> instructions = new HashSet<Integer>(); for (int target = 0; target <= limit; target++) { int toSetZero = 0, toSetOne = 0; for (int i = 0, tmp = target; i < numCits; i++, tmp /= 3) { if (tmp % 3 == 0) toSetZero |= 1 << i; else if (tmp % 3 == 1) toSetOne |= 1 << i; } buildInstructions(0xc, toSetZero, toSetOne, false, false, instructions); } int[] rv = new int[instructions.size()]; Iterator<Integer> it = instructions.iterator(); for (int i = 0; i < rv.length; i++) rv[i] = it.next().intValue(); return rv; } private static void buildInstructions(int suffix, int toSetZero, int toSetOne, boolean emitted0, boolean emitted1, Set<Integer> instructions) { if (!emitted1) { buildInstructions((suffix << 4) + 0x8, toSetZero, toSetOne, false, true, instructions); } if (!emitted0) { buildInstructions((suffix << 4) + 0x4, toSetZero, toSetOne, true, true, instructions); } if (toSetZero == 0 && toSetOne == 0) { instructions.add(suffix); return; } for (int i = 0; toSetZero >> i > 0; i++) { if (((toSetZero >> i) & 1) == 1) buildInstructions((suffix << 3) + 0x0 + i+1, toSetZero & ~(1 << i), toSetOne, emitted0, emitted1, instructions); } for (int i = 0; toSetOne >> i > 0; i++) { if (((toSetOne >> i) & 1) == 1) buildInstructions((suffix << 3) + 0x4 + i+1, toSetZero | (1 << i), toSetOne & ~(1 << i), emitted0, emitted1, instructions); } } private static long pow(long n, int k) { long rv = 1; while (k-- > 0) rv *= n; return rv; } static class Program { private final int numCits; private final int[] instructions; private final Set<Integer> checked = new HashSet<Integer>(); private final Set<Integer> toCheck = new HashSet<Integer>(); Program(int numCits, int[] instructions) { this.numCits = numCits; this.instructions = (int[])instructions.clone(); toCheck.add(Integer.valueOf(0)); } boolean test() { try { while (!toCheck.isEmpty()) checkNext(); } catch (Exception ex) { return false; } // Need each reachable state which hasn't emitted the full output to be able to reach one which has. Set<Integer> reachable = new HashSet<Integer>(checked); for (Integer reached : reachable) { checked.clear(); toCheck.clear(); toCheck.add(reached); while (!toCheck.isEmpty()) checkNext(); boolean emitted = false; for (Integer i : checked) { if ((i.intValue() & 3) == 2) emitted = true; } if (!emitted) return false; } return true; } private void checkNext() { Integer state = toCheck.iterator().next(); toCheck.remove(state); checked.add(state); run(state.intValue()); } private void run(final int state) { // Check which instructions apply for (int i = 0; i < instructions.length; i++) { boolean ok = true; for (int j = 1; j <= numCits; j++) { int cit = (state >> (2 * j)) & 3; if (cit == 2 || cit == ((i >> (j-1)) & 1)) continue; ok = false; break; } if (ok) run(state, instructions[i]); } } private void run(int state, int instruction) { while (true) { int cit = instruction & 3; if (cit == 0) { int emit = (instruction >> 2) & 3; if (emit == 3) break; if (emit > (state & 3) + 1 || emit < (state & 3)) throw new IllegalStateException(); state = (state & ~3) | emit; instruction >>= 4; } else { int shift = 2 * cit; int transitionIdx = (instruction & 4) + ((state >> shift) & 3); int stateMasked = state & ~(3 << shift); consider(stateMasked | (TRANSITION_ABORT[transitionIdx] << shift)); state = stateMasked | (TRANSITION_OK[transitionIdx] << shift); instruction >>= 3; } // Could abort between instructions (although I'm not sure this is strictly necessary - this is "better" than the mid-instruction abort consider(state); } // Halt or loop. consider(state); } private void consider(int state) { if (!checked.contains(state)) toCheck.add(state); } } } ``` [Answer] This is was my best attempt at answering my own question. I am uncertain that it meets requirement 3, and am open to refutation. It is not tenacious :-( ``` /* 1 */ #include "hal.h" /* 2 */ main(){ /* 3 */ unsigned c = r(2); // get cit 2 into c /* 4 */ unsigned d = r(c); // get cit c into d /* 5 */ // here if d==c then we have not output 1 yet /* 6 */ // else we have output 0 /* 7 */ if (0==c) /* 8 */ w( 2, 0 ), // cit 2 to 0 /* 9 */ w( 1, 0 ), // cit 1 to 0 /* 10 */ w( 1,!d ), // cit 1 to complement of d /* 11 */ w( 2, 1 ); // cit 2 to 1 /* 12 */ w( 0, 0 ); // cit 0 to 0 /* 13 */ if (d==c) /* 14 */ p( 2 ), // put 2, first one outputs 0 /* 15 */ w( 2, 0 ); // cit 2 to 0 /* 16 */ w( 0, 1 ); // cit 0 to 1 /* 17 */ p( 1 ); // put 1, first one outputs 1 /* 16 */ } // halt ``` ]
[Question] [ Given two strings \$A\$ and \$B\$ with edit (Levenshtein) distance \$x\$, find a third string with edit distance \$a\$ to \$A\$ and edit distance \$b\$ to \$B\$ so that \$a+b=x\$ and \$a=int(x/2)\$ (that is half of \$x\$ rounded down to the nearest integer). The input is the two strings \$A\$ and \$B\$ and their edit distance \$x\$. You don’t need to compute \$x\$. \$A\$ is of length \$n\$ and \$B\$ is of length \$m\$ such that \$n/2 \le m \le n\$. Your can take the input in any convenient format you like. # Examples ``` Inputs: "hello", "hallo", 1. Output: "hello" Inputs: "sitteng", "kitten", 2. Output: "sitten" Inputs: "bijamas", "banana", 4. Output: "banamas" Inputs: "Pneumonoultramicroscopicsilicovolcanoconiosis", "noultramicroscopicsilicovolcanoconiosis", 6. Output: "umonoultramicroscopicsilicovolcanoconiosis" ``` # Restriction Your code must be run in \$O(n^2)\$ time where \$n\$ is the length of A. [Answer] # [Python](https://www.python.org), ~~459~~ ~~514~~ 502 bytes *+60 bytes, use correct initial condition* *-11 bytes, thanks to ValueInk* *-1 byte, thanks to c--* ``` l=len I=range def f(s,t): m,n=l(s),l(t);w=m-~n;M=[[([t[:k]+s for k in I(j+1)],j)for j in I(n+1)]]+[[([s[k:]for k in I(i+2)],0)]+n*[0]for i in I(m)] for j in I(n): for i in I(m):D,d=M[i][j+1];U,u=M[i+1][j];R,r=M[i][j];a=l(D:=D+[p[:d]+p[d+1:]])if(p:=D[-1])[:d]==t[:d]else w;b=l(U:=U+[p[:u]+[t[j]]+p[u:]])if(p:=U[-1])[:u]==t[:u]else w;c=l(R:=R+[[],[p[:r]+[t[r]]+p[r+1:]]][p[r]!=t[r]])if(p:=R[-1])[:r]==t[:r]else w;M[i+1][j+1]={b:(U,u+1),c:(R,r+1),a:(D,d)}[min(a,b,c)] return(p:=M[m][n][0])[~-l(p)//2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZPNbtwgEMfVq_sSTi6BmG2yOVVY3PaSw0rVSntCc8BeO8GLwQLcqKqaF-kll_ah-iA9d7DXSSpVUUHCzMfvDzPI338OX-K9s09PP8bYrj7-evfbCNPY7FZ4Ze-a7NC0eUsCi5Rnec-sMCRQZkik5YPoV4-23AopiYySH6EIeet8fsy1zW9JV6wpsI4mVze7bHJBkYAgjxxeZeviBrOvKRT2Ul5PET1HegpZ_lokXSX_K4Fv2EFspQaJh0K5Z2OycCs7KHfMn2JQKrz_hotNIQfJD1AM8lCsOQDVLRnQL1droCkiREyfxoQmfygrxPZc7CdsxAIiiiV6fGH3J3ac2XFha2R3XOywamCJ9xPvJ95PpwO6PZyJyXuS253k_CznF7mlLlzE14oTrBWbympOsM60U5xgN-g32WtLFKtYnfrnmzh6m4S3sgdpAXtM5ePKkIFeXd3A8vzvB69tJBcXHzqHfEuMDpGc3zfGuHN8-NlSk4Uj-3d60DE29u4ZOE72W0SlO9Wr8ExUyuJ8i_hkm7F31o0metXr2rtQu0HXQRtdu8_O1Mq62lntgn7R_e98HHNPll_jDw) Input&Output as lists of characters. *For some examples the result is different from the result in the question, but also satisfies the distance requirement* ## Explanation Uses modified version of the [dynamic programming algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix) for the computation of the Levenshtein distance. Each cell stores the current prefix length and the path of all previous edits. At the end the cell in the middle of the path is returned. ungolfed code: ``` def levDist(s,t): m,n=len(s),len(t) w=m+n+1 # one larger than the largest possible Levenshtein distance M=[] # initialize first row and column for i in range(0, m+1): M.append([([s[k:] for k in range(i+1)],0)]+[0]*n) for j in range(1, n+1): M[0][j]=([t[:k]+s for k in range(j+1)],j) for j in range(0, n): for i in range(0, m): # cell i,j -> shortest edit path that: # 1) only modifies the first i characters in s # 2) ends with a word starting with the first j characters in t D,d=M[i][j+1] # deletion U,u=M[i+1][j] # insertion R,r=M[i][j] # substitution # for each edit type check if the previous cell contains the correct prefix and if yes perform the repetitive edit if (p:=D[-1])[:d]==t[:d]: D=D+[p[:d]+p[d+1:]] a=len(D) else: a=w if (p:=U[-1])[:u]==t[:u]: U=U+[p[:u]+[t[j]]+p[u:]] b=len(U) else: b=w if (p:=R[-1])[:r]==t[:r]: if p[r]!=t[r]: R=R+[p[:r]+[t[r]]+p[r+1:]] c=len(R) else: c=w x=min(a,b,c) # find operation with the shortest edit path if x==a: M[i+1][j+1] = (D,d) elif x==b: M[i+1][j+1] = (U,u+1) else: M[i+1][j+1] = (R,r+1) return ((p:=M[m][n][0])[(len(p)-1)//2],M[m][n]) # the ungolfed version also returns the complete edit path ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVSxbtswEJ269CuuySJWchJlKgyok8dmMeCJ4EBLJ5uORAokZcf9lS5Z2n9qv6ZHSo4c14UBC-I9vvfu8cQfv7qj3xr9-vqz9_Xsy58PuwpraHC_UM4nLvNs_hGgzXTRoE4cy8LDM1o7FG2q0xxuwWiERtoNWvBbqelvfHceOuOcWjcI33CP2m09Kg0VcUtdIrE8FVzQ4xaUVl7JRn1HqJWlndYcQOoKStP0rSZMbSwowoGVeoPJQwZtmkd7RHMnuw51lfCEO_48FxH9PKEVQUX2wETKH8RnzUa-3YTIM9ATH6H4ThQJ93z-LFJ3ybeLfLsrPORLjyxXHI-V0HGJTQMq28HsK7itsT7khZWi0KTfhij9BM4ZxdwcoTWVqhW6GPIQlIJyK60sPVoXxBy87XpkQKE4OCgilHAwtgKK3nqlN8PiRLO7oPEnmkVWFU9cUR5pLoi0wga9Mnosr7I-lKlGgcWDdGjP6svMjttF9OT6tfPK92eQ25gUynI79O-PHZIbLCnwOlrsLO6V6d0QWmm0l6QTS6WxFksfILV6iSNDm44UUYeWeNuIstiRaa_2GCVGYQIm3bxY8FkuGJ9Xoih8eJxyp-aLRcq7sJZ2vErzuRBvNRm_iQUbF7BxOD8rHt6LrEaRfhDpz0RWxSqK9DSdnnIKWv250joqra4rrS-VlqOSHZTsmRIhOm7FJ1o_X6ZTKpbRgo0WbLRg37dbRhPL6ybKNxMvRat0IrN1VrJwsooOxNBRyHDg09D9O_FTEy9FISfq03CF6SsgoXGcLAzg9X_BNJz0oV51fIGkMR2QFn1vNSQhySfeCq4FXQaMJ6H7js1ydn__KLKxFFoM7fR6Y5oaK9jT5xMalY0zI9dpTtuOPhycGh6u3N93nVXaJ6c7twl_N2u1k610N3ThDu9S0--GMTbsOl3YfwE) [Answer] # [Haskell](https://www.haskell.org), ~~182~~ 175 bytes, not in \$O(n^2)\$ *-7 bytes thanks to [@Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)* ``` import Data.List l=length (x:w)#(y:z)|x==y=map(x:)$w#z a@(x:w)#b|y:z<-b=sortOn l[a:w#b,a#z++[b],a:map(y:)(w#z)]!!0|1>0=a:w#[] _#(y:z)=[]#z++[y:z] _#_=[[]] a%b=b#a!!div(l$b#a)2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVPRatswFIU96itu4rZIRA5J1sEwUdjDxhgU9gFCpFert3i13KzSGjvkT_rSl7LHfc_2NbuyHa-ljoPOPefcK3GvfP9rg_46L8uHh8ef4Wv69s_vwm1vbgO8x4DTi8IHVqoyr76FDeN1thMJb7K9ONRKNcrhljhxskv2DN91sj2Qvkyt8lTlcwWlxmyXWInJfjLR1kjMYlqTCU5pwoxGs8N8NVPRpQ1bd_WVNq2fcOTWSmtjGJ5aZRMcja6KO16eEBSL7th_X310RfUasgw-VQHS1cuFtQYFnFaYCpgCAcbK_C5mffgBCGoFGk3090tMiwZt4qtgdozokI0XxMxhAj3X-FalNtQktf6jWnuKn6p9_gFqUAoasva250WebdOen_e-ThFd3LujlQ91BGMh9-EL-txTBc2AHj7e0LBvxhLGG-zAPOKWFLL3-CIEGnl0XbeQ0IKCjv_vs8V3dOijz2JFP0LnfRD5wThsSv83cRmU8bD7UWkFw5hDmpOC7W1BI9TcybZFCK7vqQMbe9eRFs7OBv0Je0k35RIWsdMcJVgJVxLWApYpDM2R4JapRjgFS3esu0_Hz-Ef) --- Edit: I remembered that the Levenshtein distance could be calculated in quadratic time, but I didn't remember *which* algorithm was the one with this time complexity and I didn't bother to check the complexity of the naive one. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/258728/edit). Closed 12 months ago. [Improve this question](/posts/258728/edit) [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) is a partition of a plane (or part of plane) into regions close to each of a given set of objects ("seeds"). Here we’ll be dealing with discrete arrays or even rather with ASCII-art: ``` 2 2 4 4 4 4 1 1 1 1 1 1 1 3 3 3 3 2 2 4 4 4 1 1 1 1 1 1 1 3 3 3 3 3 2 2 4 4 4 1 1 1 1 1 1 3 3 3 3 3 3 2 2 2 4 1 1 1 1 1 1 3 3 3 3 3 3 3 2 2 2 1 1 1 1 1 1 3 3 3 3 3 3 3 3 2 2 2 1 1 1 1 1 1 3 3 3 3 3 3 3 3 2 2 2 1 1 1 1 1 1 3 3 3 3 3 3 3 3 5 5 5 1 1 1 1 1 1 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 1 1 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 ``` Since it is not difficult to draw a discrete Voronoi diagram, we will go a little further and consider [Lloyd's algorithm](https://en.wikipedia.org/wiki/Lloyd%27s_algorithm). #### Short description It repeatedly finds the centroid of each cell in the Voronoi partition and then re-partitions the input according to which of these centroids is closest. The process converges quickly to a certain precision, but for real numbers formally infinitely long. For integer coordinates the process should always stop. To find Voronoi cells you can use any of the algorithms of several known. Like just brutal-force tagging with nearest seed, or something [like this](https://en.wikipedia.org/wiki/Jump_flooding_algorithm). It seems that with the next distance functions process will be converge (but I have no math proof): * SquaredEuclidean distance * Euclidean distance * [Chessboard (Chebyshev) distance](https://en.wikipedia.org/wiki/Chebyshev_distance) * [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) * [Canberra distance](https://en.wikipedia.org/wiki/Canberra_distance) Probably with slightly different visual results. You can use any distance that is suitable for golfing in your language. #### Challenge Print out ASCII art as a result of Lloyd's algorithm for given initial seeds. #### Input * Width `W` and height `H` of the board. Integers `W, H > 0` and not very big (no more than `100` I think) * Initial array of seeds as explicit list of coordinates: `[[4,5], [1,1], …]` * Number of seeds (as length of array) `N` should be `0 < N < 10` (for not to break print formatting) #### Output Final state of Lloyd's process as a pretty-printed array of ASCII strings, where `"0"` is used for any seed and `"1"..."9"` digits for filling corresponding cells. Might be interesting to print firstly initial state. #### Test cases The main test is that the code is not broken in obvious cases, for example: ``` Input: W:2, H:2, initial seeds: [[1,1]] Output: 01 11 ``` ``` Input: W:10, H:1, initial seeds:[[1, 1], [2, 1]] Output: 1011220222 ``` Simple program on Mathematica 12.2 was used for samples. With [`ChessboardDistance`](https://reference.wolfram.com/language/ref/ChessboardDistance.html?q=ChessboardDistance) as distance function, [`Nearest`](https://reference.wolfram.com/language/ref/Nearest.html) as core for Voronoi tessellation and [`FixedPoint`](https://reference.wolfram.com/language/ref/FixedPoint.html), `Floor@Mean@Position` combination for Lloyd relaxation. ``` Input: W:13, H:10, initial seeds: [[2, 3], [4, 7], [8, 8], [9, 11]] ``` Initial Voronoi partition: ``` 1 1 1 1 1 1 2 2 2 2 2 2 2 1 1 0 1 1 2 2 2 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 2 2 3 1 1 1 1 1 2 0 2 2 2 2 3 3 1 1 1 1 2 2 2 2 2 2 3 3 4 1 1 1 2 2 2 2 2 2 3 3 4 4 1 1 2 2 2 3 3 3 3 3 4 4 4 1 2 2 2 3 3 3 0 3 4 4 4 4 2 2 2 3 3 3 3 3 3 4 0 4 4 2 2 3 3 3 3 3 3 3 4 4 4 4 ``` Result of the Lloyd process: ``` 1 1 1 1 1 2 2 2 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 2 2 4 1 1 0 1 1 2 2 0 2 2 2 4 4 1 1 1 1 1 2 2 2 2 2 4 4 4 1 1 1 1 1 2 2 4 4 4 4 4 4 1 3 3 3 3 3 3 4 4 4 4 4 4 3 3 3 3 3 3 3 4 4 4 0 4 4 3 3 3 0 3 3 3 4 4 4 4 4 4 3 3 3 3 3 3 3 4 4 4 4 4 4 3 3 3 3 3 3 3 3 4 4 4 4 4 ``` As challenge is not very difficult, it is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and shortest code wins. [Answer] # Excel (ms365), 542 bytes Using [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance), here is an iterative example where `W==10`, `H==1` and seeds are `[[1, 1], [1, 2]]` (note the appropriate row, column notation): **1st Seeds/Partition**: The 1st seeds are given in `R1:S2`. So we just need to create the 1st partition. In Excel this was doable using the following formula in `A1`: ``` =MAKEARRAY(V2,V1,LAMBDA(r,c,LET(x,BYROW(ABS(R1:S2-HSTACK(r,c)),LAMBDA(x,MAX(x))),MATCH(MIN(x),x,0)))) ``` [![enter image description here](https://i.stack.imgur.com/UCJlA.png)](https://i.stack.imgur.com/UCJlA.png) **2nd Seeds/Partition**: After this initial partition we need to iterate all possible group of digits 1-9 and find it's centroid ([Lloyd's algorithm](https://en.wikipedia.org/wiki/Lloyd%27s_algorithm)). In Excel to find the centroid and make it applicable for the next iteration we can use an average of each cell's respective row and column. In my case I choose to round down any figure to find the position of the next centroid: ``` =HSTACK(TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUND(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(A1#,r,c)=y,r,NA()))),2)),0))),2),TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUND(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(A1#,r,c)=y,c,NA()))),2)),0))),2)) ``` This would return: `[[1,1],[1,6]]` **Final Seeds/Partition:** For a 2nd partition, we can use the formula from the 1st partition but need a way to swap the hardcoded `R1:S2` out with the formentioned results. For this we need an iterative `LAMBDA()` function that we can feed results as we go. One option could be `REDUCE()`. Since OP stated that there are no more rows/column than a 100 we can iterate 99 times (Excel's performance will take a big hit here though): ``` =REDUCE(R1:S2,ROW(1:99),LAMBDA(a,b,LET(z,MAKEARRAY(V2,V1,LAMBDA(r,c,LET(x,BYROW(ABS(a-HSTACK(r,c)),LAMBDA(x,MAX(x))),MATCH(MIN(x),x,0)))),HSTACK(TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,r,NA()))),2)),0))),2),TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,c,NA()))),2)),0))),2))))) ``` This will give us the final seeds `[[1,2],[1,7]]` which in return can be used in the formula we created in the 1st partition: [![enter image description here](https://i.stack.imgur.com/n4aID.png)](https://i.stack.imgur.com/n4aID.png) Formula in `A1`: ``` =MAKEARRAY(V2,V1,LAMBDA(r,c,LET(x,BYROW(ABS(REDUCE(R1:S2,ROW(1:99),LAMBDA(a,b,LET(z,MAKEARRAY(V2,V1,LAMBDA(r,c,LET(x,BYROW(ABS(a-HSTACK(r,c)),LAMBDA(x,MAX(x))),MATCH(MIN(x),x,0)))),HSTACK(TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,r,NA()))),2)),0))),2),TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,c,NA()))),2)),0))),2)))))-HSTACK(r,c)),LAMBDA(x,MAX(x))),MATCH(MIN(x),x,0)))) ``` **Final [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram):** What is left to do is to change the cells that hold the last known centroid's positions into a zero. For this we need to nest an `IF()` to check this requirement. The final result looks like: [![enter image description here](https://i.stack.imgur.com/CXkY8.png)](https://i.stack.imgur.com/CXkY8.png) Formula in `A1`: ``` =MAKEARRAY(V2,V1,LAMBDA(r,c,LET(q,REDUCE(R1:S2,ROW(1:99),LAMBDA(a,b,LET(z,MAKEARRAY(V2,V1,LAMBDA(r,c,LET(x,BYROW(ABS(a-HSTACK(r,c)),LAMBDA(x,MAX(x))),MATCH(MIN(x),x,0)))),HSTACK(TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,r,NA()))),2)),0))),2),TOCOL(MAP(ROW(1:9),LAMBDA(y,ROUNDDOWN(AVERAGE(TOCOL(MAKEARRAY(V2,V1,LAMBDA(r,c,IF(INDEX(z,r,c)=y,c,NA()))),2)),0))),2))))),x,BYROW(ABS(q-HSTACK(r,c)),LAMBDA(x,MAX(x))),IF(ISNUMBER(MATCH(1,(TAKE(q,,1)=r)*(DROP(q,,1)=c),0)),0,MATCH(MIN(x),x,0))))) ``` --- **Other results:** [![enter image description here](https://i.stack.imgur.com/85YHw.png)](https://i.stack.imgur.com/85YHw.png) [![enter image description here](https://i.stack.imgur.com/Zxjgx.png)](https://i.stack.imgur.com/Zxjgx.png) [![enter image description here](https://i.stack.imgur.com/fymHU.png)](https://i.stack.imgur.com/fymHU.png) [![enter image description here](https://i.stack.imgur.com/qGE0t.png)](https://i.stack.imgur.com/qGE0t.png) [![enter image description here](https://i.stack.imgur.com/Qgk2s.png)](https://i.stack.imgur.com/Qgk2s.png) --- **Famous Quote:** *"As challenge is not very difficult..."*([Lesobrod](https://codegolf.stackexchange.com/users/114511/lesobrod), 2023). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes ``` W¬⁼ζυ«≔ζυ≔EθEEηEζ⌈↔Eξ⁻ρ⎇ςμκ⌕μ⌊με≔EζE⟦EεE№μλνEε⌕Aμλ⟧÷ΣΣμLΣμζ»Fζ§≔§ε§ι⁰⊟ι±¹E⊕ε⪫ι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZFLTsMwEIbFkp5ilJUtXKmhSBR1FfGQiqCqVHZRFmniNhaO3fpRShBrDsGmiyK4EpwGO25ZEMn5xzPzz2fL719FlatC5ny7_bBm3h38HL09VYxTQGNp0PXK5lyjhoDFGMNL5zjRmi1EyAz_tvf5Eq0IePGrCmHjZcNqW6NkpiW3hrbljcszYTVSBB6oErl6RmsCNYFHHD4CN0yUqG4b2wF1SNN_0CaQUv-jIb6UVhhv5a5feNO-6EcmnIcSzgiMhLlia1ZSNHWEaaAQuKNiYarDvsU2DvvamUsFqMEQ-IkZiZJu0EEd4RAyAj1vm8glYk7HdJG7u8fYjZko5o7njzQShaI1FYaWiLquW8mEt0YQOehwp2eF3r_KZxp11zzKvk_SuEcg7hNI01MCfXeL9IzAudcBgYHXC9cQZ1kWrL8) Link is to verbose version of code. Explanation: ``` W¬⁼ζυ« ``` Repeat until the process stabilises. ``` ≔ζυ ``` Save the previous seeds. ``` ≔EθEEηEζ⌈↔Eξ⁻ρ⎇ςμκ⌕μ⌊με ``` For each cell in the matrix, calculate the nearest 0-indexed seed according to the chessboard distance, using the earlier seed in the event of a tie. ``` ≔EζE⟦EεE№μλνEε⌕Aμλ⟧÷ΣΣμLΣμζ ``` Calculate the centroids of the regions using integer arithmetic (so the results are always truncated). ``` »Fζ§≔§ε§ι⁰⊟ι±¹ ``` Set the cells with seeds to `-1`. ``` E⊕ε⪫ι ``` Increment the cells to make them 1-indexed and output the final Voronoi diagram. 80 bytes to output the diagram at each step: ``` W¬⁼ζυ«≔ζυ≔EθEEηEζ⌈↔Eξ⁻ρ⎇ςμκ⌕μ⌊με≔EζE⟦EεE№μλνEε⌕Aμλ⟧÷ΣΣμLΣμζFυ§≔§ε§κ⁰§κ¹±¹⟦E⊕ε⪫κ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVHLSsNAFMWlfsUlqxmcQmMFK66CD6hoEXQXskiTaTN0MrHzqDXiT7h104Wiv6Rf49xMK2IgOfdxzj13Jq-fRZXrosnlev3u7LQ3_N55eaiE5EDGjSXnC5dLQ1oGjlIKT3u7iTFipkLl5De9zu_JggECvlUIW4SVqF1NkolppLO8a698XShniGZwx7XK9SNZMqgZzGl4GFwIVZK6I3YD6lDm_0zb4JTih4f4tHHKolR6vkLRpokjEylDi2YMRsqeiaUoObn1DrfBhcEVVzNbbfPOtkXbaaOBOArBPrEjVfIV2aI32IZzBn1U_cljn475LPc3EFMcdqOF37Lbe6QKzWuuLC8J97zLRijURBD5NT35-c1MCrP5QR9p1FvKKPvaT-O-HzxgkKYHDAb-QOkhgyPEIYMh4rEnxFmWBekP) Link is to verbose version of code. Note that if I added multidimensional indexing to Charcoal then both solutions would be 76 bytes. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 184 bytes ``` (s=#1;w=#2;h=#3;r=Range@Length@s;b=Array[0&,{h,w}];v=(Do[b[[i,j]]=First@Nearest[#->r,{i,j}],{i,h},{j,w}];⌊Mean@Position[b,#]⌋&/@r)&;s=FixedPoint[v@#&,s];Print@ReplacePart[b,s->0])& ``` [Try it online!](https://tio.run/##HYzBagIxGIRfZSEQFH5xt7YUCZEUSk@2LF5DDv9qNJGaLUlQS8gLtD6lL7LN9jB8MwwzJ4xGnzDaLQ57PkwCJw27cPLADCcL5vkG3UGLtXaHaERgHX/xHr9lTSEZuGTFznzy2stOSgtHpfib9SGKD41ehyjJbOUhlSarESZDOv6v7refd41OtH2w0fZOdkDU/fZL58JPKQvl56p3bW9dlGdBKATFWl@S2OivT9zqFn0sozBb1WpKh71MqYFqkaFKj1A9jXyGapmLaepRavgD "Wolfram Language (Mathematica) – Try It Online") I am sorry that this challenge caused such a misunderstanding. Perhaps the problem is my bad English. Here is a short version for Mathematica (and sure should be more golfed!). It uses `EuclideanDistance` (as it's default for `Nearest`) and output only final state. All this is acceptable for other answers. Unfortunately TIO does not understand pretty-print operators WM like `TableForm` and `MatrixForm`. But I know that for many languages TIO works well, so I believe that eg Vyxal ASCII-art version should be less than 100 bytes (-\_0) Maybe this full-named and commented version will be useful. ``` print[{board_, seeds_}] := TableForm[ ReplacePart[board, seeds -> 0], TableSpacing -> {0, 0.5} ]; lloyd[initSeeds_, w_, h_] := With[ {dist = ChessboardDistance, numSeeds = Length@initSeeds }, (*Initialize board with background 0 and seeds*) board = Normal@SparseArray[ Table[initSeeds[[i]] -> i, {i, numSeeds}], {h, w}]; (*Lambda where # stands for seeds, but board also updated*) voronoi = (Do[ (*Update board, tagging every position with it's closest seed index*) board[[i, j]] = First@Nearest[# -> Range@numSeeds, {i, j}] , {i, h}, {j, w}]; (*Return new seeds as centroids of every cells*) Table[Floor@Mean@Position[board, k], {k, numSeeds}]) &; (*Repeat voronoi until result no longer changed*) seeds = FixedPoint[voronoi@# &, initSeeds]; (*Output board and final seeds*) {board, seeds} ]; ``` ]
[Question] [ ## Bounty One of the convincing conjectures, by Loopy Walt is, ``` maxlib(n) = 0, if n = 1 2, if n = 2 6, if n = 3 (2n - 1)⌊n / 3⌋, if n % 3 = 0 (2n - 1)⌊n / 3⌋ + n, if n % 3 = 2 2n⌊n / 3⌋ + 1, otherwise ``` Loopy Walt's post below explains how this conjecture is derived, and contains a partial proof. AnttiP and I will award 250 point bounty each to anyone who proves or disproves this conjecture. I will award 50~500 point bounty for any other provable fast solution, depending on how fast it is. ### Introduction The problem is about the game of Go. I will explain the basics you need to understand the problem, but if you are already familiar with this game, the problem is basically the following sentence. *Compute the function \$\operatorname{maxlib}(n)\$ for a natural number \$n\$, whose output is the maximum number of liberties a group can have on an \$n\times n\$ Go board.* \$\operatorname{maxlib}(n)\$ has an OEIS sequence ([A320666](https://oeis.org/A320666)). The currently known values is only up to \$n=24\$. ``` n maxlib(n) 1 0 2 2 3 6 4 9 5 14 6 22 7 29 8 38 9 51 10 61 11 74 12 92 13 105 14 122 15 145 16 161 17 182 18 210 19 229 20 254 21 287 22 309 23 338 24 376 ``` Go is a board game played on an \$n\times n\$ square grid, with two players, black and white, placing a stone alternately on an empty intersection of the grid. In this challenge we will only consider the black stones (`X`). On this \$4\times4\$ board, black has \$3\$ groups. ``` X X . . X . X . X X . X . . X X ``` A *group* is a group of stones that are connected horizontally or vertically. Let's denote each group with different alphabets. ``` A A . . A . B . A A . C . . C C ``` Group `A` has \$5\$ liberties. Group `B` has \$4\$ liberties, and group `C` has \$3\$ liberties. *Liberty* is the number of empty spaces connected horizontally or vertically to a group. ``` . . . . X . . . . . . . X X . . . . . . . X X X . . . ``` There are three \$3\times3\$ boards each with a single black group. Counting the liberties, it is \$4\$, \$5\$, and \$6\$, respectively. In fact, on a \$3\times3\$ board with nothing else than \$1\$ black group, \$6\$ is the maximum number of liberties that group can have. ### Challenge Compute the function \$\operatorname{maxlib}(n)\$ for a natural number \$n\$, whose output is the maximum number of liberties a group can have on an \$n\times n\$ Go board. ### Example Output up to \$n=6\$ ``` X 1 -> 0 X . . . 2 -> 2 . . . X X X . . . 3 -> 6 . . X . . . X . X X X . . . . . 4 -> 9 . . . . . . X X X X . X . . . . X X X . . . . . . 5 -> 14 . X . . X . . X . . X . . X . . X . . X . . X . . X X X X . . . . . . . 6 -> 22 ``` You don't have to print the board positions. ### Scoring I will run your program for 30 minutes on my computer, *not exclusively* on a single core. The maximum \$n\$ you can reach within this time is your score, starting from \$n=1\$ incrementing by \$1\$. Your program must reach at least \$n=6\$, and I will not run your program if this seems unlikely. The maximum score you can get is 10000. The OS is Linux, and [here](https://pastebin.com/hz1rAKqM) is my CPU information. [Answer] # Rust, score ≈ 15 in 37 minutes This uses dynamic programming to run in \$O((1 + \sqrt5)^n n^{3/2})\$ time (much faster than a brute-force \$2^{n^2}n^{O(1)}\$ solution). The idea is that if we fill the grid row-by-row and column-by-column with stones or holes, trying each of these two decisions at each step, the only state we need to remember is * whether the last point in each column has a stone or a hole, * if it has a stone, which other stones it’s been connected to so far, * if it has a hole, whether it’s already been counted as a liberty, and * how many liberties have been counted so far; and we can use a hash table to collapse states that are identical up to the number of counted liberties. The number of distinct states we need to store grows as \$\frac{5(1 + \sqrt{5})^{n + 5/2}}{4\sqrt[4]{5}\sqrt{2\pi}n^{3/2}}\$. Build with `cargo build --release` and run with `cargo run --release`. **`Cargo.toml`** ``` [package] name = "liberty" version = "0.1.0" edition = "2021" [dependencies] mimalloc = { version = "0.1.28", default-features = false } [profile.release] codegen-units = 1 lto = true panic = "abort" ``` **`src/main.rs`** ``` use mimalloc::MiMalloc; use std::collections::HashMap; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; #[derive(Copy, Clone, Eq, Hash, PartialEq)] enum Point { Unused, Used, Stone(u32), } fn lib(n: usize) -> u32 { let mut states = HashMap::from([(vec![Point::Used; n], 0)]); let mut best = 0; for _i in 0..n { for j in 0..n { let mut states1 = HashMap::new(); let mut add = |state: Vec<Point>, count: u32| { states1 .entry(state) .and_modify(|c| *c = count.max(*c)) .or_insert(count); }; for (state, count) in states { if state[j] != Point::Stone(j as u32) { let mut state = state.clone(); let used = matches!(state[j], Point::Stone(_)) || (j != 0 && matches!(state[j - 1], Point::Stone(_))); state[j] = if used { Point::Used } else { Point::Unused }; add(state, count + used as u32); } else if let Some(k) = state[j + 1..] .iter() .position(|&point| point == Point::Stone(j as u32)) .map(|k| j + 1 + k) { let mut state = state.clone(); for point in &mut state[k..] { if *point == Point::Stone(j as u32) { *point = Point::Stone(k as u32); } } state[j] = Point::Used; add(state, count + 1); } else if !state[..j] .iter() .chain(&state[j + 1..]) .any(|state| matches!(state, Point::Stone(_))) { best = best.max(count); } let mut state = state; let used0 = state[j] == Point::Unused; let used1 = j != 0 && state[j - 1] == Point::Unused; if used1 { state[j - 1] = Point::Used; } if let Some(Point::Stone(k)) = j.checked_sub(1).map(|j1| state[j1]) { if let Point::Stone(l) = state[j] { if l < k { for point in &mut state[k as usize..j] { if *point == Point::Stone(k) { *point = Point::Stone(l); } } } else if l > k { for point in &mut state[j..] { if *point == Point::Stone(l) { *point = Point::Stone(k); } } } } else { state[j] = Point::Stone(k); } } else if let Point::Stone(_) = state[j] { } else { state[j] = Point::Stone(j as u32); } add(state, count + used0 as u32 + used1 as u32); } states = states1; } } for (state, count) in states { let mut it = state.into_iter(); if let Some(j) = it.find_map(|point| { if let Point::Stone(j) = point { Some(j) } else { None } }) { if it.all(|point| { if let Point::Stone(k) = point { j == k } else { true } }) { best = best.max(count); } } } best } fn main() { for n in 0.. { println!("{n} {}", lib(n)); } } ``` [Answer] # [Python 3](https://docs.python.org/3/), Using pnlwc (Probably Definitely not loopy Walt's conjecture) ``` def pnlwc(n): if n<4:return[0,0,2,6][n] if n%3==0:return n//3*(2*n-1) if n%3==2:return n//3*(2*n-1)+n return n//3*2*n+1 ``` [Try it online!](https://tio.run/##bc7LCsIwFIThvU9xNkLSRpqLugj2SUoXookekGkIEfHpY1ERBWf7f4tJ93Ke4Go9hkgJl9tBQPoFzeNI2K19DuWaMWillVXbccD4qUvX9/oNCF3nGmEbrIz8EfafaPE032UOralxysTEoLzHKQij7Eb6lBlFsHodZCnrAw "Python 3 – Try It Online") ## Conjectured optimal group The conjectured formula seems to hold for all test cases larger than 3. It is definitely a lower bound, see the corresponding groups below. n = 0 mod 3 ``` ............ XXXXXXXXXXXX .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. ``` n = 2 mod 3 ``` ........... XXXXXXXXXXX .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 ``` n = 1 mod 3 ``` .......... XXXXXXXXXX .X..X..X.. .X..X..X.. .X..X..XXX .X..X..X.. .X..X..X.. .X..X..XXX .X..X..X.. .X..X..XX. ``` ### Partial proof: *The n=0 mod 3 case is actually comparatively easy to prove:* Start with a few easy observations: 1. We can assume that all squares are either stone or lib. Proof: (easy) exercise. Hint: trade squares that are neither against adjacent libs. 2. As a consequence, we can either maximise libs or minimise stones. 3. Another consequence is that each of the four corners must neighbour at least one stone. It follows that at least one pair of opposite edges (E and W, say) must be connected by a stone path. 4. (Arithmetic 101:) (a) the stone-to-lib ratio is at least 1:2. Indeed, the E-W path if it is straight has exactly this ratio. If it meanders, (b) each turn knocks off one lib. (c) 3-way (4-way) branch points knock off 3 (6) libs. (d) Ends gain 1 lib if in the open and are neutral at a wall. In either case they incur a net loss because they necessitate a branch point. Finally, (e) a straight hugging a wall or (f) running parallel to another straight less than 2 squares away loses 1 lib per length unit (2 if parallel and directly touching). Note: the reader is encouraged to verify themselves that the group can indeed be thought of as assembled from connected horizontal and vertical straights. Inspecting the claimed optimal pattern we see that it has no turns and exactly n/3 3-way branch points. It has n/3 x (n+1) stones and n/3 x (2n-1) libs which is as predicted by our arithmetic 101 exactly n short of doubling the stones. We will now show that this is as good as it gets: The group must contain either at least n/3 horizontal or at least n/3 vertical straights. If it doesn't there is a y coordinate y0 where there is no stone or lib caused by a horizontal straight and similar for x coordinates and vertical straights. But this would mean square y0,x0 is neither stone nor lib which we have ruled out. Let's say WLOG that it is n/3 verticals. Generally, connecting k horz displaced vert straights will cost at the very least 2xk-2 libs as all but 2 vert straights must connect to at least two others each. Indeed, the cheapest way would be through two horz straights each connected via a turn to either end of the vert. That does, however, not work for the case at hand because the horizontal ends of this construction do not line up flush (cf. fig) and there is not enough slack in the system to create compensating elements. For example, just pushing the bridging horz all the way to the wall costs too much (101.e). ``` . . . . . . . . . . O O O O . . O O X X X X O O O O X O O X O O O O X O O X O O O O X O O X O O X X X O O X X X O O O . . O O O . . . . . . . . ``` The next cheapest way of joining is branching off from a single horz which costs exactly n libs and is in fact precisely what the reference pattern does. Note 1: This argument does not work for n=3 which may be viewed as a reason why the formula needs a special value there. Note 2: The proof is relatively straight forward because for n=0 mod 3 the very small number of lost libs puts strong constraints on eligible patterns. The n=2 mod 3 and are considerably more forgiving and therefore tricky. ]
[Question] [ A [complete Boolean](https://en.wikipedia.org/wiki/Functional_completeness) function is a function such that, an amount of them can be used to express any Boolean function. For example, NAND \$\left[\begin{matrix}\text{input1}&0&0&1&1\\\text{input2}&0&1&0&1\\\text{output}&1&1&1&0\end{matrix}\right]\$ is complete. Inputs may be reused any number of times, and the functions can be composed arbitrarily. Some functions, like IMPLY \$\left[\begin{matrix}\text{input1}&0&0&1&1\\\text{input2}&0&1&0&1\\\text{output}&1&1&0&1\end{matrix}\right]\$, are not individually complete. We can prove this simply by noting that there is no way to output 0 if all inputs are 1. However, if we are allowed to use the constant functions (always 0 and always 1, aka `false` and `true`), then the set of functions becomes complete. Given a Boolean Function with input, check whether it's complete, not complete, or only complete if constants are allowed. Flexible IO, shortest code wins. ## Test cases (2-input) ``` a 0 0 1 1 b 0 1 0 1 #1 1 1 1 0 Complete #2 0 1 1 0 Not complete #3 0 0 1 0 Need Constant ``` (3-input) ``` a 0 0 0 0 1 1 1 1 b 0 0 1 1 0 0 1 1 c 0 1 0 1 0 1 0 1 #1 0 0 0 0 0 0 0 1 Not complete #2 1 0 0 0 0 0 0 0 Complete #3 1 1 1 1 0 0 0 0 Not complete #4 1 1 0 1 0 0 1 0 Complete #5 0 0 1 1 0 1 0 1 Need constant ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~152~~ ~~150~~ ~~147~~ 136 bytes ``` def c(a):E=enumerate;x,y,z=map(min,*[[a[i|c]>=v,c&c-1>=w^a[0]^a[i^c]^v,v^a[~i]>=a[0]-a[-1]]for i,v in E(a)for c,w in E(a)]);print-x|-y|z ``` [Try it online!](https://tio.run/##jVJda4MwFH33V4Q@DB2xmD22WCidg0HXFvRN0uLSdAvUKCbaD8r@uouxH7ab60II9x7OOTc3uelOfib8qSyXdAWIGVk9z6U8j2kWSdrfwh3cu3GUmjHj8DEMo5AdCB64BSQPxEYDdzOPQgerg80JnhewUOEXU4wKtqPQRhivkgwwWADGgacqVCmBm1OKrX5GZZ5xe3uwd4d9SdaREGCUxOmaSsqpED0DqDWavs3GXuABFzgamEyDRQO0UY163rOv8IkfDCeBwpFhGJIKKVQcaooZIgjq7WB4Vap7MrTgkeq0Upv1m3SnhX51sRvBzUb/qoV@k97v6Nw8@kvWVhGdG2zttP1RmmJ094GwYVTDkuQyzSUEdJtSIumymhz9ofVcfCRS/Swxa5qlMbbSMBNnUc2tVpoxLkFnNvT9DqxoF2fNoWtBf7Bfhq9jkHAlON2m0/WOKhVfLHTynsvKuLYvvwE "Python 2 – Try It Online") (TIO link outputs through function `return` instead of stdout) *-15 bytes thanks to @ovs* Takes input as a list of boolean outputs in the same order as the question, so (for example) a two-argument function is represented by the four-element list `[f(0,0),f(1,0),f(0,1),f(1,1)]`. In general, for an input list `a` of length `2^n`, we must have `a[i] = f(i&1, i&2, ..., i&(1<<n-1))`. Outputs by printing to STDOUT according to the following table: ``` COMPLETE = -1 NOT_COMPLETE = 1 NEEDS_CONSTANT = -2 ``` ## Theory This uses Post's [Characterization of Functional Completeness](https://en.wikipedia.org/wiki/Functional_completeness#Characterization_of_functional_completeness), which describes five terms that can describe a boolean function: monotonic, affine, self-dual, truth-preserving, and falsity-preserving. For a different explanation of what they mean, read the comments in class `Char` in the ungolfed code below. These five terms completely characterize the answer, as proven by Emil Post. If a term describes every member of a set of boolean expressions, then that set of boolean functions is not functionally complete. For example, if every function is truth-preserving, then plugging in all inputs as 1 (true) will always return 1 (true), no matter how the functions are arranged. This means that the functions cannot be arranged to take all inputs as 1 and return 0, so that set of functions is not functionally complete. Similar arguments work for the other four terms as well. The converse (if none of the five terms describe every member of a set of functions, then that set of functions is functionally complete) is harder to prove in the general case, so I'm relying on Emil Post's proof. ## Application To answer the challenge, we calculate which of the terms describe the given function. * If none of the terms describe the given function, then it is functionally complete. Return `COMPLETE`. * Otherwise, if the given function is either monotonic or affine, then adding the two constant functions (`true` and `false`) would cause the new set of functions to still be monotonic or affine (because true and false are both monotonic and affine). Return `NOT_COMPLETE` * Otherwise, return `NEEDS_CONSTANT`. Neither of the two constant functions are self-dual, so adding either one would cause the set of functions to not all be self-dual. Similarly, the `true` constant is not falsity-preserving, and the `false` constant is not truth-preserving, so adding both handles the case where the given function is truth-preserving, falsity-preserving, or both. ## Ungolfed code ``` from enum import Enum # BEGIN GOLF class Completeness(Enum): COMPLETE = "COMPLETE" NOT_COMPLETE = "NOT_COMPLETE" NEEDS_CONSTANT = "NEEDS_CONSTANT" class Char(Enum): # changing any 0 to a 1 does not cause the result to change from 1 to 0 MONOTONIC = "MONOTONIC" # every input variable either always or never affects the truth value # i.e. equivalent to the logical XOR or XNOR of the inputs AFFINE = "AFFINE" # flipping all the 0s to 1s and 1s to 0s flips the result between a 0 and 1 SELF_DUAL = "SELF_DUAL" # if all inputs are 1, then the output is 1 TRUTH_PRESERVING = "TRUTH_PRESERVING" # if all inputs are 0, then the output is 0 FALSITY_PRESERVING = "FALSITY_PRESERVING" def is_power_of_two(n): return n & n - 1 == 0 def characterize(output): chars = set() u = len(output) mask = u - 1 powers_of_two = list(filter(is_power_of_two, range(u))) if all(output[i | c] >= output[i] for i in range(u) for c in powers_of_two): chars.add(Char.MONOTONIC) if all( all(output[i ^ c] != output[i] for i in range(u)) or all(output[i ^ c] == output[i] for i in range(u)) for c in powers_of_two ): chars.add(Char.AFFINE) if all(output[i] != output[mask & (~i)] for i in range(u)): chars.add(Char.SELF_DUAL) if output[-1] == 1: chars.add(Char.TRUTH_PRESERVING) if output[0] == 0: chars.add(Char.FALSITY_PRESERVING) return chars def completeness(output): chars = characterize(output) if len(chars) == 0: return Completeness.COMPLETE elif Char.MONOTONIC in chars or Char.AFFINE in chars: return Completeness.NOT_COMPLETE else: return Completeness.NEEDS_CONSTANT # END GOLF tests = [ # (none) ([1, 1, 1, 0], Completeness.COMPLETE), # affine, falsity-preserving ([0, 1, 1, 0], Completeness.NOT_COMPLETE), # falsity-preserving ([0, 0, 1, 0], Completeness.NEEDS_CONSTANT), # monotonic, truth-preserving ([0, 0, 0, 0, 0, 0, 0, 1], Completeness.NOT_COMPLETE), # (none) ([1, 0, 0, 0, 0, 0, 0, 0], Completeness.COMPLETE), # self-dual, affine ([1, 1, 1, 1, 0, 0, 0, 0], Completeness.NOT_COMPLETE), # (none) ([1, 1, 0, 1, 0, 0, 1, 0], Completeness.COMPLETE), # falsity-preserving, truth-preserving ([0, 0, 1, 1, 0, 1, 0, 1], Completeness.NEEDS_CONSTANT), ] for output, expected in tests: got = completeness(output) if got == expected: print("PASS") else: print(f"FAIL on {output}. Expected {expected} but got {got}") print(f" Chars: {', '.join(map(str,list(characterize(output))))}") ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes ``` ≔E↨⊖Lθ²X²κη✳∧⊙⮌θ⁼§θκι›§θ⁰§θ±¹›⊙η⊙θ‹§θ|ιμλ⬤ηΦ²⬤θ∨&ιξ⁼λ⁼§θ|ιξν ``` [Try it online!](https://tio.run/##bY/bCsIwDIbvfYpdpjBh89ariQcET/gGZQtbsHaurTqfviYqOMGUUJr@35@kbLQrW21iLLyn2sJWX2CmPcIcS4dntAEr2KCtQwOdUmky4Ty0d3QwSZOTVBo1HR0c2QBzclgGai0UtuJ8wBFv6NitY92iu2rjoQhrW2EPneBpQmKxcqgDWw7@Mi4PnjusWQG5khgA3KNhIV8s2qD/8Z9RuJPHvQNKk7Nw5kUXxgi1JBPee0iB9Sz8IDI/M/13bPNvgZ8GvVhb9YlpjFmW5xmfOL6ZJw "Charcoal – Try It Online") Link is to verbose version of code. Can take input as a binary string or an array and outputs `/` for complete, `-` if constants are needed, nothing if incomplete. Explanation: Port of @fireflame241's solution. ``` ≔E↨⊖Lθ²X²κη ``` Get the powers of 2 up to the length of the string. ``` ✳∧⊙⮌θ⁼§θκι›§θ⁰§θ±¹ ``` If any function value matches that of the reverse of the string (meaning that the function is not self-dual), and the first value is greater than the last value (meaning that the function is neither true- or false-preserving), then prepare to print a `/` rather than a `-`. ``` ›⊙η⊙θ‹§θ|ιμλ⬤ηΦ²⬤θ∨&ιξ⁼λ⁼§θ|ιξν ``` Don't print anything if the function is monotonic or affine. The function is not monotonic if there exists a set of inputs such that changing one of the inputs to `1` changes the value from `1` to `0`. (Inputs of `1` are also checked, but changing them to `1` obviously has no effect on the value.) The function is affine if for all inputs the values where that input is `1` are either equal to or the exact complement of the values where that input is `0` all at the same time. This was the part that was hardest to golf in Charcoal as it doesn't have the bitwise XOR function, nor does it have a simple way of comparing all the values in an array with each other. ]
[Question] [ # Challenge The challenge is to implement the [bottom](https://github.com/bottom-software-foundation/spec) encoding (only encoding, not decoding). There is a wide variety of existing implementations in the [bottom-software-foundation org](https://github.com/bottom-software-foundation). Bottom is a text encoding where each character is separated into multiple emoji. | Unicode escape(s) | Character | Value | | --- | --- | --- | | `U+1FAC2` | 🫂 | 200 | | `U+1F496` | 💖 | 50 | | `U+2728` | ✨ | 10 | | `U+1F97A` | 🥺 | 5 | | `U+002C` | , | 1 | | `U+2764`, `U+FE0F` | ❤️ | 0 | | Unicode escape(s) | Character | Purpose | | --- | --- | --- | | `U+1F449`, `U+1F448` | 👉👈 | Byte separator | ## Notes on encoding * The output stream will be a sequence of groups of value characters (see table above) with each group separated by the byte separator character, i.e. ``` 💖✨✨✨👉👈💖💖🥺,,,👉👈💖💖,👉👈💖✨✨✨✨🥺,,👉👈💖💖✨🥺👉👈💖💖,👉👈💖✨,,,👉👈 ``` * The total numerical value of each group must equal the decimal value of the corresponding input byte. + For example, the numerical value of `💖💖,,,,`, as according to the character table above, is `50 + 50 + 1 + 1 + 1 + 1`, or 104. This sequence would thus represent `U+0068` or `h`, which has a decimal value of `104`. + Note the ordering of characters within groups. Groups of value characters **must** be in descending order. While character order (within groups) technically does not affect the output in any way, arbitrary ordering can encroach significantly on decoding speed and is considered both illegal and bad form. * Byte separators that do not follow a group of value characters are illegal, i.e `💖💖,,,,👉👈👉👈` or `👉👈💖💖,,,,👉👈`. As such, `👉👈` alone is illegal. * Groups of value characters must be followed by a byte separator. `💖💖,,,,` alone is illegal, but `💖💖,,,,👉👈` is valid. * The null value must not be followed by a byte separator. `💖💖,,,,👉👈❤️💖💖,,,,👉👈` and `💖💖,,,,👉👈❤️` alone are valid, but `💖💖,,,,👉👈❤️👉👈` is illegal. Some pseudocode to illustrate how each character is converted: ``` for b in input_stream: # Get `b`'s UTF-8 value let v = b as number let o = new string if v == 0: o.append("❤️") else: while true: if v >= 200: o.append("🫂") v = v - 200 else if v >= 50: o.append("💖") v = v - 50 else if v >= 10: o.append("✨") v = v - 10 else if v >= 5: o.append("🥺") v = v - 5 else if v >= 1: o.append(",") v = v - 1 else: break o.append("👉👈") return o ``` # Rules 1. The [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. 2. The input must be a string, not a list of bytes. 3. An empty string should return an empty string. 4. It should return the same result as [bottom-web](https://bottom-software-foundation.github.io/bottom-web/) for any input with no null bytes (UTF-8 validation is not required). Some test cases: * `test` -> `💖💖✨🥺,👉👈💖💖,👉👈💖💖✨🥺👉👈💖💖✨🥺,👉👈` * `Hello World!` -> `💖✨✨,,👉👈💖💖,👉👈💖💖🥺,,,👉👈💖💖🥺,,,👉👈💖💖✨,👉👈✨✨✨,,👉👈💖✨✨✨🥺,,👉👈💖💖✨,👉👈💖💖✨,,,,👉👈💖💖🥺,,,👉👈💖💖👉👈✨✨✨,,,👉👈` * `🥺` -> `🫂✨✨✨✨👉👈💖💖💖🥺,,,,👉👈💖💖💖✨🥺👉👈💖💖💖✨✨✨🥺,👉👈` * (2 spaces) -> `✨✨✨,,👉👈✨✨✨,,👉👈` * `𐀊` -> `🫂✨✨✨✨👉👈💖💖✨✨✨✨,,,,👉👈💖💖✨✨🥺,,,👉👈💖💖✨✨✨🥺,,,👉👈` * `⍉⃠` -> `🫂✨✨🥺,👉👈💖💖✨✨✨✨,👉👈💖💖✨✨✨🥺,,👉👈🫂✨✨🥺,👉👈💖💖✨✨✨,👉👈💖💖💖✨👉👈` * `X⃩` -> `💖✨✨✨🥺,,,👉👈🫂✨✨🥺,👉👈💖💖✨✨✨,👉👈💖💖💖✨🥺,,,,👉👈` * `❤️` -> `🫂✨✨🥺,👉👈💖💖💖🥺,,👉👈💖💖💖✨,,,,👉👈🫂✨✨✨🥺,,,,👉👈💖💖💖✨✨✨,,,,👉👈💖💖✨✨✨✨,,,👉👈` * `.\0.` (null byte surrounded by full stops) -> `✨✨✨✨🥺,👉👈❤️✨✨✨✨🥺,👉👈` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes win! [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 133 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {↑,/{⍵=0:'❤️'⋄'👉👈',⍨⍬{⍵≥200:(⍺,'🫂')∇⍵-200⋄⍵≥50:(⍺,'💖')∇⍵-50⋄⍵≥10:(⍺,'✨')∇⍵-10⋄⍵≥5:(⍺,'🥺')∇⍵-5⋄⍵≥1:(⍺,',')∇⍵-1⋄⍺}⍵}¨'UTF-8'⎕ucs⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UNlFHv/pR71ZbAyv1R3OXvN/Rr/6ou0X9w/yJnUDcoa7zqHfFo941ICWPOpcaGRhYaTzq3aUDVLC6SV3zUUc7UEIXKAzUBFFiilAxaRpchSlCgSFMwaM5K@DyhkgGwPUv3YXQj9AOldZB6AXL7aoFsmsPrVAPDXHTtVB/1De1NLkYJAQA&f=S1N/1Nv5qHmBOgA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f) -5 thanks to ovs. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~101~~ ~~100~~ ~~90~~ 86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ’inȦt("ÿ",î³aries: 1)’.E#εþD_i•yÑáÜ•2äçJë•$Hô}•Ƶ&вvy‰`}1D)•}Ѫ—ĆœŒÜ{¹’θǝ₂?••1þÀ•вç×]S ``` Output as a list of characters. -10 bytes thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f//UcPMzLzDHYeWlWgoHd6vpHN43aHNiUWZqcVWCoaaQEk9V@VzWw/vc4nPfNSwqPLwxMMLD88BsowOLzm83OvwaiBTxePwllogfWyr2oVNZZWPGjYk1Bq6APUuqj088dCqRw1TjrQdnXx00uE51Yd2Ak08t@P43EdNTfZABUBkeHjf4QYgfWHT4eWHp8cG//9fklpcEmMAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw0zM/MOdxxaVqKhdHi/ks7hdYc2JxZlphZbKRhqAiX1XJXPbT28zyU@81HDosrDEw8vPDwHyDI6vOTwcq/Dq4FMFY/DW2qB9LGtahc2lVU@atiQUGvoAtS7qPbwxEOrHjVMOdJ2dPLRSYfnVB/aCTTx3I7jcx81NdkDFQCR4eF9hxuA9IVNh5cfnl5bG/zfS@d/tFJJanGJko6SR2pOTr5CeH5RTgqQ92H@0l1ASkEBxJ7Q0AWkHvV2PmpeAGREPGpeCeLPXfJ@Rz@QoRdjoKcUCwA). **Explanation:** ``` ’inȦt("ÿ",î³aries: 1)’ # Push dictionary string "inspect("ÿ",binaries: 1)", # where `ÿ` is automatically replaced with the (implicit) input .E # Execute it as Elixir code # # Split the result in spaces ε # Map over each string-part: þ # Only leave the digits of the string D_i # If it's 0 (thus a null-byte): •yÑáÜ• # Push compressed integer 1008465039 2ä # Split it into 2 parts: [10084,65039] ç # Convert each to a character with this codepoint: ["❤","️"] J # Join the inner pair together: "❤️" ë # Else: •$Hô}• # Push compressed integer 1626142265 Ƶ& # Push compressed integer 201 в # Convert 1626142265 to base-201 as list: [200,50,10,5] v # Loop over each integer `y`: y‰ # Take divmod-`y` on the top integer # (which is the codepoint in the first iteration) ` # Pop and push the pair separated to the stack: n//y and n%y }1D # After the loop: push two 1s ) # And wrap everything into a list •}Ѫ—ĆœŒÜ{¹’θǝ₂?• # Push compressed integer 618452457360154459249099105698966985 •1þÀ• # Push compressed integer 129731 в # Convert the larger integer to base-129731 as list: # [129730,128150,10024,129402,44] ç # Convert each to a character: # ["🫂","💖","✨","🥺",",","👉","👈"] × # Repeat each character the divmod-list amount of times ] # Close the if-else statement and map S # Convert the list of lists to a flattened list of characters # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?*; *How to compress large integers?*; and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’inȦt("ÿ",î³aries: 1)’` is `"inspect("ÿ",binaries: 1)"`; `•yÑáÜ•` is `1008465039`; `•$Hô}•` is `1626142265`; `Ƶ&` is `201`; `•$Hô}•Ƶ&в` is `[200,50,10,5]`; `•}Ѫ—ĆœŒÜ{¹’θǝ₂?•` is `618452457360154459249099105698966985`; `•1þÀ•` is `129731`; and `•}Ѫ—ĆœŒÜ{¹’θǝ₂?••1þÀ•в` is `[129730,128150,10024,129402,44,128073,128072]`. [Answer] # [Python 3](https://docs.python.org/3/), ~~134~~ 130 bytes -4 bytes thanks to [bb94](https://codegolf.stackexchange.com/users/14109/bb94)! ``` for v in open(0,'rb').read():print(v//200*'🫂'+v//50%4*'💖'+v//10%5*'✨'+v//5%2*'🥺'+v%5*',',end=0**v*'❤️'or'👉👈') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SKFMITNPIb8gNU/DQEe9KEldU68oNTFFQ9OqoCgzr0SjTF/fyMBAS/3D/NVN6tpAnqmBqgmIO2kamGtooGqqpf5ozgqIpKoRSG7pLiAPJK6jrpOal2JroKVVBlQ0d8n7Hf3q@UVAFRM7gbhDXfP//0e9nY@aFzAAAA "Python 3 – Try It Online") Test case includes a trailing null byte. `open(0,'rb').read()` is the exact same length as `bytes(input(),'u8')`, but reads the entire input instead of one line. [Answer] ## JavaScript (newer browsers), ~~166~~ 164 bytes ``` f= s=>[...new TextEncoder().encode(s)].map(c =>(`🫂`[r=`repeat`](c/200)+`💖`[r](c/50%4)+`✨`[r](c/10%5)+`🥺`[r](c/5%2)+`,`[r](c%5)||`❤️`)+`👉👈`).join`` ``` ``` <input oninput=o.textContent=f(this.value)><div id=o> ``` (Only the second line qualifies as the code; the rest is just part of the Stack Snippet.) Can I Use says that Firefox supported TextEncoder before arrow functions, but I didn't bother to check other browser support. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 141 bytes ``` Table@@@({Characters@"🫂💖✨🥺,",#~NumberDecompose~{200,50,10,5,1}})<>If[#>0,"👉👈","❤️"]&/@Normal@StringToByteArray@#<>""& ``` [Try it online!](https://tio.run/##ZU/LSsNAFN3nK@KNhFaGNBXc1BrG6kI3rdCCQuxiEic2kEeZTJAQEqRdaAWpunCl1IWC4g@In5MfaP4gJnUjuLj3PLgc7nEJH1GXcNskhbVTDIjhUIxxLd4bEUZMTlmAIV98TvLFw2P29J4v3r4RICnthq5B2T41fXfsBzSNN1UVbamoWW7UTJLl/Kre1g4tXdJUVCbcz8q5BgTZ8@vyaw5DuYG7PnOJg/uc2d75wO9EnO4yRiIstTUAuehZFu7YHmHRMbM5bbUMy@VC7Y@lr/dCPg45koYy3vgX1MAxaJpY/otAAGRhKdk@Km@4PqzLad8kXhoLwGnAAQlwQB3HFy985pytVbrqWqEortTd5U2F2e0sm75U7CSbfqyc30YlU04VVVVASIof "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 133 bytes ``` s=>[...Buffer(s)].map(n=>n?[200,50,10,5,1].map((v,i)=>[..."🫂💖✨🥺,"][i].repeat(n/v,n%=v)).join``+"👉👈":"❤️").join`` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i5aT0/PqTQtLbVIo1gzVi83sUAjz9Yuzz7ayMBAx9RAxxBI6hhCJDTKdDI1IVqUPsxf3fRh/qRpj@as@DB/6S4dpdjozFi9otSC1MQSjTz9Mp08VdsyTU29rPzMvIQEbaD6iZ1A3KFkpfRo7pL3O/qVYHL/k/PzivNzUvVy8tM10jSUSlKLS5Q0NbnQhD1Sc3LyFcLzi3JSFLFIgxyBRVhBAZvaCQ1dWIQf9XY@al6ARSLiUfNKbOqh/sCQ0Isx0AMK/wcA "JavaScript (Node.js) – Try It Online") [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~110~~ 112 bytes ``` {[~] map ->\a {[~] "❤️🫂💖✨🥺,👉👈".comb Zx(!a,a/200,a/50%4,a/10%5,a/5%2,a%5,?a,?a)},@(.encode)} ``` *+2 bytes to properly implement null byte encoding* [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7vzq6LlYhN7FAQdcuJlEBzFN6NHfJ@x39H@avbvowf9K0R3NWfJi/dJfOh/kTO4G4Q0kvOT83SSGqQkMxUSdR38jAAEiaGqiaAClDA1VTEE/VSCcRyLJPBCLNWh0HDb3UvOT8lFTN2v/FiZUKaQpKJanFJUrWXFCeR2pOTr5CeH5RTooiQhRkLRJvQkMXgveot/NR8wIEP@JR80okWbAPEHy9GAM9Jev/AA "Perl 6 – Try It Online") [Answer] # [Lua (LuaJIT)](https://luajit.org/), ~~184~~ ~~172~~ 158 bytes ``` r=s.rep;s:gsub('.',function(v)v=v:byte()io.write(r('🫂',v/200),r('💖',v/50%4),r('✨',v/10%5),r('🥺',v/5%2),r(',',v%5),v~=0 and'👉👈'or'❤️')end) ``` [Try it online!](https://tio.run/##yylN1M0pTczKLPmfZptWmpdckpmfp1Gs@b/ItlivKLXAutgqvbg0SUNdT10HLl2mWWZbZpVUWZKqoZmZr1delAlkFWmof5i/ukldp0zfyMBAUwfMnzQNxDc1UDUBCzyaswLENzRQNYUqWLoLrEDVCMzXAXJAUmV1tgYKiXkpQAUTO4G4Qz2/SP3R3CXvd/Sra6bmpWj@BxJcBUWZeSVAl8UY6KlrcqWB3KinV1wCFE3XS85ILNIw0NQDCgHloCpj8kpSi0sgaqEsuIxHak5OvkJ4flFOiiJEBZIIskKwm8EKIKz//wE "Lua (LuaJIT) – Try It Online") ]
[Question] [ ## Challenge We once had [a challenge to count domino tilings of m by n grid](https://codegolf.stackexchange.com/q/55240/78410), and we all know that, for any fixed number of rows, the number of domino tilings by columns forms a linear recurrence. Then why not have a challenge to compute **the linear recurrence**?! Let's define \$D\_m(n)\$ as the number of domino tilings on a grid of \$m\$ rows and \$n\$ columns. Then the task is: given a single integer \$m \ge 1\$ as input, **output the linear recurrence relation for** \$D\_m(n)\$. If the relation has order \$k\$ (that is, \$D\_m(n+k)\$ depends on \$k\$ previous terms), you need to output the coefficients \$a\_i\$ of the recurrence relation $$ D\_m(n+k)=a\_{k-1}D\_m(n+k-1) + a\_{k-2}D\_m(n+k-2) + \cdots + a\_0 D\_m(n) $$ in the order of \$a\_0\$ to \$a\_{k-1}\$ or the reverse. There are infinitely many correct such relations; you don't need to minimize the order of the relation. **But,** to ensure that the result is at least minimally useful, **the order \$k\$ cannot exceed \$2^m\$ for any input value of \$m\$.** (Side note: An actual sequence is defined only if the initial \$k\$ terms are given along with the recurrence equation. That part is omitted for simplicity of output, and to give incentive to approaches not using the brute-forced terms.) Note that, for odd \$m\$, every odd-column term will be zero, so you will get a recurrence different from the OEIS entries which strip away zeroes (e.g. [3 rows](http://oeis.org/A001835), [5 rows](http://oeis.org/A003775), [7 rows](http://oeis.org/A028469)). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Examples Here are the representations from the OEIS, adjusted for odd \$m\$. Initial terms start at \$D\_m(0)\$, and the coefficients are presented from \$a\_{k-1}\$ to \$a\_0\$. Again, your program only needs to output the coefficients. To empirically check the correctness of your output of length \$k\$, plug in the \$k\$ initial terms from the respective OEIS entry, and see if the next \$k\$ terms agree. ``` m = 1 Initial terms [1, 0] # D(0) = 1, D(1) = 0 Coefficients [0, 1] # D(n+2) = D(n) m = 2 Initial terms [1, 1] Coefficients [1, 1] m = 3 Initial terms [1, 0, 3, 0] Coefficients [0, 4, 0, -1] # D(n+4) = 4D(n+2) - D(n) m = 4 Initial terms [1, 1, 5, 11] Coefficients [1, 5, 1, -1] m = 5 Initial terms [1, 0, 8, 0, 95, 0, 1183, 0] Coefficients [0, 15, 0, -32, 0, 15, 0, -1] m = 6 Initial terms [1, 1, 13, 41, 281, 1183, 6728, 31529] Coefficients [1, 20, 10, -38, -10, 20, -1, -1] ``` ## Possible approaches There is at least one way to find the recurrence without brute forcing the tilings, outlined below: 1. Compute the transition matrix \$A\$ of \$2^m\$ states, so that the target sequence is in the form of \$D\_m(n) = u^T A^n v\$ for some column vectors \$u,v\$. 2. Find the [characteristic polynomial](https://en.wikipedia.org/wiki/Characteristic_polynomial) or [minimal polynomial](https://en.wikipedia.org/wiki/Minimal_polynomial_(linear_algebra)) of \$A\$ as $$x^k - a\_{k-1}x^{k-1} - a\_{k-2}x^{k-2} - \cdots - a\_0 $$ 3. Then the corresponding recurrence relation is $$s\_{n+k} = a\_{k-1}s\_{n+k-1} + a\_{k-2}s\_{n+k-2} + \cdots + a\_0s\_n$$ An example algorithm of computing the minimal polynomial of a matrix can be found [on this pdf](http://bulletin.pan.pl/(56-4)391.pdf). (Of course, you can just brute force the domino tilings for small \$n\$ and plug into a recurrence finder.) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 72 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` {⍵=1:⍳2⋄(2*⌈⍵÷2)(⌷⌹⍉⍤↑)⍉L↑⍉↑,¨+.×\(L←2*⍵)⍴⊂∘.((0∊+)⍱1∊2|×≢¨⍤⊆⊣)⍨⍸1⍴⍨⍵⍴2} ``` [Try it online!](https://tio.run/##JU89awJBEO39FVuuHxFv1RSBVDYKQiBa2hzI2Qi5NiQ2UeTc3B6xOLTW5gpBxK8k5d0/eX/kfIswO@/xZubNrOuPH4bv7vhtlCOKfR/zH1Ug67yQ1QrZhfAB888Q93dmWJjk1M/PzhPMUeF7JlUJYUApu6qiRHhF@AezsA7LIkmXSGCupEm5mq0Gsmu3lTjC@gn6C8G6KmUNgS5TOTgk6jNbYbFJE/roOfSWhQTm17ETlvGck5rkHq1gIugpzI5Suq/bfVHce20x99udHu@NYrZ5d7BfSBNHKFEXDdEUjzc "APL (Dyalog Unicode) – Try It Online") (uses a polyfill for ⍤ since TIO is not updated to 18.0 yet) Requires `⎕pp←2` (implicit rounding of output) and `⎕IO←0` (0-indexing). We compute a transition matrix, then use the approach listed in [S. Białas and M.Białas](http://bulletin.pan.pl/(56-4)391.pdf) to find the minimum polynomial and hence the recurrence relation. ### Defining the Transition Matrix Each possible binary fill of a column of \$m\$ cells is one state, so there are \$2^m\$ states. For `m=3`, one example state (`1 0 0`) is ``` █ ▒ ▒ ``` The first cell is filled (it is the right side of a horizontal domino sticking out from the previous column), but the second and third cells are empty. This could occur e.g. as the second column in the following tiling (`n=4`, `3×4` grid): ``` ━━┃┃ ┃┃┃┃ ┃┃━━ ``` When considering state transitions, we have to be careful to avoid double counting. My approach is to require full horizontal dominos to be placed whenever possible, then vertical dominos can optionally be placed in the next state's column. For example, if the current state is `1 0 0`: ``` █ ▒ ▒ ``` then we force horizontal dominos on the bottom two rows ``` █▒ ━━ ━━ ``` so the next state would have to be `0 1 1`: ``` ▒ █ █ ``` This rule guarantees the current column to be filled in completely. In addition, it avoids double-counting transitions because it never places vertical dominos in the current column. Vertical dominos go in the next column. There is no space for vertical dominos in the past example. As an example where vertical dominos can be placed, take the current state to be `1 1 1`: ``` █▒ █▒ █▒ ``` One possibility would be to place no vertical dominos at all, so `1 1 1 → 0 0 0` is a valid state transition. In addition, a vertical domino can be placed in either of two positions: ``` █┃ █▒ █┃ or █┃ █▒ █┃ ``` so `1 1 1 → 1 1 0` and `1 1 1 → 0 1 1` are valid state transitions. ### Obtaining the Recurrence from the Transition Matrix. The paper describes the approach well, but I modified it a little while golfing. As given, the problem is to find coefficients \$a\_i\$ for a given recurrence order \$k\$ such that, for all \$n\$¸ $$a\_0 D\_m(n) + a\_1 D\_m(n+1) + \cdots + a\_{k-1}D\_m(n+k-1) = D\_m(n+k)$$ With regards to powers of the transition matrix \$A\$, this can be rewritten as finding coefficients $c\_i$ such that $$c\_1 A^1 + c\_2 A^2 + \cdots + c\_k A^k = A^{k+1}$$ (the paper starts with \$A^0=I\_L\$, but that is expensive in terms of bytes) Let \$L=2\*m\$ be the width (and height) of the transition matrix \$A\$. Denoting the entries of \$A^i\$ as \$a\_{11}^{(i)}, a\_{12}^{(i)}, \ldots a\_{LL}^{(i)}\$, we can rewrite the recurrence as \$L^2\$ equations $$ \begin{align\*} c\_1 a\_{11}^{(1)} + c\_2 a\_{11}^{(2)} + &\cdots + c\_k a\_{11}^{(k)} = a\_{11}^{(k+1)} \\ c\_1 a\_{12}^{(1)} + c\_2 a\_{12}^{(2)} + &\cdots + c\_k a\_{12}^{(k)} = a\_{12}^{(k+1)} \\ &\;\;\,\vdots \\ c\_1 a\_{LL}^{(1)} + c\_2 a\_{LL}^{(2)} + &\cdots + c\_k a\_{LL}^{(k)} = a\_{LL}^{(k+1)} \end{align\*} $$ Treating \$a\_{hi}^{(j)}\$ as constants (since we know \$A\$), this is a system of \$L^2\$ equations in \$k\$ variables \$c\_i\$. Let \$B\$ be the augmented matrix for this massive system of equations for \$k=L\$. Solving the full \$B\$ would give a recurrence of order \$L=2^m\$, but we need a smaller recurrence. To find a smaller recurrence, we simple use a smaller \$k\$. The bulk of the paper is in proving that the minimum possible \$k\$ is the rank of \$B\$. However, for this specific problem, the minimum \$k\$ is \$k\_0=2^{\lceil \frac{m}{2} \rceil}\$ ([Source](http://oeis.org/A187596#:%7E:text=linear%20recurrence%20of%20order) --- floor since the row \$k\$ has \$m=k-1\$). Thus we can take the \$k\_0 \times (k\_0+1)\$ submatrix at the top left of \$B\$ and solve it to find the \$k\_0\$ coefficients of a useful recurrence. ``` {⍵=1:⍳2⋄(2*⌈⍵÷2)(⌷⌹⍉⍤↑)⍉L↑⍉↑,¨+.×\(L←2*⍵)⍴⊂∘.((0∊+)⍱1∊2|×≢¨⍤⊆⊣)⍨⍸1⍴⍨⍵⍴2} {...} ⍝ Dfn with right argument m ⍵=1:⍳2⋄ ⍝ Special case m=1: return [0 1] ⍝ Compute the transition matrix A: ⍸1⍴⍨⍵⍴2 ⍝ All 2^m states: cartesian m-th power of [0 1] ⍝ (m=1 yields a vector of scalars rather than vectors, which is why we need a special case for m=1) ∘.{...}⍨ ⍝ Outer product with itself (all current→next state pairs) using function: ⍱ ⍝ Neither of the following are true: (0∊+) ⍝ 0→0 in mapping (invalid since we require a horizontal domino when the current state has a 0) 1∊2|×≢¨⍤⊆⊣ ⍝ Some run of 1→1 has odd length (requires a half vertical domino, impossible) ⍝ Compute the minimal polynomial of A +.×\(L←2*⍵)⍴⊂ ⍝ Produce matrix powers of A: A, A*2, ... A*L, where L=2*m ↑,¨ ⍝ B: Ravel each (Vec A*k) and join into single (L×L) × L matrix ⍉L↑⍉ ⍝ B': Trim to first L rows (for numerical stability in later gauss-jordan elimination) (2*⌈⍵÷2) ⍝ Rank r ⌷⌹⍉⍤↑ ⍝ Compute recurrence coefficients α←first r entries of b˜÷B̃ ⍉⍤↑ ⍝ B̃: columns 0 to r-1, inclusive, of B' (taller than B̃ in paper) ⌷ ⍝ b˜: r-th column of B' (taller than b˜ of paper) ⌹ ⍝ matrix divide b˜÷B̃ to get coefficients ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~327 ... 249~~ 246 bytes *Saved 37 bytes thanks to fireflame241!* This is using a port of [my JS answer to *Number of domino tilings*](https://codegolf.stackexchange.com/a/209118/58563) to feed SymPy's `find_linear_recurrence()` method. ``` import re,sympy,sympy.abc as s L=[1];N=2**input()-1;a=[0]*N+L;R=range(N+1) for _ in[0]+R:a=[sum(a[k]*(~k&~i&N<bool(re.match("0b(0*11)*0*$",bin(k&i))))for k in R)for i in R];L+=a[-1:] print sympy.sequence(L,(s.n,1,N+3)).find_linear_recurrence(N+3) ``` [Try it online!](https://tio.run/##JY7BioMwGITvPkUoiyQxFdOFPdTNG0gOXiVIdNPtjzXJJvHgpa/uWjuHYeAbhvFrujt72TaYvQsJBcPiOvv17aUeRqQjilkjOq5qKS6UgvVLwuTMay26SlFZNHUrgra/BsuCk@zmAuoR2B0W7XUvxWXGupsUxc8pf0IuvwfnHjiYctZpvONTNeCKck5oRT9ObACLpxzIrtfUtE@h9ohwRFU3hdDdmV9V5gPYhN5no/lbjB0NbhiOpWWcyeKTkPIG9qd/gDU69MGMSwhH6wW37esf "Python 2 – Try It Online") or [Run a test suite](https://tio.run/##VVLBjtsgEL3zFchbJWCztsk2myqp/yDyIXtMLYs4ZINsAwVcN5f99RSbNtpyQAPz5s28B/rmrkqu7vw3b2rrjJDvRRRFd9FrZRw0nNhbr29hT9mpgcxCC/bFkVa7sljFsZB6cAg/0x0rjnkVl8l@dygMk@8clQnF4KIMrKGQPpkcth5khx6xY1vF6KNdfIhF@f2kVIcMT3vmmiuK8hPKY0pxnMdfInISErULgf2aqFpPBQ9zKOaw2u2Tgh2f6bYC2gtwMAxr@c@By4ajPUE2lYSSMnnBOL0Iea47ITkzteHNYMyMmpJ3Lx2AWZGFBeyEdSgooQRuMAbgCb6JfuiY49C6s28/zxEsAH9NU9bbZT306py22yyzjjWt@sXNpVNj2qg@Yxld5@v16@o123z9Rtd0AwyBo@@pbKqF5p5N8rEOPebby1lpLpGHLc0SA9WdQ5Z4uTb9B3zEBD7qwfgfw@gZxmV4l35yMOjdAujXmI5GOO4fQxvUY5jA6IeMMPBjd8pOY4GH85@cCcXBfUHmw/Sj4Kdvdf8D) ## How? ### State transitions Given \$n-1\$ rows that are entirely filled and given an \$n\$th row which is partially filled with state \$S\_m(n)\$, we want to find out what are the compatible states \$S\_m(n+1)\$ for the next row. In the example below, we have \$m=5\$ and \$S\_5(n)=7\$ (in blue). There are three valid ways of setting the next row while completing the \$n\$th row. The compatible states \$S\_5(n+1)\$ for the next row are \$24\$, \$27\$ and \$30\$. [![example](https://i.stack.imgur.com/pjHts.png)](https://i.stack.imgur.com/pjHts.png) As a rule of thumb, empty cells in the \$n\$th row have to be filled with vertical dominoes (in yellow) and we may then insert horizontal dominoes (in green) in the remaining free spaces of the new row. In the Python code, we use the variables `k` and `i` for \$S\_m(n)\$ and \$S\_m(n+1)\$ respectively. For the vertical dominoes, we make sure that the bits that are cleared in `k` are not cleared in `i` by testing if the following expression evaluates to \$0\$: ``` ~k & ~i & N ``` where `N` is a constant bit mask set to \$2^m-1\$. For the horizontal dominoes, we make sure that the islands of bits that are set in both `k` and `i` all include an even number of bits. We do that with a regular expression: ``` re.match("0b(0*11)*0*$", bin(k & i)) ``` Both tests are combined into: ``` ~k & ~i & N < bool(re.match("0b(0*11)*0*$", bin(k & i))) ``` ### Number of valid tilings The variable `a` holds a list of \$2^m\$ entries describing how many times each state appeared in the previous iteration. We update `a` by using the above tests: the new value for `a[i]` is the sum of all previous values `a[k]` for all pairs of compatible states `(k,i)`: ``` a = [sum(a[k] * (...) for k in R) for i in R] ``` The total number of valid tilings is the number of times we reach the 'full' state (\$2^m-1\$) for the last row, which is `a[-1]`. ### Final solution We use this method to compute the first \$2^m+2\$ terms of the sequence in the list `L` and inject it into `find_linear_recurrence()` to get the final solution. **Note**: According to [OEIS](http://oeis.org/A187596#:%7E:text=linear%20recurrence%20of%20order) (and as already pointed out by fireflame241), computing \$2^{\lceil m/2\rceil}\$ terms would be enough and would make the code faster, but also a bit longer. [Answer] # [Python 3.8](https://docs.python.org/3/), 228 bytes Similarly to [Arnauld's answer](https://codegolf.stackexchange.com/a/209203/68261), this uses [my answer to Number of domino tilings](https://codegolf.stackexchange.com/a/209206/68261) to feed SymPy's `find_linear_recurrence` function. ``` from math import* import sympy,sympy.abc as s def f(m):N=2**m+2;return sympy.sequence([round(abs(prod(2*cos((i//k+1)*pi/-~m)+2j*cos((i%k+1)*pi/-~k)for i in range(m*k)))**.5)for k in range(N)],(s.n,1,N)).find_linear_recurrence(N) ``` [Try it online!](https://tio.run/##VY9NboQwDIX3nMKbSnFIQVDNhmpuMOICVTUKEDop5KdOsmDTq1PKUI268eI9@/N7fok3Z19WbbyjCM4rktFRNpIzMCbbR@fmAIdNaki9yjy54TxL0w0SLs1dZH@nhUmzgIuACtedYmS8HQCeHaCwGL@IfRay60EGCNmgRhiZwaY915ybvH4lFRPZ@3YR1FdSdvv0Ri7ZgckusN8krOa9C4zpspzyCrnX5fO3wbz@PPSnhzzh6Ag0aAsk7Ydihk@IyHlx2p3p4bT4LlgorKhEi1iM2g7XWVsl6UqqT0R7lnYr@Z9YiRM2GYAnbSPTYqukEdcf "Python 3 – Try It Online"). TIO doesn't have sympy in its Python 3.8 installation, so the link includes a polyfill of `math.prod`, which is new to 3.8. Since this multiplies (floating-point) complex numbers together, it loses precision for \$m\geq 5\$, leading to a completely incorrect recurrence. ]
[Question] [ ## Problem Description We all love a Twix (because it is the best candy), but this is the kids' first Halloween --- we gotta grab at least one of each type of candy for them. Each Halloween all the residents of Numberline avenue send out an email saying what types of candy they'll be giving away this year. Oh! And we live in a 1D world. Being exceptionally lazy in some ways and not in others, we've made a map of the houses giving their positions along the street. We also noted the types of candy they have. Here's the map we made for this year: ``` [(-2, {"Kisses", "KitKats"}), (1, {"KitKats", "Peanut Butter Cups"}), (6, {"Kisses", "Twix"}), (9, {"Skittles"}), (10, {"Twix"})] ``` For the sake of the kids' little legs, we need to find the **shortest** walk starting at any house in the neighborhood to gather at **least one** of each type of candy. ## Examples At the request of a couple users (including Shaggy), I'll toss in some worked examples. Hopefully this clears things up. :) **Input:** ``` [(-2, {"Kisses", "KitKats"}), (1, {"KitKats", "Peanut Butter Cups"}), (6, {"Kisses", "Twix"}), (9, {"Skittles"}), (10, {"Twix"})] ``` **Output:** ``` [1, 2, 3] ``` Another map and solution... **Input:** ``` [(-3, {"KitKats", "Twix"}), (-1, {"Hundred Grands"}), (3, {"Kisses"}), (12, {"Hundred Grands", "Twix", "KitKats"})] ``` **Output**: ``` [0, 1, 2] ``` We could begin at the coordinate 9 house collecting candies to at houses 6 and 1. That fills the candy quota by walking 8 units, but is it the shortest solution? ## Rules Entries must take in a *similarly* structured single argument to the example and output the indices of the houses to visit in the shortest solution. Typical code golf rules apply: shortest correct solution in bytes wins! *P.S. This was an interview question given to me by one of the world's largest tech companies. If you don't like golf, try finding an O(k\*n) time solution where k is the number of candy types and n is the number of houses.* ## Edit As Jonathon Allan pointed out, some confusion exists around what "indices" means in this case. We want to output the houses positions **in the argument list** and not their coordinates on the lane. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒPṪ€ẎQLƲÐṀẎISƊÞḢ ``` A monadic Link accepting the input as described in a list sorted from lowest to highest Numberline Avenue houses (if we need to accept any ordering we can prepend an `Ṣ`) which yields the shortest path starting at the lowest numbered house and travelling up the Avenue. **[Try it online!](https://tio.run/##y0rNyan8///opICHO1c9alrzcFdfoM@xTYcnPNzZAGR7Bh/rOjzv4Y5F////j47WNTLQUYhW8s4sLk4tVtJRALJKvBNLipViY7l0onWNQZLB2ZklJTmpUDEFQ4gGiDKgjoDUxLzSEgWn0pKS1CIF59ICmEIzVJNDyjMroDKWmMYagt0BUxMLAA "Jelly – Try It Online")** If we want to find all such shortest paths replace the trailing bytes, `ÞḢ`, with `ÐṂ`; this is also 16 bytes. ### How? ``` ŒPṪ€ẎQLƲÐṀẎISƊÞḢ - Link: list of [index, candies] ŒP - power-set ÐṀ - keep those for which this is maximal: Ʋ - last four links as a monad: Ṫ€ - tail €ach -- this removes the candies lists from the current list - and yields them for use now Ẏ - tighten (to a flat list of candies offered by these hoses) Q - de-duplicate (get the distinct candies offered) L - length (how many distinct candies are on offer) Þ - sort (now just the indexes of remaining sets due to Ṫ) by: Ɗ - last three links as a monad: Ẏ - tighten (to a flat list of indexes since Ṫ leaves a list behind) I - incremental differences (distances between houses) S - sum Ḣ - head (get the first) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~133~~ ~~130~~ 127 bytes ``` def f(l):r=range(len(l));v,c=zip(*l);print min((v[j]-v[i],r[i:j+1])for i in r for j in r if s(*c)==s(*c[i:j+1]))[1] s={0}.union ``` [Try it online!](https://tio.run/##VYwxb8IwEIV3fsUp05maijBUKshLO7JUopvlIaI2XEgvkX1JaRG/PU0UqNTpvnvf02u@5Vjzqu8/fICAlVpHEws@eKw8D6/adHpvfqjBeaU2TSQW@CRG7GzpFp0lp6OldfmQOxXqCATEEGHEckIKkHC@V8aM595VNnezZC7L62PLVHMf0OJipeGSbSklnzINA8m2kJRdlZ4B5pOcosG@@YJbgZdWxEd4bZt78en/yvsXnW/meTS7E4lU/m92OYa3klP9Lw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æʒ€θ˜I€θ˜åP}€€нD€¥OWQÏ ``` Assumes the numbers in the input-list are sorted lowest to highest. If more than one solution is found, it will output all of them. [Try it online.](https://tio.run/##yy9OTMpM/f//8LJTkx41rTm34/QcTyh9eGlALZAJRBf2ugDJQ0v9wwMP9///Hx2ta6QTreSdWVycWqykA2SUeCeWFCvFxuooRBuCZSACOkoBqYl5pSUKTqUlJalFCs6lBVBVZsj6Q8ozKyDClkDh4OzMkpKcVJhxBkAhqIJYAA) **Explanation:** ``` æ # Get the powerset (all possible combinations) of the (implicit) input-list ʒ # Filter this list of combinations by: €θ # Get the last items of each (the list of strings) ˜ # Flatten the list I # Get the input-list again €θ˜ # Get the last items of each (the list of strings) flattened as well å # Check for each if it is in the list of strings of this combination P # Check if all are present } # Close the filter (we now have all combinations, containing all unique strings) €€н # Only leave the first items of each item in the combination (the integers) D # Duplicate this list €¥ # Get the deltas (forward differences) of each O # Sum these deltas W # Get the lowest sum (without popping the list) Q # Check for each if it's equal to this minimum Ï # And only leave the list of integers at the truthy indices # (which are output implicitly as result) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 70 bytes ``` {grep({.[@^i;1]⊇.[*;1]},combinations ^$_).min:{[-] .[@^i[*-1,0];0]}} ``` [Try it online!](https://tio.run/##bY/BqoJAFIb3PcVBIixG0YKgJIhadKFNULthiinHGMpRZkZuIa6DHrMXMS2NinaH///4zjkxk8d@Hp6hFcAoT/eSxWZq4/Gaey65XS827hRDhnZRuOWCah4JBevmpm2HXAxTbBF40LhjucghnkOyLFf0DIFZQBBEsoFNq4sAG3OuFFMGgmLSc6qVQdqoAab7LJ9R0S4YFYmGSaI1kzBN4hrsf1pW//xUNYOyWR641kf20jplWEEElWf0vja9GazHFX@J8CXzYSap8GtR721tpe7@gGvfx3/Ey@8 "Perl 6 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~343~~ 372 bytes Thanks to [@ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for improvements, there's also a [271 bytes variant](https://tio.run/##bVDRagIxEHy/r1glDwnkxCoUipwUW2iLhRZa6IOK7uVSDSa56yVHz/68zdVqVfq0w85kZjYrdGup9XarTJGXHm7RY@dROR8dL57KLEKKfM7nLMFBSuc8bWA6EAHOuWCJiDSY5F1pL0tKk8RgrUxlqMECUjCMdVJmIgsuEcQo23CjDRW5KbBUdgnIiCZBTKc6HlIXXn6p4k35FZ3WsImHmDqCUMcIG6aJR6VBM66lXfoVsVVKRG4FerLL07yZIkgYcVXq5EclrZBul4DXtOYbFnLC4LiQWpoHm6kgWLhWq8uY2xpUFhLI8giKUNADAQsTGvc4TNpj5Zx0bQ4B@TF6154xHgHQix272wX6WaKtPIwqH74FbqrioLw89Xn9VPWeumqol7XyXss/526z/ZXNzkr1z2KP3eKfTveVzUqZwV2JNjuY9o9K7HN6/8j3licHz7bf) he proposed in the comments :) ``` import Data.List import Data.Function f s=subsequences(map(\a@(x,y)->(x,y,[(a`elemIndices`s)!!0]))s) g f s=if f*s<=0 then f+abs f+abs s else f+abs(f-s) h=foldl(\(a,b,c)(d,e,f)->(g a d,nub(b++e),c++f))(0,[],[]) i s=map h(filter(not.null)s) l m=filter(\(_,x,_)->length x==(maximum$map(\(_,x,_)->length x)m))m m=minimumBy(compare`on`(\(p,_,_)->p)) n s=(\(_,_,l)->l)$m$l$i$f s ``` [Try it online!](https://tio.run/##bZBfT9swFMXf8ykuVR5s4qIOJCSkZZrYBEzsYdJ4a6PWSa4bC/smxLYWPn1x@gcKTIoc@97j3z3HjXSPaMxmo23X9h5@Si/Pfmvnk@PCTaDK65YSBS53oXT4FJAqdMzKji3kdzaIZz79Nv7EnMkVGrS/qNZRsnL85GRWcO54soYRoBWoU/c1n4FvkEBlsnT71QEah7sDU9N4pclVa2rDFkyKUlSc1QKFGmetQUItKJSszDLkosoyxTmbiXkRP57oOCrag4YpbTz2jFp/RsGY0YkBm@/LC7YUg1hGpEFa@waGPI@5Bm2DTbf5Pgm45dwmNreaRtX1M6ta28keVy2tor4Ty62@4zyhaGOLWAozInhqU5PqNL7ExkpNkEPdJtD1mjykQDBn03MB88m9dg7dREDc@Xvp3aTgIgFgX3bdXS22/6Ck4OE6@BgHfoTuVXn5nvPwTw@H1tXY@vuovTf4Rp6N1b2s@GDq4sPYY9p06@kuUN1jDbe9pPoVenFk4jDn/D/yA/Jd4GLzAg "Haskell – Try It Online") --- **Ungolfed** ``` import Data.List import Data.Function allPaths :: [(Integer, [String])] -> [[(Integer, [String], [Int])]] allPaths xs = subsequences(map (\a@(x,y) -> (x,y,[(a`elemIndices`s) !! 0])) s) pathLength :: Integer -> Integer -> Integer pathLength f s = if f*s <= 0 then f + abs f + abs s else f + abs(f - s) traversePath :: [(Integer, [String], [Int])] -> (Integer, [String], [Int]) traversePath = foldl (\(n1, a1, c1) (n2, a2, c2) -> (pathLength n1 n2, nub (a1 ++ a2), c1 ++ c2)) (0, [], []) allTraversedPaths :: [[(Integer, [String], [Int])]] -> [(Integer, [String], [Int])] allTraversedPaths xs = map traversePath (filter (not . null) xs) getCompletePaths :: [(Integer, [String], [Int])] -> [(Integer, [String], [Int])] getCompletePaths m = filter (\(_,x,_) -> length x == ( maximum $ map (\(_,x,_) -> length x) m)) m getFastestPath :: [(Integer, [String], [Int])] -> (Integer, [String], [Int]) getFastestPath = minimumBy (compare `on` (\(p, _, _) -> p)) getPath :: [(Integer, [String])] -> (Integer, [String], [Int]) getPath xs = (\(_,_,l) -> l) getFastestPath $ getCompletePaths $ allTraversedPaths $ allPaths xs ``` --- [First attempt](https://tio.run/##VU9dS8MwFH3vr7iMPiQ2G1NQEKzIFEGnIOjbNra0u1nDkrT2Jtj9@pm6KQ5CPs4595yTStIWjdnvtW3q1sOD9HL0oskn/4HH4Eqva3cCvspdgUmigHIKBeFnQFciMSsbNpd3rBM7PrztDzFTbW2fA/lUrtCgfXJr7Fa04Jx4soHeQitQZ3STj8FX6EBlsqDjToCG8PBgahhHqlzVZm3YnElRiJKztUCh@rQNSFgLFwpWZBlyUWaZ4pyNxWwRF090jIoFoWJKG48tc7UfuWBM38TkR3DOlqITy2ho0G18BV2eX/LE5lY7bYOd7FhZ20a2uKrdKsobsfyRN5wnro9ITarT@K@9ldpBDk2rnYcUHMCMDS8EzAZTTYQ0EBBvfio9DRZcJMDOD@QBiuwbShc8TIKP1eA@NL/Cq1OXjy/dHZnrnnnfau8N/tmOe/AoWuy/AQ "Haskell – Try It Online") [Answer] # O(k\*n) time solution, with O(k\*n) space Let \$x\_i\$ be the position of the \$i\$th house (where \$0 \le i < n\$, and \$x\_i\$ are sorted) and \$c\_i\$ be the list of candies offered by the \$i\$th house. Observe that if we have a path from house \$i\_1\$ to \$j\_1\$ that gets all candy types, then for all \$i\_0 < i\_1\$, there is such a path from \$i\_0\$ to \$j\_0\$ where \$i\_0 \le j\_0\$. Thus, our algorithm is: ``` // A[k] is the number of each candy we get from the first k houses A := array of n bags A[0] := {} for k := 0 to n - 1 A[k] := A[k - 1] + c[k - 1] end best_distance := ∞ best_i := -1 best_j := -1 // Find the range [i, j] such that we get all candy types j := n for i := n - 1 to 0 while j > i and (A[j - 1] - A[i]) has all candy types j := j - 1 end if (A[j] - A[i]) does not have all candy types then continue end distance = x[j - 1] - x[i] if distance < best_distance then best_distance = distance best_i = i best_j = j end end return best_i ..^ best_j ``` The construction of \$A\$ takes \$O(k)\$ time for each element, or \$O(nk)\$ time (and space) total. The outer loop for computing the best distance executes \$n\$ times. The inner loop can execute up to \$n\$ times in one iteration, but the body is executed at most \$n\$ times, so the condition is checked \$O(n)\$ times; thus, the inner loop accounts for a total of \$O(nk)\$ time. The rest of the outer loop body takes \$O(k)\$ time as well. Hence, our algorithm takes \$O(nk)\$ time and space. ]
[Question] [ Given three non-negative integers `y`, `m`, and `d` (of which at least one must be positive) and a valid date with a positive year (in any reasonable format that includes the year, month, and day, and no additional information), output the date that is `y` years, `m` months, and `d` days after the original date. The Gregorian calendar is to be used for all dates (even dates prior to the adoption of the Gregorian calendar). The method for computing the next date is as follows: 1. Add `y` to the year 2. Add `m` to the month 3. Normalize the date by applying rollovers (e.g. `2018-13-01` -> `2019-01-01`) 4. If the day is past the last day of the month, change it to the last day in the month (e.g. `2018-02-30` -> `2018-02-28`) 5. Add `d` to the day 6. Normalize the date by applying rollovers (e.g. `2019-01-32` -> `2019-02-01`) Leap years (years divisible by 4, but not divisible by 100 unless also divisible by 400) must be handled appropriately. All inputs and outputs will be within the representable integer range of your language. # Test Cases Test cases are provided in the format `input => output`, where `input` is a JSON object. ``` {"date":"2018-01-01","add":{"d":1}} => 2018-01-02 {"date":"2018-01-01","add":{"M":1}} => 2018-02-01 {"date":"2018-01-01","add":{"Y":1}} => 2019-01-01 {"date":"2018-01-30","add":{"M":1}} => 2018-02-28 {"date":"2018-01-30","add":{"M":2}} => 2018-03-30 {"date":"2000-02-29","add":{"Y":1}} => 2001-02-28 {"date":"2000-02-29","add":{"Y":4}} => 2004-02-29 {"date":"2000-01-30","add":{"d":2}} => 2000-02-01 {"date":"2018-01-01","add":{"Y":2,"M":3,"d":4}} => 2020-04-05 {"date":"2018-01-01","add":{"Y":5,"M":15,"d":40}} => 2024-05-11 ``` You may use [this JSFiddle](http://jsfiddle.net/ansgr401/) for testing. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in each language) wins. [Answer] # [C (gcc)](https://gcc.gnu.org/), 291 bytes This one was pretty fun to get returning the same values as the JS builtin. ``` z,m=0xEEFBB3;int*y;g(){z=28+(m>>y[1]*2&3)+!(y[1]-1)*(!(*y%4)&&(*y%100)||!(*y%400));}h(a){z=(a>g())?g():a;}j(){*y+=y[1]/12;y[1]%=12;y[2]=h(y[2]);}f(int*a){y=a+6;for(z=0;z<3;z++)y[z]=a[z];y[1]--;j();*y+=a[3];y[1]+=a[4];j();y[2]+=a[5];for(;y[2]>h(y[2]);(y[1]=++y[1]%12)||++*y)y[2]-=g();y[1]++;} ``` [Try it online!](https://tio.run/##fVFNb9swDL37V6gtHMiWvEq2kyVT5AEFsu1Q7LSbp4Nn50ND4wxJVsxO/dszUnaHZIcClkjx8T2SZhmty/J8Z@vy6Xe1JPPDsbK7d5vMuwo92R8QO7d8q8WfxeLTw0OibH0MG7WmwanV8ZTRbZY1uTRhPEoCdkPRj2QQ0hsaNn4ajEZopRDBy0sfAjdQ3YYWqECLDKSCj3B9KFT3E2TDhmlUuZexQutr58RGbygaIK8odgECjS7YRK12e9pqodp5olrGgiZvjS7gcvwoUiCrULbIkz6GbmpcHCXxOTZOx72z10puHM2Y60PGMANjYRMgGOm1Y4MYU935rlqubL0kj4uvn799geEIPdh2uVuBez940HHgedA6KXKTz4w@eYScYiEEJzF8M06IhCPwdBxBOXsDBGb6BiinHIMJAnGfkMr/QHfG4I75WAxM0Xmd6vvcFramruH9uuTlptiTMAT/OSDYOyKHY7E/asGXdaX/DR9JhTAMD7xs0mcTgj8YORaWZecTZWFZ8C8uaCa3sLrjziLzObdMwhYct69zWYFclcSszvMuizgKFIK8vtTQBS2gyiD7aw@5K3rri7SKfBH3F2F@1XA/rrbcT6qKaHKNf69vuaMTglq5MNxZOdjYXMHJEE4HO76GJ0P4/WCnZpimO/8F "C (gcc) – Try It Online") Un-golfed: ``` // De No Oc Se Au Jl Jn Ma Ap Mr Fe Ja // 31 30 31 30 31 31 30 31 30 31 28 31 = Month length // 11 10 11 10 11 11 10 11 10 11 00 11 = Offset (2-bit representation) // E E F B B 3 = Hex representation int m=0xEEFBB3; // Month lengths-28 in reverse order, stored as 2 bits/month int *y; // Pointer to the output date, shared as a global between calls // Regenerate month length and add leap day int days_month(void) { return 28+(m>>y[1]*2&3)+!(y[1]-1)*(!(*y%4)&&(*y%100)||!(*y%400)); } int calendar_day(int day) { return day>days_month()?days_month():day; } void truncate_date(void) { *y+=y[1]/12; y[1]%=12; y[2]=calendar_day(y[2]); } void f(int *a) { int z; y=a+6; for(z=0;z<3;z++)y[z]=a[z];y[1]--; // Convert month to 0-based truncate_date(); *y+=a[3]; y[1]+=a[4]; truncate_date(); y[2]+=a[5]; for(;y[2]>calendar_day(y[2]);(y[1]=++y[1]%12)||++*y) y[2]-=days_month(); y[1]++; // Return month to 1-based } ``` [Try it online!](https://tio.run/##fVRtb9s2EP6uX3Ft4UCvMynZWTJFHpouaREs7dDtmyYEtETbBGzKkOiscuvfnh4pNpOKooB5PN7dc/fwjnIZrcvy6ZWQ5fZQcbhqVSXqXzYLZ2TaiiXanqZT@IPD@xo@lPA3h9cHuNvCnYR7Bq/3cN/ALYc75mBYQiEhAzk@xhdaZnBfS7WBLZdrtdEoSoGSgRwfiZEZfFitWq7AjaOlUNDwfcNbLhVTopaeTgNwA/Asb428HsgEVwbv@KfvwI4jpIJdRj7d3NxeXycpYLIhxzZC5kIi7JE3LYe6qXgTQqvqhlfAWogBKbXTncaYZH5nkvxV44E3oGpQG8Qd1P6goGKKI3rDLJrBelsv2RaWXP3HuYSSbbeto6/0ka@55A0CYDcgBEwisqrwyPaYrzNFcW8fTJj7WIvKg8/gAJJWh0Zi7wN3t1h0OS38@Czxgheu1iPq@e4L1@8mM@/sTO@UEO/Ll96Eqpc6p75ByIrLijUPWMe19XQNWwBPiwED7/fh4Tc8pICJNDFQzUGWeKcH3YlvXJGq3wWZJjWlcQpamWSooaPL4yIb1deWnprJuDKEfNbn0frR4DIWnGtlVTfuMSPp8SpJj0HgdfmxyBiK1DQhMtN6U0ucr7KdxpmRaMlaXiF@zNhLLVmWJ0XPVOsz1H8QqKlq97z4xiTVpsUP7mNGkgWBuTuNcQ5B4Heeo1@vjoiyYVP75Fg7MPQ/9nN4Zk8t@9PTq4qvhOTw5837t/@8c7FLbiuOvF6hOrUa9s7r58zyIr8sMt3IzzEhJIQYf5chAMVF9DqF2kkvf@JE5OwnTnoRamOiHXEfMKPfOc2aozoP58Qiyck5pfaDZUKasbNmXYYlfk7g@6g//v8IWsUalZEQ@5w9Xz6iunECL4@4xXkf3Q9GYwQ@E3F1ngp8JtiLAazIBT4aVQuNfMxFQAszA7B1hhVgVFJH4VMdFjEQLIRxfSnLwmVYxabdNxi7cl9OyKyKJiTuBQSTqgsncbULJwn@B2Qw9v8rX4YGDqBz5aQIzU7tHhcjd2LNM7vPx@5za/7V7heFvc3p6Ss "C (gcc) – Try It Online") [Answer] # perl -MDate::Calc=:all -E, 28 bytes ``` $,=$";say Add_Delta_YMD@ARGV ``` This takes 6 arguments: the input year, month and date (as separate arguments), and the number of years, months and days to add. [Answer] # [R](https://www.r-project.org/), 88 bytes ``` function(Y,M,D,y,m,d,o=M+m){while(is.na(x<-ISOdate(Y+y+o%/%12,o%%12,D)))D=D-1;x+864e2*d} ``` [Try it online!](https://tio.run/##dc/BaoNAEAbge59CKMJunU1nRg1K4s1LD9JDTx5DVCo0CmlKlJBnt7tLq60my7CX/fj/2eNQJUP11exPdduIHDJIoYcDFNAmmXeQl/N7/VGK@nPV7ES3VS9vr8XuVIrc673WfXaJoXXNnUop0yRVtOm8aB2U/FRch0owUgRIZhy0Q9LR59ExLwpJIT8smLn/MdZyxn4CJxbbtL/Mx3tpHC0Zz5mvfLQMEZCB42Wp3f83bWLBnAWWxSMbS03vxPDmT/Vivs4cGWumA8MZC4FCCKZSNkYRDd8 "R – Try It Online") A function that takes 3 arguments (`Y,M,D`) for the date, and other 3 arguments (`y,m,d`) for the values to be added. The output comes with prepended `12:00:00 GMT` which is the default format for `ISOdate`'s [Answer] # [Perl 6](https://perl6.org), ~~60 50 45~~ 44 bytes ``` {Date.new($^a).later(:$:year).later(:$:month).later(:$:day)} ``` [Test it (60)](https://tio.run/##jZJNb5tAEIbv/IoRpTWomACOo4TYqJXSW3OLoqaHVht2aiMtH2KXtJbLb3dnF@KvtE4FB2ZnnvednaHGRlxsWonwdBFk15ZVrOBdVnGE@WZ9wxQGJf50nW/MCwRFjZs4yQpZsxcWVamWezFnK6/bkM4HhVLBHEReogwKViewtgDeQJGXecEEZEtWLlCCqmCBCvCJiZY9CgTOFKNK0nCdvKxb5Tv4q8ZMIfdIMJDto1TuCOYpjHx6vOEkWfijhGKT8IJP9x8/05W0paxFrqCtQS0RjOSBCX2j71SCjxk3Fr3tTJ8DHaWDTN@xEaFTI/HcfStN61I1babaBoNe@62um8NMDw3MqIhapfCVWnSfHWcPcAs8hS9nZxB6g1eDJFMCKwGZzLHRRnpRWweqcqFv3dj4sJ0SfX4HEuosSyN3tIhrqxak9d5shSx@VM2woXF6SoejzMAzm8sl6F9jW/zbXM57WW91m7Wta@zEjsPochxG9Nq@TfV2Qik7ibpOb2mXjm3rJHN7zMQ6fZp5OGCuhvRLZhKe9IkvX2fiA2ai0/tMGBqhq3/0ZgZw7PNX5nzHnA/pY@awN77fWy/5P3OLfX2ria/5nWdMPNlOX@enho@mvUC4U9D4OIrsPw "Perl 6 – Try It Online") Input is `( "2000-02-29", year => 1, month => 0, day => 0 )` --- ``` {$^a.later(:$:year).later(:$:month).later(:$:day)} ``` [Test it (50)](https://tio.run/##jZJNb5tAEIbv/IoRpTWrYgI4jhJiW63U3ppbFSU9tNqwUxuJL7FLWsvlt7uzCzG2kzoVHNiZed53doYK6@xi20iExws/ubasfA3vklIgzLcb5zv3M66wdmMnXiOv2XDMy0Kt9s6Cr1m7JfqDQqlgDllaoPRzXsWwsQDeQJ4Wac4zSFa8WKIEVcISFeAjzxr@kCEIrjhVkobrpEXVKM/B3xUmCgUjQV82D1K5I5gvYOTRw/pIvPRGMZ1Ngvmfbz9@oYtoS1llqYKmArVCMJIHJvSNnlNmYsyFsehsZzoOFFr0Ml3HRoSiRuKp@0aa1qWqm0Q1Nfqd9ltdN4eZHhqYURG1XsA3atF9cpzdww2IBdydnUHAeq8aSaYAXgBymWKtjfR6dg5U5cIn6tAv8Fd3B@YZQw9286LPH0CSrWVp@Cut5NqqMlJ9b/ZDZj/Lut/VmHqCbhgv6AiUCTCzw1SC/jV2xX/MNdnzeqvdbmxdY8d2FISX4yCk1/ZsqrdjStlx2LZ6X0M6sq2TzM0xE@n0aeb@gLnq08@ZSXDSJ7p8nYkOmIlO7zNBYISu/tGbGcCxz4vM@cCc9@lj5rA3sd9bJ/k/c4s8fauJp/nBMyKebKev81PDh9NOIBgUND4OQ/sv "Perl 6 – Try It Online") Input is `( Date.new("2000-02-29"), year => 1, month => 0, day => 0 )` --- ``` {$/=$^a;$/.=later(|$_) for |[R,] $^b.sort;$/} ``` [Test it (45)](https://tio.run/##jZLBbptAEIbvPMWI0hpavAEcRwk2Viu1t@RSVZXSqonW7MRGwoDYJanl@Nmd2YXEsZM6FRyWmfn@f3aGCuv8ZNNIhNsTlo4sa7GED2kpEJLNyjlKnCs@co5YknOFtXvvXHtwU9Zw//u7/wecqymTZa2oYr0h8LNCqSCBPCtQsgWvYlhZAO9gkRXZgueQznkxQwmqhBkqwFueN3yaIwiuOFWShutkRdUo38G/FaYKhUeCTDZTqdweJBPo@fR4XSSe@b2Yvk3CY99@fjmnO2hLWeWZgqYCNUcwkjsmdEbfKXPR58JYtLZjHQcKTTqZtmMjQlEj8dh9I03rUtVNqpoaWav9Xtcl4I6XyGtYlIWaE7acwC/q8dFxfAkXICYem9VIU/rI9CSQCbyh0YnOu0aSLYAXgFxmWGtjvaknR6py4St1zAq8a@/k@aYBH57mR8dr8EbW2rI0/INWNLKqnFQ/mX2Rmd5ou7v@hBTb4byiI1Cm4JmdiozPwDaVrKJ/yPVMfXe2R1SSSdA/0o4eeC8VrfVmZesSO7ajIDztByG9tm9TvR1Tyo7D9VpveJuObOsgc7HPRDp9mLncYc669EtmEBz0iU7fZqIdZqDTz5kgMEJn/@jNDGDf51XmeMscd@l9Zrc38by3VvJ/5hb5@lYDX/Nbz4h4sh2@zQ8NHw5bgWCroPF@GNoP "Perl 6 – Try It Online") Input is `( Date.new("2000-02-29"), %( year => 1 ) )` (No need to include keys with a value of 0) --- ``` {$/=$^a;$/.=later(|$_) for |[R,] %_.sort;$/} ``` [Test it (44)](https://tio.run/##jZLBbptAEIbvPMWIkhpavAEcRwkOViu1t@ZSVZXSqrU27MRGwoDYJall@9nd2YXYsZM6FRyWmfn@f3aGCuv8fNNIhPtzlo4sa76At2kpEJLN0jlNnN985JyyJOcKa3flTDy4K2tY/fzq/4KTCZNlrahgvSHug0KpIIE8K1CyOa9iWFoAb2CeFdmc55DOeDFFCaqEKSrAe543/DZHEFxxqiQN18mKqlG@g38qTBUKjwSZbG6lcnuQjKHn0@N1kXjq92L6NgmPff7@8QtdQVvKKs8UNBWoGYKR3DOhM/pOmYs@F8aitb3ScaDQuJNpOzYiFDUSj9030rQuVd2kqqmRtdonui4B92qBvIZ5WagZYYsx/KAeHx2vbuAaxNhj0xppSu@YngQygXc0OtF510iyBfACkMsMa22sF7V1pCoXPlHHrMCH9k6ebxrwYTs/Ok7AG1lry9LwN1rRyKpyUn1v9kVmeqHt7vpjUmyH84KOQJmCZ3YqMj4F21Syin4h1zP13dkeUUkmQf9HW72VmYz3XNJab5a2rrFjOwrCi34Q0mv7NtXbMaXsOFyv9Yp36ci2jjLXh0yk08eZmz3msks/ZwbBUZ/o4nUm2mMGOv2UCQIjdPmP3swADn1eZM52zFmXPmT2exNPe2sl/2duka9vNfA1v/OMiCfb4ev80PDhsBUIdgoa74eh/Rc "Perl 6 – Try It Online") Input is `( Date.new("2000-02-29"), year => 1 )` ### Expanded: ``` { # bare block lambda $/ = $^a; # store only positional param into a modifiable scalar # (params are readonly by default) # do a loop over the data to add $/ .= later( # add using Date.later() |$_ # turn current iterated Pair into a named parameter ) for | # flatten so that `for` will iterate [R,] # shorter than `reverse` (year=>1, month=>0, day=>0) %_.sort # sort the named arguments (day=>0, month=>0, year=>1) ; # return new Date $/ } ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 48 bytes ``` (a,y,m,d)=>a.AddYears(y).AddMonths(m).AddDays(d) ``` [Try it online!](https://tio.run/##rZJRa8IwEIDf@ysOnxJoa5oqKE5BJj6tbExhjLGH0EQXsCk02UYZ/vYuTX2owlRmj7S90qPffcelOkjzQlTpjmkNT96PBzbSXGkD2hRSbWH5@JzM1zCFXmkjSJKA897Ec4XaMCNTKATjudqVsCq1EVm4/FTp3SFfMCPWMhM@SGXat5PvM9jAtELML/3M53g6Y@Gc81fBCo1KXOdJrsyHRpl7WbBSI44rOMRxQ1@55JAwqVAj8fYOrNhq7GoaxzoOLdxb3XwnwpdCGvEglUAbpMT3aYeIkmjkQ2QP9oG4E@Fwna8cAzWDwnhS/7rfh7o8IFFAaFdAm5GLQGqZnQCjRvI8cOwMbwfG5KJiy5COOgPSK4BxEJP/A0lDoeOLM3VAtzE3GbaBgyuAAwcc3wZsjbTGnwWSDrfUisZW8@yWUgu0ksNOgEP7sNfgj5k2wJoWRI3h3ttXvw "C# (.NET Core) – Try It Online") [Answer] # Java 8, 51 bytes ``` (s,y,m,d)->s.plusYears(y).plusMonths(m).plusDays(d) ``` Input (`s`) and output are both `java.time.LocalDate`. [Try it online.](https://tio.run/##vVJBS8MwGL3vV3z0lEAS0m4DZczT8GSHMC8iHmKbameTliYbFNlvr1/r3EF78GCbhI@8kLz3vUf26qj4Pn1vk0I5B7HK7ccMILde15lKNGw7CLDHe8LnRou7MlHFRnkNCRk6dQwfQ9NX09eUrpDjNMPivPJ5AluwsIaWONYww1LKb5yoioN71Kp2pKE9iEvr3xwxX2ijGkdS2q46murwUiDNme1Y5ikY7JzsfJ3b16dnUPRn21lZG@VF1@ID4tseoknILrv1H66LMrvvN5YEDQ4exzxNg94hwK5xXhtRHryosBNfWHKhP1MSKwZzExVa1ySIZHjFZYgrYJe3lEmcIaUT6IRMTqATdo7G0JnLafz80on@W0dKLiMeXY@d26DOYhydgdwwuQn@W8TmbDGBzpKFS7b4Tu40O7Wf) **Explanation:** ``` (s,y,m,d)-> // Method with LocalDate and 3 int parameters and LocalDate return-type s.plusYears(y) // Add the years to the input start-Date .plusMonths(m) // Add the months as well .plusDays(d) // And add the days as well ``` [Answer] # [R](https://www.r-project.org/), 65 bytes ``` function(x,y){require(lubridate) x%m+%period(y,c("ye","mo","d"))} ``` Uses the `lubridate` package. The `%m+%` infix operator is sugar for the `add_with_rollback` function which essentially implements what the question asks for. TIO doesn't have `lubridate` so you can [Try It Here Instead](https://rdrr.io/snippets/) with `f <-` prepended to the function above along with test cases: ``` f(as.Date("2018-01-01"),c(0,0,1)) f(as.Date("2018-01-01"),c(0,1,0)) f(as.Date("2018-01-01"),c(1,0,0)) f(as.Date("2018-01-30"),c(0,1,0)) f(as.Date("2018-01-30"),c(0,2,0)) f(as.Date("2000-02-29"),c(1,0,0)) f(as.Date("2000-02-29"),c(4,0,0)) f(as.Date("2000-01-30"),c(0,0,2)) f(as.Date("2018-01-01"),c(2,3,4)) f(as.Date("2018-01-01"),c(5,15,40)) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~150~~ 149 bytes ``` a=$2+$5-1+b y=$1+$4+a/12 m=1+a%12 d=date $d -d@$[$($d +%s+$6*86400 -d$[y]-$[m]-$($d +$3%n%d -d@$[`b=1;$d +%s-86400 -d$[y]-$[m]-1`]|sort -n|head -1))] ``` [Try it online!](https://tio.run/##ZYvBCoMwEETvfoWHDdQuodloRSiB/kcImBDBiwqNF8F/3y5tb73MDDNvUiwzc3RgEe6aMFWHA0LoMN7IVosjjEpCdjnuUwW51vkJHi6SUBWE/jr0nTFSgz@CBr@IfFZo1ap@/JgcPb4X/c/TGM6yvfZar@c8RflQ0wRmtoYGJm4NGzHzBg "Bash – Try It Online") Takes input via command line arguments in order: old year, old month, old day. year change, month change, day change. Outputs a string like `Wed Feb 28 00:00:00 UTC 2018` to stdout. [Answer] # [PHP](http://www.php.net/), 203 bytes ``` <?list(,$a,$y,$m,$d)=$argv;$b=new DateTime($a);$j=$b->format('j');$b->modify("+$y year +$m month");$j==$b->format('j')?:$b->modify('last day of last month');$b->modify("+$d day");echo$b->format('Y-m-d'); ``` To run it: ``` php -n <filename> <date> <y> <m> <d> ``` Example: ``` php -n date_occurrences.php 2018-01-01 5 15 40 ``` Or [Try it online!](https://tio.run/##ZYzRCoIwFIZfZcgBFTfQSIjMvOkRuulytpkTt4mOYi/faXklBf/F@Q//9039hHhqRrW4hAKn4CloCiKtgc@PZwVtbeSLXLiTV6VlAjytYKihZefOzpq7JB7i8ApdW6E6n0QZeOIln0kGmmhrXB@tzC/UHDdUPPLFEcE9sR1Z75X8U4vvJvjkvbdb341pJsIaEXd5cWB5EYIlFiXu87ednLJmQWY@ "PHP – Try It Online") Tests: [Try it online!](https://tio.run/##fZDRTsMgFIavx1OcNCRtMzC0m4la6258BG/M3AVbqe1SoGlR0xhf3UpRY@PEBMiBj/87hLZqx/F6gxDm3eNzDzls0WKrnpqGQJiy5IKyxI6QAHMj2RE/T@zq5cmn4i@@Yv/nv3l6whmjLKXppc8/42sf//FPLbzvt81X1uLl5/YJdq6nDrsMoVJ3gh@q6OtjeQ@uil/Roql7ExHMCR4IlgQXce5Yhve5Ei9wy424q6Ww2TjDxxzv6Y3VSW6i8BjaI7uXuqjLIQqWeIBB8A6WWILUylSBy/wOba5mqbDhvYGCD6BLcLVLnqiL6Y71iUOl5757KmkRxmfBgwoy9DaO77o1tVb9SNUH "PHP – Try It Online") [Answer] # T-SQL, 53 Bytes ``` SELECT DATEADD(D,d,DATEADD(M,m,DATEADD(Y,y,a)))FROM t ``` I'm not sure that it matters, but I'm applying the Year adjustment, followed by the Month adjustment, followed by the Day. All test values check out. [Per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken from a pre-existing table **t** with date field **a** and integer fields **y**, **m**, and **d**. Note interestingly that it isn't the capitalization that matters between the *date type codes* (**D**, **M**, and **Y**) and my *input values* (**d**, **m**, and **y**) its simply the order of parameters [in the SQL `DATEADD` function](https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-2017). ]
[Question] [ For this task your code should take two sorted arrays of integers X and Y as input. It should compute the sum of the absolute distances between each integer in X and its closest number in Y. Examples: ``` X = (1 5,9) Y = (3,4,7) ``` The distance is 2 + 1 + 2. ``` X = (1,2,3) Y = (0,8) ``` The distance is 1 + 2 + 3. Your code can take input in any way that is convenient. The main restriction is that **your code must run in linear time in the sum of the length of the two arrays.**. (You can assume that adding two integers takes constant time.) [Answer] # [Haskell](https://www.haskell.org/), ~~70~~ 64 bytes ``` a%b=abs$a-b x@(a:b)#y@(c:d)|e:_<-d,a%c>a%e=x#d|1>0=a%c+b#y _#_=0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTYxqVglUTeJq8JBI9EqSVO50kEj2SpFsybVKt5GN0UnUTXZLlE11bZCOaXG0M7AFsjXTlKu5IpXjrc1@J@bmJlnW1CUmVeiEm2oY6pjGascbaxjomMe@x8A "Haskell – Try It Online") ## Explanation First we define `(%)` to be the absolute difference between two numbers. Then we define `(#)` to be the interesting function. In the first line we match when both lists are non-empty: ``` x@(a:b)#(c:d:e) ``` On our first case from here we bind `d` to `e:_` with `e:_<-d`. This ensures that `d` is non-empty and sets it's first element to `e`. Then if the second element of \$Y\$ (`e`) is closer than the first (`c`) to the first element of \$X\$ (`a`), we return `x#d` removing the first element of \$Y\$ and calling again with the same \$X\$. If we match the pattern but don't pass the condition we do: ``` a%c+b#y ``` Which, removes the first item of \$X\$ and adds the absolute difference of it from the first element of \$X\$ to the remaining result. Lastly if we don't match the pattern we return \$0\$. Not matching the pattern means that \$X\$ must be empty because \$Y\$ cannot be empty. This algorithm has order notation \$O(|X|+|Y|)\$. # [Haskell](https://www.haskell.org/), 34 bytes Here's how I would do it in \$O(\left|X\right|\times\left|Y\right|)\$ time: ``` x#y=sum[minimum$abs.(z-)<$>y|z<-x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0K50ra4NDc6NzMvM7c0VyUxqVhPo0pX00bFrrKmyka3IvZ/bmJmnm1BUWZeiUq0oY6pjmWscrSxjomOeex/AA "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~124~~ 120 bytes ``` X,Y=input() i=j=s=0 while i<len(X): v=abs(Y[j]-X[i]) if j+1<len(Y)and v>=abs(Y[j+1]-X[i]):j+=1 else:s+=v;i+=1 print s ``` [Try it online!](https://tio.run/##NY4xT8MwEIXn3q84qUNsxUhNS0sxmK2sLAyJqg5pcqgOkWPZTmh/vXFQGe50790nvWdv4TKYdWyGllSWZbEUldLGjoFx0KpTXq3g56J7Qv3ak2Ell4CTqs@eVcfu9FAe9YkD6i/s8uKPqHhtWpze/pm8uFOyy1UBSL0n6XM1vehZW6dNQB9TONyTPt1IEhbB3dJe0JUanPtBOhuyAQ8f7wfnBjd/z47qb4Al0tVSE6jFYQypvkzWNs0OIivEVjxzwTbiUTxxSHotNkmvxJ7HXw "Python 2 – Try It Online") Saved 4 bytes by moving to program versus function. Meeting the time-complexity constraint is possible because both lists are sorted. Note that each time around the loop, either `i` is incremented or `j` is incremented. Thus the loop is executed at most `len(X)+len(Y)` times. [Answer] ## C (gcc), 82 bytes ``` n;f(x,y,a,b)int*x,*y;{for(n=0;a;)--b&&*x*2-*y>y[1]?++y:(++b,--a,n+=abs(*x++-*y));} ``` This takes input as two integer arrays and their lengths (since C has no way to get their length otherwise). This can be shown to run in `O(a+b)` because either `a` or `b` is decremented on each iteration of the loop, which terminates when `a` reaches `0` (and `b` cannot be decremented below `0`). [Try it online!](https://tio.run/##fc7NisIwEMDxu08xCEo@JmASxdXQ9UFcD2ml4sG4qIcMpc/eHbV03cMayOk/80sqc6iqrkuhFhkJI5bymG4qo6LQ1OeLSMUsxCCNKadTlZUzij5pa3cbrWkttC7RmIhJF7G8CpW15gEpQ9ud4jEJCc0I@LAJ2W53UEBjERYIqzYMhfriEeYIy758X7jVYjzZf6UxAn@QN4kvj3l@4hd2A@w4vcJ9mSF8/KvyDrmH6v6o/rm7QrC8b@2r6wf3nt7pzJJ/6PO73nY/) ``` n; // define sum as an integer f(x,y,a,b) // function taking two arrays and two lengths int*x,*y; // use k&r style definitions to shorten function declaration { for(n=0; // initialize sum to 0 a;) // keep looping until x (the first array) runs out // we'll decrement a/b every time we increment x/y respectively --b&& // if y has ≥1 elements left (b>1, but decrements in-place)... *x*2-*y>y[1]? // ... and x - y > [next y] - x, but rearranged for brevity... ++y: // increment y (we already decremented b earlier); (++b, // otherwise, undo the in-place decrement of b from before... --a,n+=abs(*x++-*y)) // decrement a instead, add |x-y| to n, and then increment x ;} ``` Some notes: * Instead of indexing into the arrays, incrementing the pointers and dereferencing directly saves enough bytes for it to be worth it (`*x` vs `x[a]` and `y[1]` vs `y[b+1]`). * The `--b&&` condition checks for `b>1` in a roundabout way - if `b` is `1`, it will evaluate to zero. Since this modifies `b`, we don't need to change it in the first branch of the ternary (which advances `y`), but we do need to change it back in the second (which advances `x`). * No `return` statement is needed, because black magic. (I *think* it's because the last statement to be evaluated will always be the `n+=...` expression, which uses the same register as the one used for return values.) [Answer] # Ruby, 88 bytes ``` ->(p,q){a=q.each_cons(2).map{|a|a.sum/a.size} x=a[0] p.sum{|n|x=a.pop if n>x (n-x).abs}} ``` [Try it online!](https://tio.run/##KypNqvz/X9dOo0CnULM60bZQLzUxOSM@OT@vWMNIUy83saC6JrEmUa@4NFcfSGZWpdZyVdgmRhvEchWABKtr8mqAfL2C/AKFzDSFPLsKLo083QpNvcSk4tra//8B) Also, for fun, a shorter anonymous function that doesn't quite meet the complexity restrictions: ``` ->(a,b){a.map{|x|x-b.min_by{|y|(x-y).abs}}.sum} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes ``` x=>g=(y,i=0,j=0,v=x[i],d=v-y[j],t=d>y[j+1]-v)=>1/v?g(y,i+!t,j+t)+!t*(d>0?d:-d):0 ``` * It run in O(|X|+|Y|): Every recursion run in O(1), and it recursive |X|+|Y| times. + `x`, `y` are passed by reference, which do not copy the content * `1/v` is falsy if `x[i]` is out of range, truthy otherwise * `t` -> `d>y[j+1]-v` -> `v+v>y[j]+y[j+1]` is false as long as following conditions meet. And which means `y[j]` is the number closest to `v` in `y` + `v` is less than `(y[j]+y[j+1])/2`, or + `y[j+1]` is out of range, which would convert to `NaN`, and compare to `NaN` yield `false` - that's why we cannot flip the `>` sign to save 1 more byte * `t` is always a boolean value, and `*` convert it to `0`/`1` before calculating [Try it online!](https://tio.run/##ZcpBDoMgFATQfW/RHZRPC7WmrcnHgxAWRtRAjDSVED09xXUXk5lknu9St/Zf94l8CXbII@YN1YRkB4cCfEnCTTsDFhPftTcQ0aoymDQ8UVTyltrp4OwcwbNIS1@IVaK1Dbe0EbkPyxrm4TqHiYxES6jhbSjRFTzgaSg9/YE7VAcQ8Cp3/gE "JavaScript (Node.js) – Try It Online") [Answer] # Mathematica, 40 bytes ``` x = {1, 5, 9}; y = {3, 4, 7}; Norm[Flatten[Nearest[y] /@ x] - x] ``` If you must create a full program, with inputs: ``` f[x_,y_]:= Norm[Flatten[Nearest[y] /@ x] - x] ``` Here's the timing for up to 1,000,000 points (sampled every 10,000) for `y`: [![enter image description here](https://i.stack.imgur.com/kupq5.png)](https://i.stack.imgur.com/kupq5.png) Close to linear. ]
[Question] [ As a fan of an at most moderately successful footballBE team, towards the end of the season I often wonder whether my favourite team still has any theoretical chance left of becoming champion. Your task in this challenge is to answer that question for me. # Input You will recieve three inputs: the current table, the list of remaining matches, and the current position of the team we are interested in. **Input 1:** The *current table*, a sequence of numbers were the *i*-th number are the points gained by team *i* so far. For example, the input `[93, 86, 78, 76, 75]` encodes the following table (only the last column is of importance): [![premier league table](https://i.stack.imgur.com/k4jQe.png)](https://i.stack.imgur.com/k4jQe.png) --- **Input 2**: The *remaining matches*, a sequence of tuples where each tuple (*i*,*j*) stands for a remaining match between team *i* and *j*. In the above example, a second input of `[(1,2), (4,3), (2,3), (3,2), (1,2)]` would mean that the remaining matches are: ``` Chelsea vs Tottenham, Liverpool vs Man. City, Tottenham vs Man. City, Man. City vs Tottenham, Chelsea vs Tottenham ``` --- **Input 3:** The *current position* of the team we are interested in. For example, an input of `2` for the above example would mean that we'd like to know whether Tottenham can still become champion. # Output For each remaining match of the form (*i*,*j*), there are three possible outcomes: * Team *i* wins: Team *i* gets **3 points**, team *j* gets **0 points** * Team *j* wins: Team *i* gets **0 points**, team *j* gets **3 points** * Draw: Team *i* and *j* both get **1 point** You must output a truthy value if there is some outcome for all remaining games such that at the end, no other team has more points than the team specified in the 3rd input. Otherwise, output a falsy value. **Example**: Consider the exemplary input from the above section: Input 1 = `[93, 86, 78, 76, 75]`, Input 2 = `[(1,2), (4,3), (2,3), (3,2), (1,2)]`, Input 3 = `2` If team `2` wins all its remaining matches (i.e. `(1,2), (2,3), (3,2), (1,2)`), it gets 4\*3 = 12 additional points; none of the other teams gets any points from these matches. Let's say the other remaining match (i.e. `(4,3)`) is a draw. Then the final scores would be: ``` Team 1: 93, Team 2: 86 + 12 = 98, Team 3: 78 + 1 = 79, Team 4: 76 + 1 = 77, Team 5: 75 ``` This means that we have already found some outcome for the remaining matches such that no other team has more points than team `2`, so the output for this input must be truthy. # Details * You may assume the first input to be an ordered sequence, i.e. for *i* < *j*, the *i*-th entry is equal to or greater than the *j*-th entry. The first input may be taken as a list, a string or the like. * You may take the second input as a string, a list of tuples or the like. Alternatively, you may take it as a two-dimensional array `a` where `a[i][j]` is the number of entries of the form `(i,j)` in the list of remaining matches. For example, `a[1][2] = 2, a[2][3] = 1, a[3][2] = 1, a[4][3] = 1` corresponds to `[(1,2), (4,3), (2,3), (3,2), (1,2)]`. * For the second and third input, you may assume 0-indexing instead of 1-indexing. * You may take the three inputs in any order. Please specify the exact input format you chose in your answer. **Side node**: The problem underlying this challenge was shown to be NP-complete in "[Football Elimination is Hard to Decide Under the 3-Point-Rule](http://dl.acm.org/citation.cfm?id=756600)". Interestingly, if only two points are awarded for a win, the problem becomes solvable in polynomial time. # Test Cases All test cases are in the format `Input1`, `Input2`, `Input3`. **Truthy:** * `[93, 86, 78, 76, 75]`, `[(1,2), (4,3), (2,3), (3,2), (1,2)]`, `2` * `[50]`, `[]`, `1` * `[10, 10, 10]`, `[]`, `3` * `[15, 10, 8]`, `[(2,3), (1,3), (1,3), (3,1), (2,1)]`, `2` **Falsy:** * `[10, 9, 8]`, `[]`, `2` * `[10, 9, 9]`, `[(2,3), (3,2)]`, `1` * `[21, 12, 11]`, `[(2,1), (1,2), (2,3), (1,3), (1,3), (3,1), (3,1)]`, `2` # Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted. [Answer] # [Haskell (Lambdabot)](https://www.haskell.org/), 84 bytes Thanks to @bartavelle for saving me a byte. Without Lambdabot, add 20 bytes for `import Control.Lens` plus a newline. The function takes its arguments in the same order as described in the OP, 0-indexed. Its second argument (the list of remaining matchups) is a flat list of indexes (e.g. `[1,2,4,1]` corresponds to `[(Team 1 vs Team 2), (Team 4 vs Team 1)]`). The rules are a little vague as to whether or not this is allowed. If it isn't allowed, the function can take input in the format provided by the examples – a list of tuples. In that case, add 2 bytes to this solution's score, due to replacing `a:b:r` with `(a,b):r`. ``` (!)=(+~).element (t?(a:b:r))s=any(t?r)[a!3$s,b!3$s,b!1$a!1$s] (t?_)s=s!!t==maximum s ``` ### Explanation: The first line defines an infix function `!` of three variables, of type `(!) :: Int -> Int -> [Int] -> [Int]`, which increments the value at a given index in a list. Since, oftentimes, code is easier to understand than words (and since Haskell syntax can be weird), here's a Python translation: ``` def add(index, amount, items): items[index] += amount return items ``` The second line defines another infix function `?`, also of three variables (the challenge input). I'll rewrite it more readably here: ``` (t ? a:b:r) s = any (t ? r) [a ! 3 $ s, b ! 3 $ s, (b ! 1 $ a) ! 1 $ s] (t ? _) s = (s !! t) == maximum s ``` This is a recursive implementation of exhaustive search. It recurs over the list of remaining games, branching on the three possible outcomes, and then, once the list is empty, checking whether or not our team has the maximum number of points. Again in (non-idiomatic) Python, this is: ``` def can_still_win(standings, games_left, our_team): if games_left == []: return standings[our_team] == max(standings) team1, team2, other_games = games_left[0], games_left[1], games_left[2:] team1Wins, team2Wins, tie = standings.copy(), standings.copy(), standings.copy() team1Wins[team1] += 3 team2Wins[team2] += 3 tie[team1] += 1 tie[team2] += 1 return (can_still_win(team1Wins, other_games, our_team) or can_still_win(team2Wins, other_games, our_team) or can_still_win(tie, other_games, our_team)) ``` [Try it online!](https://tio.run/##PU3LCsIwELznKzbQQ4KlmHoTggevPXorRVaMGmxSyaagF389rvhgmN1ZZpi9IF3dOBYfblPKsJ1iTtPYdC5SUVJbtXjqxo0uuJiFyhuF68M6aU0W44PvpHuUq4rqw3eaCpk0vMN7jpGU2dqAdx/mAFQoYzz6eCaw0LemBtMyzSDOGBx17pTfhqmXDMNoeX/4VYOY5rRzGDhnhAjoI6tb8jFDBepnbuBfqOH/tLwA "Haskell – Try It Online") \*Sadly, TiO doesn't support Lens, so this link won't actually run. [Answer] # Microsoft SQL Server, 792 bytes ``` CREATE FUNCTION my.f(@s XML,@m XML,@ INT)RETURNS TABLE RETURN WITH s AS(SELECT s.value('@p','INT')p FROM @s.nodes('S')s(s)), m AS(SELECT m.value('@i','INT')i,m.value('@j','INT')j FROM @m.nodes('M')m(m)), a AS(SELECT ROW_NUMBER()OVER(ORDER BY-p)t,p FROM s), b AS(SELECT p+3*(SELECT COUNT(*)FROM m WHERE t IN(i,j))o FROM a WHERE t=@), c AS(SELECT i,j,ROW_NUMBER()OVER(ORDER BY 1/0)k FROM m WHERE @ NOT IN(i,j)), d AS(SELECT COUNT(*)u,POWER(3,COUNT(*))-1 v FROM c UNION ALL SELECT u,v-1 FROM d WHERE v>0), e AS(SELECT v,u,v/3 q,v%3 r FROM d UNION ALL SELECT v,u-1,q/3,q%3 FROM e WHERE u>1), f AS(SELECT v,p+SUM(IIF(t=i,r,(2-r))%3*3/2)s FROM a,c,e WHERE t IN(i,j)AND k=u GROUP BY v,t,p), g AS(SELECT MAX(s)x FROM f GROUP BY v)SELECT SUM(IIF(o<ISNULL(x,p),0,1))f FROM a,(b OUTER APPLY g)WHERE t=1; ``` The function returns 0 for a false outcome and more than 0 for a truthy one. The whole snippet: ``` SET NOCOUNT ON; --USE tempdb; USE rextester; GO IF SCHEMA_ID('my') IS NULL EXEC('CREATE SCHEMA my'); ELSE BEGIN IF OBJECT_ID('my.f', 'IF') IS NOT NULL DROP FUNCTION my.f; IF OBJECT_ID('my.s', 'U') IS NOT NULL DROP TABLE my.s; IF OBJECT_ID('my.m', 'U') IS NOT NULL DROP TABLE my.m; IF OBJECT_ID('my.c', 'U') IS NOT NULL DROP TABLE my.c; END; GO CREATE TABLE my.c( -- Test cases c INT PRIMARY KEY CLUSTERED CHECK(c > 0), -- Test Case Id n INT CHECK(n > 0), -- Current position of the team of interest ); CREATE TABLE my.s( -- Standings a INT FOREIGN KEY REFERENCES my.c(c) CHECK(a > 0), -- Test cAse Id p INT CHECK(p > 0) -- Team pts ); CREATE TABLE my.m( -- Matches s INT FOREIGN KEY REFERENCES my.c(c) CHECK(s > 0), -- Test caSe Id i INT CHECK(i > 0), -- Team i j INT CHECK(j > 0), -- Team j CHECK(i != j) ); GO INSERT my.c(c, n) VALUES (1, 2), (2, 1), (3, 3), (4, 2), (5, 2), (6, 1), (7, 2); INSERT my.s(a, p) VALUES (1, 93), (1, 86), (1, 78), (1, 76), (1, 75), (2, 50), (3, 10), (3, 10), (3, 10), (4, 15), (4, 10), (4, 8), (5, 10), (5, 9), (5, 8), (6, 10), (6, 9), (6, 9), (7, 21), (7, 12), (7, 11); INSERT my.m(s, i, j) VALUES (1, 1, 2), (1, 4, 3), (1, 2, 3), (1, 3, 2), (1, 1, 2), (4, 2, 3), (4, 1, 3), (4, 1, 3),(4, 3, 1), (4, 2, 1), (6, 2, 3), (6, 3, 2), (7, 2, 1), (7, 1, 2), (7, 2, 3), (7, 1, 3), (7, 1, 3), (7, 3, 1), (7, 3, 1); GO CREATE FUNCTION my.f(@s XML,@m XML,@ INT)RETURNS TABLE RETURN WITH s AS(SELECT s.value('@p','INT')p FROM @s.nodes('S')s(s)), m AS(SELECT m.value('@i','INT')i,m.value('@j','INT')j FROM @m.nodes('M')m(m)), a AS(SELECT ROW_NUMBER()OVER(ORDER BY-p)t,p FROM s), b AS(SELECT p+3*(SELECT COUNT(*)FROM m WHERE t IN(i,j))o FROM a WHERE t=@), c AS(SELECT i,j,ROW_NUMBER()OVER(ORDER BY 1/0)k FROM m WHERE @ NOT IN(i,j)), d AS(SELECT COUNT(*)u,POWER(3,COUNT(*))-1 v FROM c UNION ALL SELECT u,v-1 FROM d WHERE v>0), e AS(SELECT v,u,v/3 q,v%3 r FROM d UNION ALL SELECT v,u-1,q/3,q%3 FROM e WHERE u>1), f AS(SELECT v,p+SUM(IIF(t=i,r,(2-r))%3*3/2)s FROM a,c,e WHERE t IN(i,j)AND k=u GROUP BY v,t,p), g AS(SELECT MAX(s)x FROM f GROUP BY v)SELECT SUM(IIF(o<ISNULL(x,p),0,1))f FROM a,(b OUTER APPLY g)WHERE t=1; GO SELECT c, f FROM my.c OUTER APPLY(SELECT p FROM my.s S WHERE a = c FOR XML AUTO)S(s) OUTER APPLY(SELECT i, j FROM my.m M WHERE s = c FOR XML AUTO)M(m) OUTER APPLY my.f(s, m, n) ORDER BY c OPTION(MAXRECURSION 0); ``` [Check It Online!](http://rextester.com/LPCUO95674) [Answer] # Python 2, ~~242~~ 221 bytes ``` from itertools import* def u(S,M,t,O): for m,o in zip(M,O): if t in m:S[t]+=3 else:S[m[0]]+=(1,3,0)[o];S[m[1]]+=(1,0,3)[o] return S[t]>=max(S) f=lambda s,m,t:any(u(s[:],m,t,O)for O in product([0,1,2],repeat=len(m))) ``` [Try it online!](https://tio.run/##bVDBbsIwDL33KyztQLIZqWnGBkzsyA1x4Fj1kEEqKjVNlbjS2M@zpC2jm3awHD87fu@5vdDZNtn1WjproCLtyNraQ2Va6@gxOekSOnbAHRLu@TqB0jowaKFq4Ktq2W5AoSqBImbWh5yKp40MmK69DqXJ0yIgTKDElOe2eIuYGLEUZcQScJo610D8/r4x6pMdeFJuamU@Tgo8GqS1ai6sYz5fF7EMzFHMPtK2zp66I7E8RYFZgU63WtGm1g0znPNrtLFlnpSjw9E67RGMouM5PshWvQW4SSh/D@aMxFyEuWwueO@fBFLWux12FP2S0E2SByDt6ai89knrqoZgRq6j82U2lluWryTC8gXhdRki5kURWYJwjsCew0FCyoYkBzD2wlDG71sWafwVQkxAkYa6j7Epp83F0Fz2dCOB@JUkioFcTOluTkpV@6mRuGw17vujbmytplRyMDHVm4W7iiyEGAfFze39BP8qlD8Kr98 "Python 2 – Try It Online") After a first pass with basic golf-thinking. Takes input with **0-based indexing**; test cases in TIO adjust for this via the function `F`. The `product([0,1,2],repeat=len(m))` iteration evaluates the possible outcomes over tie/win/loss for each match unless the team-of-interest (TOI) is a part of the match (in which, the TOI is always assumed to win). [Answer] # JavaScript (ES6), 145 bytes ``` (s,d,t,o=[],g=(c=s,i=0)=>d[i]?[3,,0,3,1,1].map((a,j)=>(j%=2,r=j?r:[...c],r[d[i][j]]+=a,g(r,i+1))):o.push(c))=>o.some(r=>r[t]==Math.max(...r),g()) ``` Takes score input as an array (`[93,86,78,76,75]`), upcoming games as an array of 2-value arrays (`[[0,1],[3,2],[1,2],[2,1],[0,1]]`), and team index as an integer (`1`). Everything is 0-indexed. ## Test Snippet ``` let f= (s,d,t,o=[],g=(c=s,i=0)=>d[i]?[3,,0,3,1,1].map((a,j)=>(j%=2,r=j?r:[...c],r[d[i][j]]+=a,g(r,i+1))):o.push(c))=>o.some(r=>r[t]==Math.max(...r),g()) console.log("---Truthy---") console.log(f([93, 86, 78, 76, 75], [[0,1], [3,2], [1,2], [2,1], [0,1]], 1)) console.log(f([50], [], 0)) console.log(f([10, 10, 10], [], 2)) console.log(f([15, 10, 8], [[1,2], [0,2], [0,2], [2,0], [1,0]], 1)) console.log("---Falsy---") console.log(f([10, 9, 8], [], 1)) console.log(f([10, 9, 9], [[1,2],[2,1]], 0)) console.log(f([21, 12, 11], [[1,0], [0,1], [1,2], [0,2], [0,2], [2,0], [2,0]], 1)) ``` ``` .as-console-wrapper{max-height:100%!important} ``` ]
[Question] [ ## Introduction ### Rules of the puzzle: The puzzle Binary (also known as [Takuzu](https://en.wikipedia.org/wiki/Takuzu) or Subiku) is very simple to understand, and has only a few rules: Since the name of the game is binary it's pretty obvious, but you can only fill in zeros and ones. 1. No more than two of the same digit can be vertically or horizontally adjacent to each other 2. Each row and each column must contain an equal amount of zeros and ones (this implicitly means every binary game will always have even dimensions). 3. There may be no duplicated rows and no duplicated columns (with the exact same order of zeros and ones). You can play the game at [www.binarypuzzle.com](http://www.binarypuzzle.com/) if you want to. ### Tactics: Due to rule 1, we can always fill in a digit if: - There are already two of the same digit vertically or horizontally adjacent to each other, in which case we can fill in the opposite digit at both sides. I.e. `.11...` → `0110..`. - There are two of the same digit vertically or horizontally with only one gap in between them. I.e. `.1.1..` → `.101..` Due to rule 1, when three gaps are left and we cannot have three adjacent of the same digit, we can fill in one of the gaps. I.e. `.0.1.0` → `10.1.0` (We still have to fill in two ones, and we cannot have three adjacent ones in the middle, so the first gap has to be a `1`.) Due to rule 2, we can always fill in the remaining gaps in a row or column if halve of them is already filled in with the opposite digit. I.e. `.1.011` → `010011` Due to rule 3, we can always fill in the opposite digits if only two are left to solve on an equally ordered line. I.e. `101100 & 1..100` → `101100 & 110100` Due to rule 3, we can sometimes fill in a gap when three gaps are left on an equally ordered line. I.e. `010011 & .1.01.` → `010011 & .1.010` (Here we cannot fill in a `1` at the end, because that would mean we have to fill in zeros at the other two gaps, making both lines equal in order.) ### Example: We start with the following 6x6 grid with some ones and zeros filled in (and the dots are gaps we have yet to fill in): ``` .1.... .10.0. 1.11.. .1.... ...1.0 ...... ``` Due to rules 1 & 2 we can fill in these digits: ``` .1.01. .1010. 101100 010011 .0.1.0 .010.. ``` Due to rule 1 we can fill in a 1 at row 5, column 1: ``` .1.01. .1010. 101100 010011 10.1.0 .010.. ``` Due to rule 3 we can fill in a 0 at row 1, column 6 (when looking at row 4): ``` .1.010 .1010. 101100 010011 10.1.0 .010.. ``` Now we can continue to fill gaps with digits due to rules 1 & 2: ``` .1.010 010101 101100 010011 10.1.0 .010.1 ``` Now we can finish row 5 due to rule 3 (when looking at row 3): ``` .1.010 010101 101100 010011 100110 .010.1 ``` And then we can finish the puzzle due to rules 1 & 2: ``` 011010 010101 101100 010011 100110 101001 ``` ## Challenge: The challenge is simply: given the starting grid, output the solved puzzle. NOTE: You don't have to implement the rules above. You of course can, and it should give you hints on how to implement this challenge, but bruteforcing the solution with the rules in mind is completely fine. How you solve it is up to you, but the challenge is to output the solved puzzle. ### Challenge rules: * Input and output format for the grid is flexible, but please state what you use. (I.e. 2D byte-array; String with newlines; etc.) * This above also applies to the characters used. In the example I've used `01.`, but if you want you can use `ABx` instead. Please state what input/output format and characters you've used. * You can assume only the following grid sizes will be used: `6x6`; `8x8`; `10x10`; `12x12`; `14x14`; `16x16`. ### 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: The dots are only added for readability, feel free to use spaces or anything else you prefer for gaps instead. Both in and output format is flexible. ``` Input: 1..0.. ..00.1 .00..1 ...... 00.1.. .1..00 Output: 101010 010011 100101 011010 001101 110100 Input: .1.... .10.0. 1.11.. .1.... ...1.0 ...... Output: 011010 010101 101100 010011 100110 101001 Input: .......1.. .00..0..1. .0..1..0.0 ..1...1... 1.1......1 .......1.. .0..1...0. ....11...0 .0.0..1..0 0...0...1. Output: 0110010101 1001100110 1001101010 0110011001 1010100101 0101010110 1001101001 0110110100 1010011010 0101001011 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 34 bytes ``` {ℕ<2}ᵐ²&≜{d?ọᵐctᵐ=&{ḅlᵐ⌉<3}ᵐ}&\↰₂& ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/9qGWqjVHtw60TDm1Se9Q5pzrF/uHuXiA3uQRI2KpVP9zRmgNkPerptDEGKatVi3nUtuFRU5Pa///R0YY6jjqGOk6xOtEGOs46LjqGQJarjpuOu44HkGWoY6DjqeMVG/s/CgA "Brachylog – TIO Nexus") This is pretty damn slow, so the test case on TIO is 4x4. I am currently running the 6x6 test case on my computer to see how much time it takes. This takes a list of lists as input. The unknown values should be indicated with variables, that is with all-uppercase strings (and they should all be different, as otherwise you would be indicating that some cells must have the same value) ### Explanation We constrain the values to be in `{0,1}`, then we try instantiations of the variables until one respects all 3 rules. This is why this is so slow (because it will try all of them until finding one; and because in that case Brachylog is not implemented well enough so that constraints can be imposed before trying a possible matrix). ``` & Output = Input { }ᵐ² Map two levels on the Input (i.e. each cell): ℕ<2 The cell is either 0 or 1 &≜ Assign values to all cells { } Define predicate 2: d? The Input with no duplicates is still the Input (i.e. all rows are different) ?ọᵐctᵐ= All occurences of 1s and 0s for each rows are equal &{ }ᵐ Map on rows: ḅlᵐ Get the lengths of runs of equal values ⌉<3 The largest one is strictly less than 3 &\↰₂ Apply predicate 2 on the transpose of the Input (i.e. do the same checks but on columns) ``` [Answer] ## JavaScript (ES6), ~~274~~ 270 bytes Takes input as a 2D array, where empty cells are marked with `2`. Prints all possible solutions to the console. ``` f=(a,x=0,y=0,w=a.length,p,R=a[y])=>(M=z=>!a.some((r,y)=>/(0|1),\1,\1/.exec(s=r.map((v,x)=>(v=z?v:a[x][y],b-=v&1,c-=!v,m|=v&2,v),b=c=w/2))||b*c<0|o[b*c||s]&(o[s]=1),o={}))(m=0)&M(1)&&(m?R&&[0,1].map(n=>(p=R[x])==n|p>1&&(R[x]=n,f(a,z=(x+1)%w,y+!z),R[x]=p)):console.log(a)) ``` ### How it works The first part of the code uses the `M()` function to check the validity of the current board, both horizontally and vertically. ``` M = z => !a.some((r, y) => /(0|1),\1,\1/.exec( s = r.map((v, x) => ( v = z ? v : a[x][y], b -= v & 1, c -= !v, m |= v & 2, v ), b = c = w / 2 ) ) || b * c < 0 | o[b * c || s] & (o[s] = 1), o = {} ) ``` It maps a full row or column to the string ***s***. This is actually an array coerced to a string, so it looks like `"1,2,2,0,2,2"`. It uses: * The regular expression `/(0|1),\1,\1/` to detect 3 or more consecutive identical digits. * The counters ***b*** and ***c*** to keep track of the number of *ones* and *zeros*. Both counters are initialized to ***w / 2*** and decremented each time a *one* or a *zero* (respectively) is encountered. This leads to either: + ***b = c = 0*** → ***b \* c = 0*** → the line is complete and correct (as many *zeros* as *ones*) + ***b > 0 AND c > 0*** → ***b \* c > 0*** → the line is not complete but correct so far (we don't have more than ***w / 2*** *zeros* or more than ***w / 2*** *ones*) + ***b < 0 OR c < 0*** → ***b \* c < 0*** → the line is invalid * The flag ***m*** (for 'missing') which is non-zero if there's at least one remaining *two* on the board. * The object ***o*** to keep track of all line patterns encountered so far. If the board is invalid, we stop immediately. If the board is valid and complete, we print it to the console. Otherwise, the second part of the code attempts to replace each *2* with either a *zero* or a *one* with recursive calls: ``` [0, 1].map(n => (p = a[y][x]) == n | p > 1 && ( a[y][x] = n, f(a, z = (x + 1) % w, y + !z), a[y][x] = p ) ) ``` ### Demo ``` f=(a,x=0,y=0,w=a.length,p,R=a[y])=>(M=z=>!a.some((r,y)=>/(0|1),\1,\1/.exec(s=r.map((v,x)=>(v=z?v:a[x][y],b-=v&1,c-=!v,m|=v&2,v),b=c=w/2))||b*c<0|o[b*c||s]&(o[s]=1),o={}))(m=0)&M(1)&&(m?R&&[0,1].map(n=>(p=R[x])==n|p>1&&(R[x]=n,f(a,z=(x+1)%w,y+!z),R[x]=p)):console.log(a)) console.log('Example #1') f([ [1,2,2,0,2,2], [2,2,0,0,2,1], [2,0,0,2,2,1], [2,2,2,2,2,2], [0,0,2,1,2,2], [2,1,2,2,0,0] ]) console.log('Example #2') f([ [2,2,2,2,2,2,2,1,2,2], [2,0,0,2,2,0,2,2,1,2], [2,0,2,2,1,2,2,0,2,0], [2,2,1,2,2,2,1,2,2,2], [1,2,1,2,2,2,2,2,2,1], [2,2,2,2,2,2,2,1,2,2], [2,0,2,2,1,2,2,2,0,2], [2,2,2,2,1,1,2,2,2,0], [2,0,2,0,2,2,1,2,2,0], [0,2,2,2,0,2,2,2,1,2] ]) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~53~~ 51 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṡ€3ḄFf0,7L SḤnLṀȯÇ ⁻QȯÇ Fṣ©2L’0,1ṗż@€®F€s€LÇÐḟZÇ$Ðḟ ``` Takes a list of lists representing the grid, containing `0`, `1`, and `2` (the spaces). Returns a list of lists of lists, each list of lists is in the same format (although with no `2`s) and represents a possible solution to the input. **[Try it online!](https://tio.run/nexus/jelly#@/9w58JHTWuMH@5ocUsz0DH34Qp@uGNJns/DnQ0n1h9u53rUuDsQzHB7uHPxoZVGPo8aZhroGD7cOf3oHgegxkPr3IBkMRD7HG4/POHhjvlRh9tVwIz/h9sj3f//j4421DECQgMQjtXhUogGs8B8QzDfEMqD8Y10YBCmHmijjiGSekOoeoPYWAA)** (this wont run any of the question's test cases due to memory limitations - all 2nSpaces grids are created as a list of list of lists of integers - but I've put a relatively hefty case there with a single solution). The footer separates out and formats the grids. Pure brute force method - implements the rules and checks them for each grid that could be formed by replacing any of the `2`s with `1`s or `0`s. ``` ṡ€3ḄFf0,7L - Link 1, # of runs of 3 1s or 3 0s by row: list of lists ṡ€3 - all contiguous slices of length 3 for €ach list Ḅ - convert all results from binary F - flatten into one list f - filter keep values in: 0,7 - 0 paired with 7: [0,7] L - length SḤnLṀȯÇ - Link 2, unequal counts of 1s and 0s by column ...or link 1: list of lists S - sum (vectorises, hence "by column", counts 1s since only 1s or 0s appear) Ḥ - double L - length (number of rows - OK since square) n - not equal? (vectorises) Ṁ - maximum (1 if any not equal) ȯÇ - ... or last link (1) as a monad ⁻QȯÇ - Link 3, rows are unique ...or link 2: list of lists Q - unique ⁻ - not equal? ȯÇ - ... or last link (2) as a monad Fṣ©2L’0,1ṗż@€®F€s€LÇÐḟZÇ$Ðḟ - Main link: list of lists F - flatten ṣ©2 - split at 2s and copy the result to the register L - length (# of such slices) ’ - decrement (# of 2s) 0,1 - 0 paired with 1 ṗ - Cartesian power (all binary lists of length # of 2s) ® - recall value from register (the flat version split at 2s) ż@€ - zip (reversed @rguments) for €ach (1s & 0s where 2s were) F€ - flatten €ach s€L - split €ach into chunks of length length(input) (into rows) Ðḟ - filter discard if: Ç - call last link(3) as a monad Ðḟ - filter discard if: $ - last two links as a monad: Z - transpose Ç - call last link(3) as a monad ``` ]
[Question] [ # Background Many esoteric programming languages don't have numbers built in at literals, so you have to calculate them at runtime; and in many of these cases, the number representation can be quite interesting. We've already had [a challenge](https://codegolf.stackexchange.com/q/26207/62131) about representing numbers for Underload. This challenge is about representing numbers in [Modular SNUSP](http://esolangs.org/wiki/Modular_SNUSP). (Note that you don't need to learn SNUSP in order to complete this challenge – all the information you need is in the specification – but you might find the background interesting.) # The task For the purpose of this challenge, a Modular SNUSP number is a string formed out of the characters `@`, `+`, and `=`, except that the last character is a `#`, and that the penultimate character must be `+` or `=` (it cannot be `@`). For example, valid numbers include `@+#`, `==#`, and `@@+@=#`; examples of invalid numbers include `+=`, `@@#`, and `+?+#`. The value of a Modular SNUSP number is calculated recursively as follows: * `#` has a value of 0 (this is the base case). * If the number has the form `=x`, for any string `x`, its value is equal to the value of `x`. * If the number has the form `+x`, for any string `x`, its value is equal to the value of `x`, plus 1. * If the number has the form `@cx`, for any single character `c` and any string `x`, its value is equal to the value of `x`, plus the value of `cx`. For this challenge, you must write a program that takes a nonnegative integer as input, and outputs a string that's the shortest possible Modular SNUSP number that has a value equal to the input. # Clarifications * It's entirely possible that there will be more than one string with the same value, and in particular, for some integers there will be a tie for the shortest Modular SNUSP number with that value. In such a case, you may output any of the numbers involved wit the tie. * There's no restriction on the algorithm you use to find the number; for example, brute-forcing strings and evaluating them is a legal tactic, but so is doing something cleverer to reduce the search space. * As usual on PPCG, your submission may be either a full program or a function (pick whichever is more concise in your language). * This isn't a problem about handling input and output formats, so you can use any reasonable means to input a nonnegative integer and output a string. There's [a full guide on meta](http://meta.codegolf.stackexchange.com/q/2447/62131), but the most commonly used legal methods include function arguments/returns, command line arguments, and standard input/standard output. # Test cases Here are the shortest representations of the first few numbers: * **0**: `#` * **1**: `+#` * **2**: `++#` * **3**: `+++#` or `@++#` * **4**: `++++#` or `+@++#` or `@=++#` * **5**: `@+++#` or `@@++#` * **6**: `+@+++#` or `+@@++#` or `@=+++#` or `@=@++#` or `@@=++#` * **7**: `@++++#` or `@+@++#` * **8**: `@@+++#` or `@@@++#` * **9**: `+@@+++#` or `+@@@++#` or `@+++++#` or `@++@++#` or `@+@=++#` or `@@=+++#` or `@@=@++#` * **10**: `@=@+++#` or `@=@@++#` or `@@@=++#` (**this is a fairly important test case to check**, as all the possible answers include `=`) * **11**: `@+@+++#` or `@+@@++#` or `@@++++#` or `@@+@++#` * **12**: `+@+@+++#` or `+@+@@++#` or `+@@++++#` or `+@@+@++#` or `@=+@+++#` or `@=+@@++#` or `@=@=+++#` or `@=@=@++#` or `@=@@=++#` or `@@=++++#` or `@@=+@++#` or `@@=@=++#` * **13**: `@@@+++#` or `@@@@++#` * **14**: `+@@@+++#` or `+@@@@++#` or `@=@++++#` or `@=@+@++#` or `@@+++++#` or `@@++@++#` or `@@+@=++#` * **15**: `@+@++++#` or `@+@+@++#` or `@@=@+++#` or `@@=@@++#` or `@@@=+++#` or `@@@=@++#` As a larger test case, the output from input **40** should be `@@@=@@+++#`, `@@@=@@@++#`, `@@@@=@+++#`, or `@@@@=@@++#`. # Victory condition As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the winner is the shortest entry, measured in bytes. [Answer] # Oracle SQL 11.2, ~~341~~ 262 bytes ``` WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c,i)AS(SELECT'#',0,0,e,1 FROM e UNION ALL SELECT c||s,DECODE(c,'+',1,'@',p,0)+v,v,e,i+1 FROM n,e WHERE i<11)CYCLE s SET y TO 1 DEFAULT 0 SELECT s FROM n WHERE:1=v AND rownum=1; ``` Old version ``` WITH e AS(SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4),n(s,v,p,c) AS(SELECT'#',0,0,e FROM e UNION ALL SELECT s||c,CASE c WHEN'+'THEN 1 WHEN'='THEN 0 WHEN'@'THEN p ELSE 0 END+v,v,e FROM n,e WHERE LENGTH(s)<10)CYCLE s SET y TO 1 DEFAULT 0 SELECT MIN(REVERSE(s))KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s))FROM n WHERE v=:1; ``` :1 the number to represent in Modular SNUSP Un-golfed : ``` WITH e AS (SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4), n(s,v,p,c,i) AS ( SELECT '#',0,0,e,1 FROM e UNION ALL SELECT s||c , DECODE(c,'+',1,'@',p,0)+v , v , e , i+1 FROM n,e WHERE i<11 ) CYCLE s SET y TO 1 DEFAULT 0 SELECT s FROM n WHERE:1=v AND rownum=1; ``` First create a view with 3 lines, one for each symbol used to represent numbers, minus # which is only used at the end of the string : ``` SELECT DECODE(LEVEL,1,'=',2,'@','+')e FROM DUAL CONNECT BY LEVEL<4; ``` Then the recursive view n generates every string possible with those 3 symbols, concatenates them to # and evaluates them. The parameters are : s : the Modular SNUSP representation of the number being evaluated v : the decimal value of s computed by the previous iteration p : v computed by the i-2 iteration c : the next symbol to concatenate to s i : the length of s, only needed to get rid of two LENGTH() for golfing purpose ``` DECODE(c,'+',1,'@',p,0)+v ``` If the last symbol is + then add 1 If it is @ add the value of the i-2 iteration Else the symbol is either # or =. v is initialised with 0 in the init part of the recursive view, so the new v is equal to the previous v in either case. ``` WHERE i<11 ``` Every string possible with the 3 symbols is computed, this part insure that the request does not run until the big crunch. ``` CYCLE s SET y TO 1 DEFAULT 0 ``` Since there is no rule to the construction of the strings, duplicates are bound to arise. Being in a recursive view Oracle interprets those duplicates as cycles and throw an error if the case is not explicitly taken care of. ``` SELECT s FROM n WHERE:1=v AND rownum=1; ``` Returns the first Modular SNUSP representation that evaluate to the decimal number entered as parameter :1 In my tests that first line is always one of the shortest representations. In the case your database would not act in the same way, then that last clause should be replaced with ``` SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY i)FROM n WHERE:1=v ``` [Answer] ## JavaScript (ES6), 100 bytes ``` n=>eval("for(a=[['#',0,0]];[[s,t,p],...a]=a,t-n;)a.push(['='+s,t,t],['+'+s,t+1,t],['@'+s,t+p,t]);s") ``` Simple brute-force breadth-first search algorithm. [Answer] # Pyth, 41 bytes ``` L?b+ytb@[yttb001)Chb0+hfqQyTs^L"+@="UhQ\# ``` [Test suite](https://pyth.herokuapp.com/?code=L%3Fb%2Bytb%40%5Byttb001%29Chb0%2BhfqQyTs%5EL%22%2B%40%3D%22UhQ%5C%23&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) How it works: There are two parts. A recursive function which calculates the value of a SNUSP expression without the trailing `#`, and a brute force routine. Evalutaion: ``` L?b+ytb@[yttb001)Chb0 L Define the function y(b) as follows ?b If b is nonempty +ytb The sum of y(tail(b)) and # tail(b) = b[1:] @[ ) The element in the list at location Chb Character values of the first character. Modular indexing means that + -> 3 @ -> 0 = -> 1 Index 2 is filler. [yttb001) @ adds y(tail(tail(b)). Tail suppresses the error when called on an empty list, so this treats @# as zero, but this can't lead to problems because removing the @ will always make the expression shorter. + adds 1, = adds 0. 0 If b is the empty string, return 0 ``` Brute force: ``` +hfqQyTs^L"+@="UhQ\# UhQ 0 ... Q # Q is the input ^L"+@=" Map that list to all strings formed from the characters "+@=", with that many characters. s Concatenate fqQyT Filter for strings which evaluate to the input h Take the first success, which is the shortest due to the order the strings were generated. + \# Add a '#' and output ``` [Answer] # CJam, 58 ``` ri:M;'#0_]]{_{M&}#_)!}{;{~[2,+1$f+"@=+"\]z\f+\af.+~}%}w=0= ``` Brute force, with a little inspiration from Neil's answer. [Try it online](http://cjam.aditsu.net/#code=ri%3AM%3B'%230_%5D%5D%7B_%7BM%26%7D%23_)!%7D%7B%3B%7B~%5B2%2C%2B1%24f%2B%22%40%3D%2B%22%5C%5Dz%5Cf%2B%5Caf.%2B~%7D%25%7Dw%3D0%3D&input=40) **Efficient version, 107** ``` ri0"#"a{_{:B\:A={'=A0j+}{A(B={'+B0j+}{AB>{BAB-j_N={'@\+}|}N?}?}?}{;_(0j'+\+a\,1>_W%.{j}Na-'@\f++{,}$0=}?}2j ``` [Try it online](http://cjam.aditsu.net/#code=ri0%22%23%22a%7B_%7B%3AB%5C%3AA%3D%7B'%3DA0j%2B%7D%7BA(B%3D%7B'%2BB0j%2B%7D%7BAB%3E%7BBAB-j_N%3D%7B'%40%5C%2B%7D%7C%7DN%3F%7D%3F%7D%3F%7D%7B%3B_(0j'%2B%5C%2Ba%5C%2C1%3E_W%25.%7Bj%7DNa-'%40%5Cf%2B%2B%7B%2C%7D%240%3D%7D%3F%7D2j&input=300) This uses dynamic programming. [Answer] # [Haskell](https://www.haskell.org/), ~~89~~ 86 bytes EDIT: * -3 bytes: zipping was shorter than indexing. Another brute force solution which ended up with a lot of inspiration from Neil's answer. (Although it worked more like isaacg's Pyth before golfing introduced the `l`.) ``` f n=[s|(a,_,s)<-l,a==n]!!0 l=(0,0,"#"):[(a+c,a,d:s)|(a,b,s)<-l,(c,d)<-zip[0,1,b]"=+@"] ``` [Try it online!](https://tio.run/nexus/haskell#LcrdCoIwHIbx867idXWwsX@ymX1Ji@7DJOZHJOgMZwjRvZtBZw8/ntbWztRuqHpbDKuXa2pX@bC1T86vbn32j26Ek5IlYFLe4UTYV7YU4dj1pZ9mMKn/cEs38uK0bsga47IgUIvGcEWK2JKJJOVWFmSpTLz4zfl/5gWVc7zrZ6pIU54xIy8smyYFjQgbxNhihz0OOELPqKEj6A10DL1FrL4 "Haskell – TIO Nexus") * `f` is the main function, which takes an integer and returns a string. * `l` is an infinite list of tuples `(a,b,s)`, shortest representations `s` first, together with their value `a` and the value `b` of the representation with the first char stripped. (as others have also noted/noticed, it's harmless to treat the latter as 0 for `#`.) * The elements of `l` other than the first one are generated recursively with a list comprehension. `d` is the character that is to be prepended to `s` to generate a new representation in the list, and 'c' is the corresponding increment to `a`. ]
[Question] [ Write a function which takes a set of integers and prints every permutation of the set, and the swap performed in between each step ### Input a set of integers, for example (0, 1, 2) ### Output the list of permutations and swaps in the format (set) (swap) (set) ... ### Test case ``` Input: (3, 1, 5) Output: (3, 1, 5) (3, 1) (1, 3, 5) (3, 5) (1, 5, 3) (1, 3) (3, 5, 1) (3, 5) (5, 3, 1) (3, 1) (5, 1, 3) ``` ### Rules * You can format the set of numbers however you want. * You can do the swaps in any order * You can repeat permutations and swaps in order to get a new one * Your code doesn't have to actually perform the swaps, the output just needs to show what swap was made between your last output and your current one * Your code only needs to function for sets with 2 or more elements * The set you're given will have no repeating elements (e.g. (0, 1, 1, 2) is invalid) This is code-golf, so shortest code wins! [Answer] # Mathematica, 102 bytes ``` <<Combinatorica` Riffle[#,BlockMap[Pick[#[[1]],#!=0&/@({1,-1}.#)]&,#,2,1]]&@*MinimumChangePermutations ``` **Examples** *//Column for a clearer result* ``` %[{1,3,5}]//Column (* {1,3,5} {1,3} {3,1,5} {3,5} {5,1,3} {5,1} {1,5,3} {1,3} {3,5,1} {3,5} {5,3,1} *) ``` [Answer] # Java, ~~449~~ 426 bytes ``` import java.util.*;interface P{static Set s=new HashSet();static void main(String[]a){o(Arrays.toString(a));while(s.size()<n(a.length)){p(a);o(Arrays.toString(a));}}static<T>void o(T z){System.out.println(z);s.add(z);}static int n(int x){return x==1?1:x*n(x-1);}static void p(String[]a){Random r=new Random();int l=a.length,j=r.nextInt(l),i=r.nextInt(l);String t=a[j];a[j]=a[i];a[i]=t;System.out.println("("+a[j]+","+t+")");}} ``` Brute force approach. It keeps making random swaps until all the possible permutations have took place. It uses a Set of the string representation of the array in order to check how many different states have been generated. For n different integers there are n! = 1\*2\*3\*..\*n distinct permutations. **Update** * Followed Kevin Cruijssen's suggestions to golf it a bit more. Ungolfed: ``` import java.util.*; interface P { static Set<String> s = new HashSet<>(); static void main(String[] a) { // prints the original input o(Arrays.toString(a)); while (s.size() < n(a.length)) { p(a); // prints the array after the swap o(Arrays.toString(a)); } } static void o(String z) { System.out.println(z); // adds the string representation of the array to the HashSet s.add(z); } // method that calculates n! static int n(int x) { if (x == 1) { return 1; } return x * n(x - 1); } // makes a random swap and prints what the swap is static void p(String[] a) { Random r = new Random(); int l = a.length, j = r.nextInt(l), i = r.nextInt(l); String t = a[j]; a[j] = a[i]; a[i] = t; System.out.println("(" + a[j] + "," + t + ")"); } } ``` Usage: ``` $ javac P.java $ java P 1 2 3 [1, 2, 3] (2,1) [2, 1, 3] (1,1) [2, 1, 3] (2,2) [2, 1, 3] (3,1) [2, 3, 1] (3,1) [2, 1, 3] (1,2) [1, 2, 3] (1,1) [1, 2, 3] (3,2) [1, 3, 2] (2,3) [1, 2, 3] (3,1) [3, 2, 1] (3,1) [1, 2, 3] (3,3) [1, 2, 3] (1,2) [2, 1, 3] (1,3) [2, 3, 1] (1,2) [1, 3, 2] (3,1) [3, 1, 2] ``` As you can see there are many more swaps than the necessary minimum. But it seems to work :-D As a bonus, it works with strings too, i.e. ``` $ java P 'one' 'two' [one, two] (two,one) [two, one] ``` [Answer] ## JavaScript (ES6), 186 bytes ``` f= a=>{console.log(a);d=a.slice().fill(-1);s=[...d.keys()];for(i=l=a.length;i;)s[k=(j=s.indexOf(--i))+d[i]]<i?(console.log(a[s[j]=s[k]],a[s[k]=i]),console.log(s.map(n=>a[n])),i=l):d[i]*=-1} ; ``` ``` <input id=i><input type=button value=Go! onclick=f(i.value.split`,`)> ``` Note: I'm not sure how flexible the output format is, may be I could do this for 171 bytes: ``` a=>{console.log(a);d=a.slice().fill(-1);s=[...d.keys()];for(i=l=a.length;i;)s[k=(j=s.indexOf(--i))+d[i]]<i?console.log(a[s[j]=s[k]],a[s[k]=i],s.map(n=>a[n],i=l)):d[i]*=-1} ``` Works by performing the [Steinhaus–Johnson–Trotter](https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm) algorithm on the shuffle array of indices and translating back to the input array. Ungolfed: ``` function steps(array) { console.log(array); // initial row var d = a.slice().fill(-1); // direction values var s = [...a.keys()]; // initial (identity) shuffle var l = a.length; for (var i = l; i; ) { // start by trying to move the last element var j = s.indexOf(--i); var k = j + d[i]; // proposed exchange if (s[k] < i) { // only exchange with lower index (within bounds) console.log(a[s[k]],a[i]); // show values being exchanged s[j] = s[k]; s[k] = i; // do the exchange on the shuffle console.log(s.map(n=>a[n])); // show the shuffled array i = l; // start from the last element again } else { d[i] *= -1; // next time, try moving it the other way } // --i above causes previous element to be tried } // until no movable elements can be found } ``` [Answer] ## Ruby, 86 bytes ``` puts (2..(a=gets.scan(/\d+/).uniq).size).map{|i|a.permutation(i).map{|e|?(+e*", "+?)}} ``` [Answer] # Haskell - 135 bytes ``` p=permutations;f=filter q(a:b:xs)=(\x->f(uncurry(/=)).zip x)a b:q(b:xs);q _=[] l=head.f(all((==2).length).q).p.p f=zip.l<*>map head.q.l ``` output: ``` > f [3,1,5] [([3,1,5],(3,1)),([1,3,5],(3,5)),([1,5,3],(1,5)),([5,1,3],(1,3)),([5,3,1],(5,3))] ``` I am using the standard `permutations` function, which is not based on swaps, so I am taking the permutations of the permutations and finding one that happens to be a chain of swaps. ]
[Question] [ # Definition * Two integers are **coprime** if they share no positive common divisors other than `1`. * `a(1) = 1` * `a(2) = 2` * `a(n)` is the smallest positive integer which is coprime to the `a(n-1)` and `a(n-2)` and has not yet appeared, for integer `n >= 3`. # Task * Given positive integer `n`, output/print `a(n)`. # Example * `a(11) = 6` because `6` is coprime with the last two predecessors (namely, `11` and `13`) and `6` has not appeared before. # Notes * Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor. # Specs * You **must** use 1-indexed. # Testcases ``` n a(n) 1 1 2 2 3 3 4 5 5 4 6 7 7 9 8 8 9 11 10 13 11 6 12 17 13 19 14 10 15 21 16 23 17 16 18 15 19 29 20 14 100 139 1000 1355 10000 13387 100000 133361 ``` # Scoring * Since coprime means that the two numbers share only one divisor (`1`), and `1` is a small number, your code should be as small as possible in terms of byte-count. # References * OEIS [A084937](http://oeis.org/A084937) [Answer] # Python 3.5, ~~160~~ ~~141~~ ~~126~~ ~~124~~ ~~121~~ 109 bytes This is a simple implementation of the sequence's definition. Golfing suggestions welcome. **Edit:** -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5. ``` import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1) ``` **Ungolfing:** ``` import math def f(n, r=[2,1], c=3): if n<2: return r[1] elif (c in r) + math.gcd(c,r[0]*r[1]) < 2: return f(n-1, [c]+r) else: return f(n, r, c+1) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~28~~ 27 bytes ``` 2:i:"`@ym1MTF_)Zdqa+}@h]]G) ``` The code is slow, but gives the correct result. [Try it online!](http://matl.tryitonline.net/#code=MjppOiJgQHltMU1URl8pWmRxYSt9QGhdXUcp&input=MTA) Or [verify the first ten cases](http://matl.tryitonline.net/#code=IgoyOkA6ImBAeW0xTVRGXylaZHFhK31AaF1dCkApRA&input=MToxMA). A small modification of the code produces a plot of the sequence: ``` 2:i:"`@ym1MTF_)Zdqa+}@h]]G:)XG ``` See it as [ASCII art](http://matl.tryitonline.net/#code=MjppOiJgQHltMU1URl8pWmRxYSt9QGhdXUc6KVhH&input=MzA), or with graphical output in the offline compiler: [![enter image description here](https://i.stack.imgur.com/EyiQx.png)](https://i.stack.imgur.com/EyiQx.png) [![enter image description here](https://i.stack.imgur.com/UWwGo.png)](https://i.stack.imgur.com/UWwGo.png) ### Explanation ``` 2: % Push [1 2] to initiallize the sequence i: % Input n. Push [1 2 ... n] " % For loop: repeat n times ` % Do while loop @ % Push iteration index, starting at 1. This is the candidate number % to extend the sequence y % Duplicate vector containing the sequence so far m % Is member? Gives true if the candidate is in the sequence 1M % Push candidate and vector again TF_) % Get last two elements of the vector Zd % GCD between the candidate and those two elements. Produces a % two-element vector qa % True if any of the two results exceeds 1, meaning % the candidate is not coprime with the latest two sequence values + % Add. This corresponds to logical "or" of the two conditions, namely % whether the candidate is member of the sequence so far, and % whether it is not coprime with the latest two. In either case % the do...while must continue with a next iteration, to try a new % candidate. Else the loop is exited, and the current candidate % is the new value of the sequence } % Finally (execute when the loop is exited) @h % Push current candidate and concatenate to the sequence vector ] % End do...while ] % End for G) % Get n-th value of the sequence. Implicitly display ``` [Answer] # C, 185 bytes ``` G(a,b){return a%b?G(b,a%b):b;} i,j,k;f(n){int a[n+2];for(i=0;i++<n;){a[i]=i<3?i:0;for(j=2;!a[i];++j){for(k=i;--k;){if(a[k]==j)++j,k=i;}a[G(a[i-1],j)*G(a[i-2],j)<2?i:0]=j;}}return a[n];} ``` [Answer] # [Actually](http://github.com/Mego/Seriously), ~~38~~ ~~37~~ ~~35~~ ~~33~~ ~~31~~ 30 bytes This is a simple implementation of the function definition. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=MlIj4pWXLDtgMSI7MsKx4pWcdM-AZ0DilZzDrStZIsKj4pWT4pWWYG5E4pWcRQ&input=MjA) **Edit:** -3 bytes thanks to Leaky Nun. ``` 2R#╗,;`1";2±╜tπg@╜í+Y"£╓╖`nD╜E ``` **Ungolfing:** ``` 2R#╗ Push [1,2] and store it in register 0 ,; Take input and duplicate `1 Start function, push 1 " Start string ; Duplicate i 2±╜t Push (list in register 0)[-2:] πg gcd(i, product of list[-2:]) @╜í Rotate the gcd and bring up i, check for i in list (0-based, -1 if not found) +Y Add the gcd and the index, negate (1 if coprime and not found in list, else 0) "£ End string, turn into a function ╓ Push first (1) values where f(x) is truthy, starting with f(0) ╖` Append result to the list in register 0, end function n Run function (input) times D╜E Return (final list)[n-1] ``` [Answer] ## Haskell, ~~81~~ 73 bytes ``` c l@(m:n:_)=m:c([x|x<-[1..],gcd(m*n)x<2,all(/=x)l]!!0:l) ((0:1:c[2,1])!!) ``` Usage example: `((0:1:c[2,1])!!) 12`-> `17`. Build the list of all `a(n)`, starting with `0` to fix the 1-based index and `1` and followed by `c[2,1]`. `c` takes the head of it's argument list `l` followed by a recursive call with then next number that fits (co-prime, not seen before) added in front of `l`. Pick the `n`th element of this list. [Answer] # R, 141 bytes ``` f=Vectorize(function(n)ifelse(n>3,{c=3;a=f(n-1);b=f(n-2);d=f(4:n-3);while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)c=c+1;c},n)) ``` ungolfed ``` f=Vectorize( function(n) #build a recursive function. Vectorize allows if(n>3) { #the function to be called on vectors. c=3 #Tests size. Builds some frequent variables. a=f(n-1) b=f(n-2) d=f(4:n-3) #Should really golf this out, but its horribly slow. while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d) c=c+1 #If we are coprime and not already seen. add. c } else n) #First three are 1,2,3. ``` [Answer] # Mathematica, ~~97~~ 90 bytes ``` a@1=1;a@2=2;a@n_:=SelectFirst[Range[2n],GCD[a[n-1]a[n-2],#]<2&&!MemberQ[a/@Range[n-1],#]&] ``` Based on ~~my conjecture that~~ `a(n) < 2n` for all `n`. To get a faster run, add `a@n=` after the original `:=` so that [the function doesn't need to recalculate previous values](http://reference.wolfram.com/language/tutorial/FunctionsThatRememberValuesTheyHaveFound.html). *Saved 7 bytes thanks to Sherlock9* (if `gcd(a,b)=1` then `gcd(ab,m) = gcd(a,m)*gcd(b,m)`) [Answer] # Pyth, 23 bytes ``` eu+Gf&-TGq1iT*F>2G1tQ]1 ``` [Test suite](https://pyth.herokuapp.com/?code=eu%2BGf%26-TGq1iT%2aF%3E2G1tQ%5D1&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) A fairly straightforward implementation, but with some nice golfing tricks. ``` eu+Gf&-TGq1iT*F>2G1tQ]1 u tQ]1 Apply the following function input - 1 times, where G is the current state (List of values so far) +G Add to G f 1 The first number, counting up from 1 -TG That has not been seen so far & And where >2G The most recent two numbers *F Multiplied together iT Gcd with the current number being checked q1 Equals 1 e Output the final element of the list. ``` ]
[Question] [ A binary recurrence sequence is a recursively-defined sequence of the following form: $$F(1) = a\_1 \\ \vdots \\ F(y) = a\_y \\ F(n) = \alpha F(n-x) + \beta F(n-y), n > y$$ This is a generalization of the Fibonacci (\$x = 1, y = 2, a = [1, 1], \alpha = 1, \beta = 1\$) sequence and the Lucas (\$x = 1, y = 2, a = [2, 1], \alpha = 1, \beta = 1\$) sequence. ## The Challenge Given \$n, x, y, a, \alpha\$, and \$\beta\$, in any reasonable format, output the \$n\$th term of the corresponding binary recurrence sequence. ## Rules * You may choose for the sequence to be either 1-indexed or 0-indexed, but your choice must be consistent across all inputs, and you must make note of your choice in your answer. * You may assume that no invalid inputs would be given (such as a sequence that terminates prior to \$n\$, or a sequence that references undefined terms, like \$F(-1)\$ or \$F(k)\$ where \$k > n\$). As a result of this, \$x\$ and \$y\$ will always be positive. * The inputs and outputs will always be integers, within the boundaries of your language's natural integer type. If your language has unbounded integers, the inputs and outputs will be within the range \$[-2^{31}, 2^{31}-1]\$ (i.e. the range for a 32-bit signed two's complement integer). * \$a\$ will always contain exactly \$y\$ values (as per the definition). ## Test Cases Note: all test cases are 0-indexed. ``` x = 1, y = 2, a = [1, 1], alpha = 1, beta = 1, n = 6 => 13 x = 1, y = 2, a = [2, 1], alpha = 1, beta = 1, n = 8 => 47 x = 3, y = 5, a = [2, 3, 5, 7, 11], alpha = 2, beta = 3, n = 8 => 53 x = 1, y = 3, a = [-5, 2, 3], alpha = 1, beta = 2, n = 10 => -67 x = 5, y = 7, a = [-5, 2, 3, -7, -8, 1, -9], alpha = -10, beta = -7, n = 10 => 39 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁴Cịæ.⁵ṭµ¡⁶ị ``` **Try it online!** [1](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzEsIDFd+WzEsIDJd+WzEsIDFd+Nw) | [2](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDFd+WzEsIDJd+WzEsIDFd+OQ) | [3](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=WzIsIDMsIDUsIDcsIDExXQ+WzMsIDVd+WzIsIDNd+OQ) | [4](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzXQ+WzEsIDNd+WzEsIDJd+MTE) | [5](http://jelly.tryitonline.net/#code=4oG0Q-G7i8OmLuKBteG5rcK1wqHigbbhu4s&input=&args=Wy01LCAyLCAzLCAtNywgLTgsIDEsIC05XQ+WzUsIDdd+Wy0xMCwgLTdd+MTE) ### How it works ``` ⁴Cịæ.⁵ṭµ¡⁶ị Main link. Arguments: a; [x, y]; [α, β]; n (1-based) µ Combine the links to the left into a chain. ¡ Execute that chain n times, updating a after each execution. ⁴ Yield [x, y]. C Complement; yield [1 - x, 1 - y]. ị Retrieve the elements of a at those indices. Indexing is 1-based and modular in Jelly, so this retrieves [a[-x], a[-y]] (Python syntax). ⁵ Yield [α, β]. æ. Take the dot product of [a[-x], a[-y]] and [α, β]. ⁶ Yield n. ị Retrieve the element of a at index n. ``` [Answer] ## Python 2, 62 bytes ``` x,y,l,a,b=input();f=lambda n:l[n]if n<y else a*f(n-x)+b*f(n-y) ``` A direct recursive solution. All inputs are taken from STDIN except for `n` as a function argument, a split that's is [allowed by default](http://meta.codegolf.stackexchange.com/a/5415/20260) (though contentiously). There doesn't seem to be a way to save bytes with `and/or` in place of `if/else` because `l[n]` could be falsey as 0. [Answer] ## JavaScript (ES6), ~~51~~ 44 bytes ``` (x,y,z,a,b)=>g=n=>n<y?z[n]:a*g(n-x)+b*g(n-y) ``` Note that the function is partially curried, e.g. `f(1,2,[1,1],1,1)(8)` returns 34. It would cost 2 bytes to make the intermediate functions independent of each other (currently only the last generated function works correctly). Edit: Saved 7 bytes thanks to @Mego pointing out that I'd overlooked that the the passed-in array always contains the first `y` elements of the result. [Answer] ## Haskell, ~~54~~ 48 bytes ``` l@(x,y,a,p,q)%n|n<y=a!!n|k<-(n-)=p*l%k x+q*l%k y ``` [Answer] # Python 2, 59 bytes ``` x,y,A,a,b,n=input() exec'A+=a*A[-x]+b*A[-y],;'*n print A[n] ``` Test it on [Ideone](http://ideone.com/4Qun1t). [Answer] # J, 43 bytes ``` {:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{. ``` Given an initial sequence of terms *A*, computes the next term *n* times using the parameters of *x*, *y*, *α*, and *β*. Afterwards, it selects the *nth* term in the extended sequence and outputs it as the result. ## Usage Since J only supports 1 or 2 arguments, I group up all the parameters as a list of boxed lists. The initial seed values *A* are first, followed by the parameters of *x* and *y* as a list, followed by the parameters of *α* and *β* as a list, and ending with the value *n*. ``` f =: {:{](],(2>@{[)+/ .*]{~1-@>@{[)^:(3>@{[)>@{. 2 3 5 7 11;3 5;2 3;8 ┌──────────┬───┬───┬─┐ │2 3 5 7 11│3 5│2 3│8│ └──────────┴───┴───┴─┘ f 2 3 5 7 11;3 5;2 3;8 53 f _5 2 3 _7 _8 1 _9;5 7;_10 _7;10 39 ``` ]
[Question] [ In [this challenge about prefix code](https://codegolf.stackexchange.com/questions/79092/is-it-a-prefix-code), we learnt that prefix codes are uniquely concatenable. That means, they can be joined together without separator, and without ambiguity. For example, since [1,2,45] is a prefix code, I can join them together without separator as such: 1245245112145, and there will be no ambiguity. However the converse is not always true. For example, [3,34] is not a prefix code. However, I can do the same: 3333434334333, and there will be no ambiguity. You would just need a smarter parser. However, [1,11] is not uniquely concatenable, because 1111 can be interpreted in 5 ways. # Goal Your task is to write a program/function that takes a list of strings (ASCII) as input, and determine if they are uniquely concatenable. # Details Duplicate counts as false. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins. # Testcases True: ``` [12,21,112] [12,112,1112] [3,4,35] [2,3,352] ``` False: ``` [1,1] [1,2,112] [1,23,4,12,34] [1,2,35,4,123,58,8] ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes On the phone, so explanation will have to follow later. Code: ``` gF¹N>ã})€`€JDÚQ ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Z0bCuU4-w6N9KeKCrGDigqxKRMOaUQ&input=WzEyLCAxMTIsIDExMTJd). Takes too much memory for the last test case, so that might not work... [Answer] ## CJam (54 bytes) ``` q_N/:A\,{_Am*:${~1$,<=},{~\,>}%La:L-}*A,A_&,-A*](\M*&! ``` Takes input on stdin as newline-separated list. [Online demo](http://cjam.aditsu.net/#code=q_N%2F%3AA%5C%2C%7B_Am*%3A%24%7B~1%24%2C%3C%3D%7D%2C%7B~%5C%2C%3E%7D%25La%3AL-%7D*A%2CA_%26%2C-A*%5D(%5CM*%26!&input=1%0A23%0A4%0A12%0A34) If we didn't have to handle duplicate codewords, this could be shortened to 44: ``` q_N/\,{_W$m*:${~1$,<=},{~\,>}%La:L-}*](\M*&! ``` Or if CJam had an array subtraction which only removed one item from the first list for each item in the second, it could be 48... ### Dissection This is the [Sardinas-Patterson algorithm](https://en.wikipedia.org/wiki/Sardinas%E2%80%93Patterson_algorithm) but de-optimised. Since each dangling suffix only comes up at most once, running the main loop as many times as there are characters in the input (including separators) guarantees to be sufficient. Note that I had to work around what is arguably a bug in the CJam interpreter: ``` "abc" "a" # e# gives 0 as the index at which "a" is found "abc" "d" # e# gives -1 as the index at which "d" is found "abc" "" # e# gives an error ``` So the prefix check is complicated to `1$,<=` instead of `\#!` ``` e# Take input, split, loop once per char q_N/\,{ e# Build the suffixes corresponding to top-of-stack and bottom-of-stack _W$m* e# Map each pair of Cartesian product to the suffix if one is the prefix of the other; e# otherwise remove from the array :${~1$,<=},{~\,>}% e# Filter out empty suffixes iff it's the first time round the loop La:L- }* e# If we generated an empty suffix then we've also looped enough times to generate all e# of the keywords as suffixes corresponding to the empty fix, so do a set intersection e# to test this condition. ](\M*&! ``` ]
[Question] [ Paper stars are a big thing in my family at christmas, so I thought a virtual one would be cool. Below is an image of a **regular dodecahedron** (from <https://en.wikipedia.org/wiki/Dodecahedron>, attributed to the author mentioned there.) [![enter image description here](https://i.stack.imgur.com/E26ya.png)](https://i.stack.imgur.com/E26ya.png) The process of [stellation](https://en.wikipedia.org/wiki/Stellation) (wikipedia) when applied to a polyhedron involves extending the faces until they cross other faces. Thus starting with the regular dodecahedron, we obtain the following shapes: **Small Stellated Dodecahedron, Great Dodecahedron and Great Stellated Dodecahedron** Image from <http://jwilson.coe.uga.edu/emat6680fa07/thrash/asn1/stellations.html> [![enter image description here](https://i.stack.imgur.com/Wo4nI.gif)](https://i.stack.imgur.com/Wo4nI.gif) These are the three possible [Stellations of the dodecahedron](http://mathworld.wolfram.com/DodecahedronStellations.html) (Wolfram). They form a natural progression from the dodecahedron, to the small stellated dodecahedron, great dodecahedron and great stellated dodecahedron, as we extend the faces further and further out. **Task** Your program or function should display or output to an image file one of the following polyhedra: **Regular dodecahedron, Small stellated dodecahedron, Great dodecahedron or Great Stellated Dodecahedron**. The colour scheme should be as the second image above. Each of the six pairs of opposite faces shall be one of the six colours Red, Yellow, Green, Cyan, Blue, and Magenta. You may use default colours with these names in your language or its documentation, or use the colours FF0000, FFFF00, 00FF00, 00FFFF, 0000FF, and FF00FF (you may tone these down by reducing the intensity to a minimum of 75% if desired, for example by reducing the F's to C's.) Note that we define a "face" as being all areas in the same plane. Thus in the images above the front face is yellow (and the parallel back face would also be yellow.) Background should be black, grey, or white. Edges may be omitted, but should be black if drawn. **Rules** The displayed polyhedron must be between 500 and 1000 pixels in width (width is defined as the maximum distance between any two displayed vertices.) The displayed polyhedron must be in perspective projection (viewpoint at least 5 widths away from the polyhedron), or orthographic projection (effectively a perspective projection with the viewpoint at infinity). The polyhedron must be displayable from any angle. (It is not acceptable to pick the easiest possible angle and making a hardcoded 2D shape.) The angle can be specified by the user in either of the following ways: 1. Input of three angles corresponding to three rotations, from stdin, or as function or commandline parameters. These can be either Euler angles (where the first and last rotations are about the same axis) or Tait-Bryan angles (where there is one rotation each about the x, y and z axis) <https://en.wikipedia.org/wiki/Euler_angles> (simply put, anything goes so long as each rotation is about the x, y, or z axis and consecutive rotations are about perpendicular axes.) 2. Facility for the user to rotate the polyhedron in steps of not more than 10 degrees about the x and y axes and refresh the display, any arbitrary number of times (assuming z axis perpendicular to the screen). The polyhedron must be solid, not wireframe. No builtins for drawing polyhedra are allowed (I'm looking at you, Mathematica!) **Scoring** This is codegolf. Shortest code in bytes wins. Bonuses Multiply your score by 0.5 if you do not use builtins for 3D drawing. Multiply your score by 0.7 if you can display all three of the stellations of the dodecahedron, selectable by the user by an integer 1-3 entered from stdin, or by function or commandline parameter. If you go for both bonuses your score will be multiplied by 0.5\*0.7=0.35 **Useful info (sources as below)** <https://en.wikipedia.org/wiki/Regular_dodecahedron> <https://en.wikipedia.org/wiki/Regular_icosahedron> The dodecahedron has 20 vertices. 8 of them form the vertices of a cube with the following cartesian (x,y,z) coordinates: (±1, ±1, ±1) The remaining 12 are as follows (phi is the golden ratio) (0, ± 1 / φ , ±φ) (± 1 / φ , ±φ, 0) (±φ, 0, ± 1 / φ ) The convex hull of the small stellated dodecahedron and great dodecahedron is obviously a regular dodecahedron. The outer vertices describe an icosahedron. According to Wikipedia an icosahedron's 12 vertices can be described in a similar manner as cyclic permutations of (0, ±1, ±φ). The outer vertices of the small stellated dodecaheron and great dodechahedron (on the same scale as the dodecahedron above) form a larger icosahedron, where the coordinates of the vertices are cyclic permutations of (0, ±φ^2, ±φ). The angles between faces for the dodecahedron and icosahedron are 2 arctan(phi) and arccos(-(√5)/3) respectively. For tips on rotating, see <https://en.wikipedia.org/wiki/Rotation_matrix> **EDIT: By mistake I have allowed the regular dodecahedron, and can't retract it now. The x0.7 bonus for drawing all three of the stellated polyhedra remains. On New Year's Day I will issue a bounty of 100 for the answer that can display the most of the four polyhedra, with shortest code as the tie break.** [Answer] # Python 2.7, 949 bytes Here is the solution for the regular dodecahedron plotted using matplotlib. The rough outline for the ungolfed code (not shown here) was is outlined below: * Make vertices Make edges (based on 3 nearest neighbours, module scipy.spatial.KDtree) * Make faces based on graph cycles with length 5 (module networkx) * Make facenormals (and select those with outward facing normal, numpy.cross) * Generate coloring based on face normals * Plotting using matplotlib > > > ``` > import itertools as it > import numpy as np > from mpl_toolkits.mplot3d.art3d import Poly3DCollection > import matplotlib.pyplot as plt > v=[p for p in it.product((-1,1),(-1,1),(-1,1))] > g=.5+.5*5**.5 > v.extend([p for p in it.product((0,),(-1/g,1/g),(-g,g))]) > v.extend([p for p in it.product((-1/g,1/g),(-g,g),(0,))]) > v.extend([p for p in it.product((-g,g),(0,),(-1/g,1/g))]) > v=np.array(v) > g=[[12,14,5,9,1],[12,1,17,16,0],[12,0,8,4,14],[4,18,19,5,14],[4,8,10,6,18],[5,19,7,11,9],[7,15,13,3,11],[7,19,18,6,15],[6,10,2,13,15],[13,2,16,17,3],[3,17,1,9,11],[16,2,10,8,0]] > a=[2,1,0,3,4,5,0,1,2,3,4,5] > fig = plt.figure() > ax = fig.add_subplot((111),aspect='equal',projection='3d') > ax.set_xlim3d(-2, 2) > ax.set_ylim3d(-2, 2) > ax.set_zlim3d(-2, 2) > for f in range(12): > c=Poly3DCollection([[tuple(y) for y in v[g[f],:]]], linewidths=1, alpha=1) > c.set_facecolor([(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0)][a[f]]) > ax.add_collection3d(c) > ax.auto_scale_xyz > plt.show() > > ``` > > [![enter image description here](https://i.stack.imgur.com/j082z.gif)](https://i.stack.imgur.com/j082z.gif) [Answer] # Ruby, 784 bytes \* 0.5 \* 0.7 = 274.4 **My own answer, therefore not eligible for my bounty.** Eligible for both the non-3D builtin bonus and the drawing all stellations bonus. ``` ->t,n{o=[] g=->a{a.reduce(:+)/5} f=->u,v,w,m{x=u.dup;y=v.dup;z=w.dup 15.times{|i|k,l=("i".to_c**(n[i/5]/90.0)).rect j=i%5 x[j],y[j],z[j]=y[j],x[j]*k+z[j]*l,z[j]*k-x[j]*l} p=g[x];q=g[y];r=g[z] a=[0,1,-i=0.382,-1][t]*e=r<=>0 b=[j=1+i,0,j,j][t]*e c=[-i*j,-i,1,i][t]*e d=[j*j,j,0,0][t]*e 5.times{|i|o<<"<path id=\"#{"%9.0f"%(z[i]*a+r*b+(z[i-2]+z[i-3])*c+2*r*d+999)}\" d=\"M#{(x[i]*a+p*b)} #{(y[i]*a+q*b)}L#{(x[i-2]*c+p*d)} #{(y[i-2]*c+q*d)}L#{(x[i-3]*c+p*d)} #{(y[i-3]*c+q*d)}\" fill=\"##{m}\"/>"}} a=233 b=377 z=[0,a,b,a,0] y=[a,b,0,-b,-a] x=[b,0,-a,0,b] w=[-b,0,a,0,-b] f[x,y,z,'F0F'] f[w,y,z,'0F0'] f[y,z,x,'00F'] f[y,z,w,'FF0'] f[z,x,y,'F00'] f[z,w,y,'0FF'] s=File.open("p.svg","w") s.puts'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-450 -450 900 900">',o.sort,'</svg>' s.close} ``` **Input as function parameters** An integer 0..3 corresponding to regular dodecahedron, small stellated dodecahedron, great stellated dodecahedron An array of three integers corresponding to degree angles for rotations about the x, y and x (again) axes (proper Euler angles, enabling any rotation to be achieved.) **Output** a file `p.svg` that can be displayed in a web browser. **Explanation** the arrays x,y,z at the bottom of the code contain the coordinates of the outer points of one face of a small stellated dodecahedron. This can be inscribed in the icosahedron whose 12 vertices are defined by the cyclic permutations of (+/-377,+/-233,+/-0). Note that 377 and 233 are consecutive Fibonacci numbers and therefore 377/233 is an excellent approximation to the golden ratio. an additional array w contains the x coordinates multiplied by -1, equivalent to reflection in the x plane. Function f is called 6 times, once for each colour, with the different cyclic permutations of x,y,z and w,y,z. The three rotations are passed as parameters in n[]. to use sin and cos in Ruby, it is necessary to do `include Math`. to avoid this, the cosine and sine of the angle are obtained by raising the square root of -1 `"i"` to a power of (angle in degrees / 90) The real and imaginary parts of this number are stored in k (cosine) and l (sine) Prior to rotation, x and y values are exchanged. Then matrix multiplication is applied to the y and z values to give a rotation about the x axis. The exchanging of values enables the three rotations to be carried out in a loop. So far, we only have one ring of points. To obtain the rest, we need to find the centre of the pentagon/star. This is done by finding the average of coordinates of the 5 vertices, which are stored in p,q,r. As mentioned before, only one function call per colour is made. The sign of r (the average of the z coordinates, and therefore the coordinate of the face) is tested. If it is positive, the face is a front face and therefore visible. If it is negative, the face is a back face. It is invisible, and we have no function call for the opposite face. Therefore, all three coordinates must be inverted. The sign of r is stored in e to facilitate this. The face is constructed of 5 triangles, whose vertices are linear combinations of the outer vertices of the small stellated dodecahedron and the centre of the face. In the case of the small stellated dodecahedron, for the tips of the triangles we set a=1 and b=0 (contribution 1 from x,y,z and 0 from p,q,r). For the 2 base vertices of the triangle we set c=-0.382 (contribution 1/golden ratio^2 from x,y,z) and d=1.382 (contribution from p,q,r.) The reason for the negative contribution is that the base vertices of the triangle are defined in terms of the opposing tips, which are on the opposite side of the face. The obtained coordinates are multiplied by e as necessary. The four unnamed arrays whose values are assigned to `a,b,c,d` contain the required values for the regular dodecahedron, small stellated dodecahedron, great dodecahedron and great stellated dodecahedron, selected according to variable `t` Note that for the small stellated dodecahedron and great dodecahedron, a+b=c+d=1. The relation a+b=c+d applies to the other shapes, but a different scale is applied. A line of svg code is created for each triangle. This contains an ID derived from the sum of the z coordinates of the 3 vertices of the triangle, a description of the vertices of the three coordinates of the triangle, and a colour. note that we view straight down the z axis in orthographic projection. Thus 2D x = 3D x and 2D y = 3D y. The line is added to `h.` finally, after all the function calls are finished, h is sorted so that the triangles of highest z value (in front) are plotted last, and the whole thing is saved as an svg file with the appropriate header and footer text. **Ungolfed in test program** ``` h=->t,n{ #t=type of polygon,n=angles of rotation o=[] #array for output g=->a{a.reduce(:+)/5} #auxiliary function for finding average of 5 points f=->u,v,w,m{x=u.dup;y=v.dup;z=w.dup #function to take 5 points u,v,w and plot one face (5 triangles) of the output in colour m 15.times{|i| #for each of 3 rotation angle and 5 points k,l=("i".to_c**(n[i/5]/90.0)).rect #calculate the cos and sine of the angle, by raising sqrt(-1)="i" to a power j=i%5 #for each of the 5 points x[j],y[j],z[j]=y[j],x[j]*k+z[j]*l,z[j]*k-x[j]*l} #swap x and y, then perform maxtrix rotation on (new) y and z. p=g[x];q=g[y];r=g[z] #find centre p,q,r of the face whose 5 points (in the case of small stellated dodecahedron) are in x,y,z e=r<=>0 #if r is positive, face is front. if negative, face is back, so we need to transform it to opposite face. a=[0, 1, -0.382, -1][t]*e #contribution of 5 points x,y,z to triangle tip vertex coordinates b=[1.382, 0, 1.382, 1.382][t]*e #contribution of centre p,q,r to triangle tip vertex coordinates c=[-0.528, -0.382, 1, 0.382][t]*e #contribution of 5 points x,y,z to coordinates of each triangle base vertex d=[1.901, 1.382, 0, 0][t]*e #contribution of centre p,q,r to coordinates of each triangle base vertex 5.times{|i| o<<"<path id=\"#{"%9.0f"%(z[i]*a+r*b+(z[i-2]+z[i-3])*c+2*r*d+999)}\" d=\"M#{(x[i]*a+p*b)} #{(y[i]*a+q*b)}L#{(x[i-2]*c+p*d)} #{(y[i-2]*c+q*d)}L#{(x[i-3]*c+p*d)} #{(y[i-3]*c+q*d)}\" fill=\"##{m}\"/>"} #write svg code for this triangle } a=233 #a,b =coordinate standard values b=377 z=[0,a,b,a,0] #z coordinates for one face of stellated dodecahedron y=[a,b,0,-b,-a] #y coordinates x=[b,0,-a,0,b] #x coordinates w=[-b,0,a,0,-b] #alternate x coordinates f[x,y,z,'F0F'] #call f f[w,y,z,'0F0'] #to plot f[y,z,x,'00F'] #each f[y,z,w,'FF0'] #face f[z,x,y,'F00'] #in f[z,w,y,'0FF'] #turn s=File.open("p.svg","w") #sort output in o, plot front triangles last s.puts'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-450 -450 900 900">',o.sort,'</svg>' s.close #add header and footer, and save as svg } t=gets.to_i n=[] 3.times{n<<gets.to_i} h[t,n] ``` **Output** for small stellated dodecahedron (will add some images of the other polygons soon) 1,0,0,0 home position [![enter image description here](https://i.stack.imgur.com/nisr7.png)](https://i.stack.imgur.com/nisr7.png) 1,30,0,0 rotate down 30 degrees [![enter image description here](https://i.stack.imgur.com/Meh25.png)](https://i.stack.imgur.com/Meh25.png) 1,0,30,0 rotate right 30 degrees (note: for a perfect side view, the rotation would be `atan(1/golden ratio)`=31.7 degrees, hence we can still see a small sliver of blue) [![enter image description here](https://i.stack.imgur.com/a19Cz.png)](https://i.stack.imgur.com/a19Cz.png) 1,0,20,0 rotate right 20 degrees [![enter image description here](https://i.stack.imgur.com/S1LVH.png)](https://i.stack.imgur.com/S1LVH.png) 1,60,10,-63 rotate down, right and up (example of orientation only possible with 3 rotations) [![enter image description here](https://i.stack.imgur.com/QwzK3.png)](https://i.stack.imgur.com/QwzK3.png) 0,30,0,0 regular dodecahedron [![enter image description here](https://i.stack.imgur.com/yfitZ.png)](https://i.stack.imgur.com/yfitZ.png) 2,0,20,0 great dodecahedron [![enter image description here](https://i.stack.imgur.com/ulMpE.png)](https://i.stack.imgur.com/ulMpE.png) 3,45,45,45 great stellated dodecahedron [![enter image description here](https://i.stack.imgur.com/Cy6UO.png)](https://i.stack.imgur.com/Cy6UO.png) [Answer] ## Mathematica, ~~426~~ 424 bytes ``` Graphics3D[{Red,Yellow,Green,Cyan,Blue,Magenta}~Riffle~(a=Partition)[Polygon/@Uncompress@"1:eJxtkjEKwkAURNeoySYgeAVP4QFsrcTGTiyUBcEith7A2wgKgpVH8/vgs2TYZmAyw9/5k784XDbHVwihnxisU39N9SiEdI8GO/uWHpXBtjFAgJ7HToFl5WabEdJ+anCqDb6dU9RP65NR59EnI0CZDAWYjFmomBmPCn3/hVVwc9s4xYd66wYqFJVvhMz75vWlHIkhG2HBDJ1V3kYps7z7jG6GomIu/QUJKTGkdtlX2pDM8m6pydyzHIOElBhyG6V9cxulzPldaVJ6lpuUkKUTzWcm+0obkrn0f3OT0rMc0jDkD37nlUo="~a~3~a~5,2],Boxed->1<0] ``` Uses the built-in `Graphics3D` to display the shape. Most of the bytes are taken up by the compressed vertex locations, however, which are then `Partition`ed into a form usable by `Polygon`. Finally: ![](https://i.stack.imgur.com/4zvcN.png) Note that this shape can be rotated by clicking and dragging. ]
[Question] [ I've got some Java pseudocode that uses whitespace instead of curly braces, and I want *you* to convert it. ## I/O Your program should take an input file along with a number designating how many spaces are used to indent a block. Here's an example: ``` $ convert.lang input.p 4 // Convert using 4 spaces as the block delimiter $ convert.lang input.p 2 // Convert using 2 spaces as the block delimiter ``` It should then convert the result using the specified block delimiter and output the result to stdout. ## The meat of the program Blocks open with `:` and each line within the block is indented using the block delimiter, like Python code. ``` while(true): System.out.println("Test"); ``` Each `:` is replaced with a `{`, and a `}` is appended to the end of the block. ``` while(true) { System.out.println("Test"); } ``` ## Examples *Input:* ``` public class Test: public static void main(String[] args): System.out.println("Java is verbose..."); ``` *Output:* ``` $ convert Test.pseudojava 4 public class Test { public static void main(String[] args) { System.out.println("Java is verbose..."); } } ``` *Input:* ``` main(): printf("Hello World"); ``` *Output:* ``` $ convert test.file 2 main() { printf("Hello World"); } ``` *Input:* ``` def generic_op(the_stack, func): # Generic op handling code b = the_stack.pop() if isinstance(b, list): if b: return top = b.pop(0) while b: top = func(top, b.pop(0)) the_stack.push(top) else: a = the_stack.pop() return func(a, b) ``` *Output:* ``` $ convert code.py 4 def generic_op(the_stack, func){ # Generic op handling code b = the_stack.pop() if isinstance(b, list) { if b { return } top = b.pop(0) while b { top = func(top, b.pop(0)) } the_stack.push(top) } else { a = the_stack.pop() return func(a, b) } } ``` ## Scoring The code with the least amount of [bytes](https://mothereff.in/byte-counter) wins! [Answer] # Perl, 41 bytes ``` #!perl -p0 1while s/( *).*\K:(( \1 .*)+)/ {\2 \1}/ ``` Counting the shebang as two, input is taken from stdin. A command line argument need not be provided. Any valid nesting context can be determined (and matched) without knowing the indentation size. --- **Regex Break-Down** ``` ( *) # as many spaces as possible (\1) .* # as many non-newline characters as possible \ (greediness ensures this will always match a full line) \K # keep all that (i.e. look-behind assertion) : # colon at eol (newline must be matched next) ( ( \n\1 # newline with at least one more space than the first match .* # non-newlines until eol )+ # as many of these lines as possible ) # grouping (\2) ``` --- **Sample Usage** *in1.dat* ``` public class Test: public static void main(String[] args): System.out.println("Java is verbose..."); ``` *Output* ``` $ perl py2java.pl < in1.dat public class Test { public static void main(String[] args) { System.out.println("Java is verbose..."); } } ``` --- *in2.dat* ``` main(): printf("Hello World"); ``` *Output* ``` $ perl py2java.pl < in2.dat main() { printf("Hello World"); } ``` --- *in3.dat* ``` def generic_op(the_stack, func): # Generic op handling code b = the_stack.pop() if isinstance(b, list): if b: return top = b.pop(0) while b: top = func(top, b.pop(0)) the_stack.push(top) else: a = the_stack.pop() return func(a, b) ``` *Output* ``` $ perl py2java.pl < in3.dat def generic_op(the_stack, func) { # Generic op handling code b = the_stack.pop() if isinstance(b, list) { if b { return } top = b.pop(0) while b { top = func(top, b.pop(0)) } the_stack.push(top) } else { a = the_stack.pop() return func(a, b) } } ``` [Answer] # Python 3, ~~299~~ 265 bytes ``` import sys;s=int(sys.argv[2]);t="";b=0 for l in open(sys.argv[1]): h=l;g=0 for c in l: if c!=" ":break g+=1 if g/s<b:h=" "*g+"}\n"+h;b-=1 if l.strip().endswith(":"):h=l.split(":")[0];h+=" {";b+=1 t+=h+"\n" b-=1 while b>-1: t+=" "*(b*s)+"}\n"b-=1 print(t) ``` Boom bam pow. Algorithm used: ``` //global vars string total //total modified program int b //indent buffer line thru lines: //iterate over every line string mline = "" //line to be added to the total //calculate the amount of spaces before the line (could be a lot easier) int spaces = 0 //total spaces c thru line: //go through every character in the line if c != " ": //if the current char isn't a space (meaning we went though all of them break //break out of iterating through chars spaces++ //increment the spaces because we've hit a space (hurr derr) if spaces/SPACE_SETTING < b: //if indent count of the current line is less than the indent buffer mline = "}\n" + line //add closing bracket to beginning of line b-- //decrement buffer if line.endswith(":"): //if the line ends with a `:` remove : from line mline += " {" //append { b++ //increment buffer total += mline //add modified line to total print(total) ``` [Answer] # Ruby, 70 ``` x=$_+" " 1while x.sub! /^(( *).*): ((\2 .*? )*)/,'\1 { \3\2} ' $><<x ``` Adds a trailing newline. Does not need the indent block-size parameter. Run this with `-n0` (this is really 68+2). Thank you greatly to @primo for saving over a dozen bytes. ]
[Question] [ In [chaos theory](https://en.wikipedia.org/wiki/Chaos_theory), the [horseshoe map](https://en.wikipedia.org/wiki/Horseshoe_map) is an example of how chaos arises in a simple process of folding and squashing. It goes like this: take an imaginary piece of dough, fold it, and finally squash it to its original size. Chaos arises in the pattern of how the pieces of dough end up in the final arrangement after n iterations. [![Example of an invariant measure](https://i.stack.imgur.com/unUP9.png)](https://i.stack.imgur.com/unUP9.png) In our case, we'll take a look at how [a simple binary pattern behaves when we fold and squash it](http://paulbourke.net/fractals/stretch/). Here are the steps with an 8-bit example (the binary representation of 201 or `11001001`). 1. Cut the bits in two pieces of equal length (add a '0' at the beginning if there is an odd number of bits). `1100 | 1001` 2. Fold the first half over the second half. Note that the order of the first half is reversed, as we rotate it while folding. `0011` `1001` 3. Squash to its original shape. While squashing, the upper bits are shifted left to the bits under their original position. `01001011` If we repeat this for this example, we can see that after 4 iterations, we are back to the original bitstring: ``` Start bits: 11001001 Iteration 1: 01001011 Iteration 2: 01001101 Iteration 3: 01011001 Iteration 4: 11001001 ``` So, for the decimal value of 201, the number of cycles is 4. ## The challenge * Write a full program that takes a decimal number as input and outputs the number of cycles it takes to repeat in the above described binary squash-and-fold process. * The (decimal) input must be taken from stdin (range: from 1 up to [Googol](https://en.wikipedia.org/wiki/Googol) or 10^100). * The (decimal) output must be written to stdout. * Your score is the number of bytes of your code. * Your answer must begin with [Programming language] - [Score in bytes] * Standard loopholes are not allowed. ## Examples ``` 7 --> 3 43 --> 5 178 --> 4 255 --> 1 65534 --> 1 65537 --> 12 1915195950546866338219593388801304344938837974777392666909760090332935537657862595345445466245217915 --> 329 ``` ## Final note What's interesting is that the number of cycles is related to the length of the binary representation, except for a few exceptions where the number of cycles is shorter because of the pattern in the bitstring (for example `111110` cycles after 1 iteration). This creates an interesting opportunity to optimize code length using the underlying pattern instead of calculating the number of cycles. [Answer] # CJam, 34 bytes ``` q~2b_,2%,\+{__,2//~\W%.\_W$=!}g;], ``` Nothing fancy, it just applies the map until we get back to the input, and print the number of iterations that took. [Test it here.](http://cjam.aditsu.net/#code=q~2b_%2C2%25%2C%5C%2B%7B__%2C2%2F%2F~%5CW%25.%5C_W%24%3D!%7Dg%3B%5D%2C&input=1915195950546866338219593388801304344938837974777392666909760090332935537657862595345445466245217915) [Answer] # Python 2, ~~175~~ ~~154~~ 149 bytes ``` i=bin(input())[2:] i=o='0'+i if len(i)%2 else i c=0 j=len(i)/2 while i!=o or c==0: a='' for x,y in zip(i[:j][::-1],i[j:]):a+=x+y i,c=a,c+1 print c ``` [Ideone link](https://ideone.com/JP4JhA) Thanks to [agtoever](https://codegolf.stackexchange.com/users/32381/agtoever) for 27 bytes! [Answer] # Pyth, 21 bytes I'm typing this on my phone, so please make sure to notify me of any mistakes. ``` fqu.i_hc2Gec2GTJ.BQJ1 ``` [Try it online.](http://pyth.herokuapp.com/?code=fqu.i_hc2Gec2GTJ.BQJ1&input=1915195950546866338219593388801304344938837974777392666909760090332935537657862595345445466245217915&debug=0) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 bytes ``` ≢{⊃,/↓⍉⌽@1⊢2 ¯1⍴{2|≢⍵:0,⍵⋄⍵}⍵}⌂traj⊤⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jzkXVj7qadfQftU1@1Nv5qGevg@GjrkVGCofWGz7q3VJtVANU8ah3q5WBDpB81N0CJGvBuKeppCgx61HXkkd9U0Fm/U/jMjIwBAA "APL (Dyalog Extended) – Try It Online") A full program which takes a single number as input. The `traj` function does a lot of heavy lifting here(thanks to Bubbler for suggesting it and helping ot golf this). The `(,,⍤0)/` idiom from APLcart is used to interleave lists together, but instead this uses `,/↓⍉⌽` since it is a matrix. ## Explanation ``` ≢{⊃,/↓⍉⌽@1⊢2 ¯1⍴{2|≢⍵:0,⍵⋄⍵}⍵}⌂traj⊤⎕ ⊤⎕ convert input to base-2 { }⌂traj calculate trajectory when the following function is applied repeatedly: {2|≢⍵:0,⍵⋄⍵}⍵ prepend a 0 if there are an odd number of bits 2 ¯1⍴ cut into two rows ⌽@1⊢ apply reverse to first row ,/↓⍉ transpose, concatenate into a vector ⊃ unenclose ≢ get length of the resulting list ``` ]
[Question] [ This challenge is inspired by [a SO question](https://stackoverflow.com/questions/1779199/traverse-matrix-in-diagonal-strips) about traversing a matrix by enumerating all its diagonal strips. Instead of a matrix, consider a block of text: ``` ABCD EFGH IJKL ``` Traversing this block's SW-NE diagonals from left to right, starting from the top left corner and ending in the bottom right, results in the following output: ``` A EB IFC JGD KH L ``` ## Challenge Write a program or a function that execute the reverse of the process described above. That is, given a set SW-NE diagonal strips, output the block of text that produced it. ## Input and Output Both input and output can be represented as strings with newlines, or arrays/lists of strings. Trailing newlines are optional. The input will consist of at least one printable character and can be assumed to be correct (there will not be inconsistent row lengths). The output block will always have a number of columns greater than or equal to the number of rows. ## Test Cases Input: ``` A ``` Output: ``` A ``` Input: ``` . LI PO. PV. CE G ``` Output: ``` .I.. LOVE PPCG ``` Input: ``` M DA AIT LAR SGI /OX /N / ``` Output: ``` MATRIX DIAGON ALS/// ``` [Answer] # CJam, ~~23~~ 20 bytes ``` {_z,,Nf*W%\.+zW%sN%} ``` [Try it here](http://cjam.aditsu.net/#code=qN%2F_z%2C%2CSf*W%25%5C.%2BzW%25sS%25N*&input=M%0ADA%0AAIT%0ALAR%0ASGI%0A%2FOX%0A%2FN%0A%2F). [Answer] ## Python 2, 84 ``` L=[] for w in input(): i=0;L+=[''][:len(w)-len(L)] for c in w:i-=1;L[i]+=c print L ``` Input and output are lists of strings. ``` input: ['A','EB','IFC','JGD','KH','L'] output: ['ABCD', 'EFGH', 'IJKL'] ``` The list of lines `L` to output is built up as we read the input. Each new character is appended to a line, starting from the last line `i=-1` and progressing towards the front. Whenever the new line to add is too long for the list, a new empty line is appended: `L+=[''][:len(w)-len(L)]`. I'm hoping for a way to shorten this part. [Answer] # Python 2, ~~165~~ ~~162~~ ~~169~~ 163 bytes ``` import sys j=map(list,[e.strip() for e in sys.stdin.readlines()]) r=max(1,len(j)-2) while j: s='' for b in range(r):s+=j[b].pop() j=[e for e in j if e] print s ``` Reads all lines from input, then turns them into a list of lists. Loops while that list has elements. In each iteration, it pops the last element from the number of inner lists equal to the number of columns in the output. The list is then cleaned and the line printed. Examples: ``` $ python rectangle.py << EOF > A > EB > IFC > JGD > KH > L > EOF ABCD EFGH IJKL $ python rectangle.py << EOF > . > LI > PO. > PV. > CE > G > EOF .I.. LOVE PPCG $ python rectangle.py << EOF > M > DA > AIT > LAR > SGI > /OX > /N > / > EOF MATRIX DIAGON ALS/// ``` Thanks to [w0lf](https://codegolf.stackexchange.com/users/3527/w0lf) for saving 6 bytes. # [PYG](https://gist.github.com/Celeo/b6ba14082ae6677b3c75), 139 bytes ``` j=M(L,[e.strip() for e in sys.stdin.readlines()]) r=Mx(1,len(j)-2) while j: s='' for b in R(r):s+=j[b].pop() j=[e for e in j if e] P(s) ``` [Answer] # Python, ~~332~~ 325 bytes Because Python. ``` n=[] v=[] x=y=-1 l=0 s="" while 1: k=raw_input() if len(k)<1:break n.append(k) while 1: if l>len(n):break y+=1 try: x+=1;k=n[y][x] if[x,y]not in v:s+=k;v.append([x,y]) else:raise except: try: x-=1;k=n[y][x] if[x,y]not in v:s+=k;v.append([x,y]) except:s+="\n";x=-1;y=l;l+=1 print s[:s.rstrip("\n").rfind("\n")] ``` ]
[Question] [ ### Task Write a program that reads three integers **m**, **n** either from STDIN or as command-line arguments, prints all possible tilings of a rectangle of dimensions **m × n** by **2 × 1** and **1 × 2** dominos and finally the number of valid tilings. Dominos of an individual tiling have to be represented by two dashes (`-`) for **2 × 1** and two vertical bars (`|`) for **1 × 2** dominos. Each tiling (including the last one) has to be followed by a linefeed. For scoring purposes, you also have to accept a flag from STDIN or as command line argument that makes your program print only the number of valid tilings, but not the tilings itself. Your program may not be longer than 1024 bytes. It has to work for all inputs such that **m × n ≤ 64**. (Inspired by [Print all domino tilings of 4x6 rectangle](https://codegolf.stackexchange.com/q/37988).) ### Example ``` $ sdt 4 2 ---- ---- ||-- ||-- |--| |--| --|| --|| |||| |||| 5 $ sdt 4 2 scoring 5 ``` ### Scoring Your score is determined by the execution time of your program for the input **8 8** with the flag set. To make this a *fastest code* rather than a *fastest computer* challenge, I will run all submissions on my own computer (Intel Core i7-3770, 16 GiB PC3-12800 RAM) to determine the official score. Please leave detailed instructions on how to compile and/or execute your code. If you require a specific version of your language's compiler/interpreter, make a statement to that effect. I reserve the right to leave submissions unscored if: * There is no free (as in beer) compiler/interpreter for my operating system (Fedora 21, 64 bits). * Despite our efforts, your code doesn't work and/or produces incorrect output on my computer. * Compilation or execution take longer than an hour. * Your code or the only available compiler/interpreter contain a system call to `rm -rf ~` or something equally fishy. ### Leaderboard I've re-scored all submissions, running both compilations and executions in a loop with 10,000 iterations for compilation and between 100 and 10,000 iterations for execution (depending on the speed of the code) and calculating the mean. These were the results: ``` User Compiler Score Approach jimmy23013 GCC (-O0) 46.11 ms = 1.46 ms + 44.65 ms O(m*n*2^n) algorithm. steveverrill GCC (-O0) 51.76 ms = 5.09 ms + 46.67 ms Enumeration over 8 x 4. jimmy23013 GCC (-O1) 208.99 ms = 150.18 ms + 58.81 ms Enumeration over 8 x 8. Reto Koradi GCC (-O2) 271.38 ms = 214.85 ms + 56.53 ms Enumeration over 8 x 8. ``` [Answer] # C A straightforward implementation... ``` #include<stdio.h> int a,b,c,s[65],l=0,countonly; unsigned long long m=0; char r[100130]; void w(i,x,o){ int j,k; j=(1<<b)-1&~x; if(i<a-1){ s[i+1]=j; w(i+1,j,1); for(k=j&j/2&-o;j=k&-k;k&=~j) w(i,x|3*j,j); } else if((j/3|j/3*2)==j) if(countonly) m++; else{ if(c==b) for(k=0;k<b;r[k++,l++]=10) for(j=0;j<a;j++) r[l++]=45+79*!((s[j]|s[j+1])&(1<<k)); else for(j=0;j<a;r[j++,l++]=10) for(k=0;k<b;k++) r[l++]=124-79*!((s[j]|s[j+1])&(1<<k)); r[l++]=10; if(l>=100000){ fwrite(r,l,1,stdout); l=0; } } } int main(){ scanf("%d %d %d",&a,&b,&countonly); c=b; if(a<b){a^=b;b^=a;a^=b;} s[0]=s[a]=0; w(0,0,1); if(countonly) printf("%llu\n",m); else if(l) fwrite(r,l,1,stdout); } ``` ### The cheating version ``` #include<stdio.h> #include<string.h> int a,b,c,s[65],l=0,countonly; unsigned long long m=0,d[256]; char r[100130]; void w2(){ int i,j,k,x; memset(d,0,sizeof d); d[0]=1; j=0; for(i=0;i<a-1;i++){ for(k=1;k<(1<<(b-1));k*=2) for(x=0;x<(1<<(b-2));x++) d[(x+x/k*k*3+k*3)^j]+=d[(x+x/k*k*3)^j]; j^=(1<<b)-1; } for(x=0;x<(1<<b);x++) if((x/3|x/3*2)==x) m+=d[x^((1<<b)-1)^j]; printf("%llu\n",m); } void w(i,x,o){ int j,k; j=(1<<b)-1&~x; if(i<a-1){ s[i+1]=j; w(i+1,j,1); for(k=j&j/2&-o;j=k&-k;k&=~j) w(i,x|3*j,j); } else if((j/3|j/3*2)==j){ if(c==b) for(k=0;k<b;r[k++,l++]=10) for(j=0;j<a;j++) r[l++]=45+79*!((s[j]|s[j+1])&(1<<k)); else for(j=0;j<a;r[j++,l++]=10) for(k=0;k<b;k++) r[l++]=124-79*!((s[j]|s[j+1])&(1<<k)); r[l++]=10; if(l>=100000){ fwrite(r,l,1,stdout); l=0; } } } int main(){ scanf("%d %d %d",&a,&b,&countonly); c=b; if(a<b){a^=b;b^=a;a^=b;} s[0]=s[a]=0; if(countonly) w2(); else{ w(0,0,1); if(l) fwrite(r,l,1,stdout); } } ``` ### Explanation of the faster algorithm It scans from left to right, and maintain the state `d[i][j]`, where: * `i` is in `[0,m)`, which means the current column. * `j` is a bit vector of size `n`, where the bit would be 1 if the corresponding position in column `i` is already occupied before starting working on this column. I.e. it is occupied by the right half of a `--`. * `d[i][j]` is the total number of different tilings. Then say `e[i][j]` = the sum of `d[i][k]` where you can put vertical dominoes base on `k` to form a `j`. `e[i][j]` would be the number of tilings where each 1 bit in `j` is occupied by anything but the left half of a `--`. Fill them with `--` and you'll get `d[i+1][~j]` = `e[i][j]`. `e[m-1][every bit being 1]` or `d[m][0]` is the final answer. A naive implementation will get you the time complexity somewhere near `g[n]=2*g[n-1]+g[n-2] = O((sqrt(2)+1)^n)` (already fast enough if n=m=8). But you can instead firstly loop for each possible domino, and try to add it to every tiling that can have this domino added, and merge the result to the original array `d` (like the algorithm for the Knapsack problem). And this becomes O(n\*2^n). And everything else are implementation details. The whole code runs in O(m\*n\*2^n). [Answer] # C After a round of optimizations, and adapted for the modified rules: ``` typedef unsigned long u64; static int W, H, S; static u64 RM, DM, NSol; static char Out[64 * 2 + 1]; static void place(u64 cM, u64 vM, int n) { if (n) { u64 m = 1ul << __builtin_ctzl(cM); cM -= m; if (m & RM) { u64 nM = m << 1; if (cM & nM) place(cM - nM, vM, n - 1); } if (m & DM) { u64 nM = m << W; vM |= m; vM |= nM; place(cM - nM, vM, n - 1); } } else if (S) { ++NSol; } else { char* p = Out; for (int y = 0; y < H; ++y) { for (int x = 0; x < W; ++x) { *p++ = vM & 1 ? '|' : '-'; vM >>= 1; } *p++ = '\n'; } *p++ = '\0'; puts(Out); ++NSol; } } int main(int argc, char* argv[]) { W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3); int n = W * H; if (n & 1) return 0; for (int y = 0; y < H; ++y) { RM <<= W; RM |= (1ul << (W - 1)) - 1; } DM = (1ul << (W * (H - 1))) - 1; place(-1, 0, n >> 1); printf("%lu\n", NSol); return 0; } ``` I started bumping into the length limit of 1024 characters, so I had to reduce the readability somewhat. Much shorter variable names, etc. Build instructions: ``` > gcc -O2 Code.c ``` Run with solution output enabled: ``` > ./a.out 8 8 >/dev/null ``` Run with only solution count: ``` > ./a.out 8 8 s ``` Some comments: * With the larger test example, I do want optimization now. While my system is different (Mac), around `-O2` seems to be good. * The code has gotten slower for the case where output is generated. This was a conscious sacrifice for optimizing the "count only" mode, and for reducing the code length. * There will be a few compiler warnings because of missing includes and external declarations for system functions. It was the easiest way to get me to below 1024 characters in the end without making the code totally unreadable. Also note that the code still generates the actual solutions, even in "count only" mode. Whenever a solution is found, the `vM` bitmask contains a `1` for the positions that have a vertical bar, and a `0` for positions with a horizontal bar. Only the conversion of this bitmask into ASCII format, and the actual output, is skipped. [Answer] # C The concept is to first find all possible arrangements of horizontal dominoes in a row, store them in `r[]` and then organize them to give all possible arrangements of vertical dominoes. The code for positioning the horizontal dominoes in a row is modified from this answer of mine: <https://codegolf.stackexchange.com/a/37888/15599>. It's slow for the wider grids but that isn't a problem for the 8x8 case. The innovation is in the way the rows are assembled. If the board has an odd number of rows it is turned through 90 degrees in the input parsing, so it now has an even number of rows. Now I place some vertical dominoes across the centreline. Because of symmetry, if there are `c` ways of arranging the remaining dominoes in the bottom half, there must also be `c` ways of arranging the remaining dominoes in the top half, meaning that for a given arrangement of vertical dominoes on the centreline, there are `c*c` possible solutions. Therefore only the centreline plus one half of the board is analysed when the program is required to print only the number of solutions. `f()` builds the table of possible arrangements of horizontal dominoes, and scans through the possible arrangements of vertical dominoes on the centreline. it then calls recursive function `g()` which fills in the rows. If printing is required, function `h()` is called to do this. `g()` is called with 3 parameters. `y` is the current row and `d` is the direction (up or down) in which we are filling the board from the centre outwards. `x` contains a bitmap indicates the vertical dominoes that are incomplete from the previous row. All possible arrangements of dominoes in a row from r[] are tried. In this array, a 1 represents a vertical domino and a pair of zeroes a horizontal domino. A valid entry in the array must have at least enough 1's to finish any incomplete vertical dominoes from the last row: `(x&r[j])==x`. It may have more 1's which indicates that new vertical dominoes are being started. For the next row, then, we need only the new dominoes so we call the procedure again with `x^r[j]`. If an end row has been reached and there are no incomplete vertical dominoes hanging of the top or bottom of the board `x^r[j]==0` then the half has been succesfully completed. If we are not printing, it is sufficient to complete the bottom half and use `c*c` to work out the total number of arrangements. If we are printing, it will be necessary to complete also the top half and then call the printing function `h()`. **CODE** ``` unsigned int W,H,S,n,k,t,r[1<<22],p,q[64]; long long int i,c,C; //output: ascii 45 - for 0, ascii 45+79=124 | for 1 h(){int a; for(a=n;a--;a%W||puts(""))putchar(45+(q[a/W]>>a%W)%2*79); puts(""); } g(y,d,x){int j; for(j=0;j<p;j++)if((x&r[j])==x){ q[y]=r[j]; if(y%(H-1)==0){ (x^r[j])==0? y?c++,S||g(H/2-1,-1,i):h() :0; }else{ g(y+d,d,x^r[j]); } } } e(z){int d; for(d=0;z;d++)z&=z-1;return n/2+1+d&1; } f(){ //k=a row full of 1's k=(1ULL<<W)-1; //build table of possible arrangements of horizontal dominoes in a row; //flip bits so that 1=a vertical domino and save to r[] for(i=0;i<=k;i++)(i/3|i/3<<1)==i?r[p++]=i^k:0; //for each arrangement of vertical dominoes on the centreline, call g() for(i=0;i<=k;i++)e(i)?c=0,g(H/2,1,i),C+=c*c:0; printf("%llu",C); } main(int argc, char* argv[]) { W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3); 1-(n=W*H)%2? H%2?W^=H,H^=W,W^=H,t=1:0,f() :puts("0"); } ``` Note that input with an odd number of rows and even number of columns is turned though 90 degrees in the parsing phase. If this is unacceptable, the printing function `h()` can be changed to accomodate it. (EDIT: not required, see comments.) EDIT: A new function `e()` has been used to check the parity of `i` (i.e the number of dominoes straddling the centreline.) The parity of `i` (the number of half-dominoes on the centreline protruding into each half of the board) must be the same as the oddness of the total number of spaces in each half (given by `n/2`) because only then can the dominoes fill all available space. This edit eliminates half the values of i and therefore makes my program approximately twice as fast. ]
[Question] [ This challenge is partly an algorithms challenge, partly an optimization challenge and partly simply a fastest code challenge. A T matrix is fully specified by its first row `r` and first column `c`. Each remaining element of the matrix is just a copy of the element that is diagonally up and left. That is `M[i,j] = M[i-1,j-1]`. We will allow T matrices which are not square. We do however always assume that the number of rows is no more than the number of columns. For example, consider the following 3 by 5 T matrix. ``` 10111 11011 11101 ``` We say a matrix has property X if it contains two non-empty sets of columns with non-identical indices which have the same (vector) sum. The vector sum of one or more columns is simply an element-wise summation of their columns. That is the sum of two or more columns containing `x` elements each is another column containing `x` elements. The sum of one column is trivially the column itself. The matrix above trivially has property X as the first and last columns are the same. The identity matrix never has property X. If we just remove the last column of the matrix above then we get an example which does not have property X and would give a score of 4/3. ``` 1011 1101 1110 ``` **The task** The task is to write code to find the highest scoring T matrix with binary entries and which *does not* have property X. For clarity, a matrix with binary entries has the property that each one of its entries is either 0 or 1. **Score** Your score will be the number columns divided by the number of rows in your best scoring matrix. **Tie Breaker** If two answers have the same score, the one submitted first wins. In the (very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted. In the even more unlikely event that you can find a proof of optimality of a finite matrix I will of course award the win too. **Hint** All the answers at [Find highest scoring matrix without property X](https://codegolf.stackexchange.com/questions/41021/find-highest-scoring-matrix-without-property-x) are valid here but they are not optimal. There are T matrices without property X which are not cyclic. For example, there is a 7 by 12 T matrix without property X but no such cyclic matrix. **21/11 would beat all the current answers from this and the previous challenge.** **Languages and libraries** You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux. **Bonus** The first answer with a score greater than 2 gets an immediate **200 point** bounty award. Ton Hospel has now achieved this! --- **Current leader board** * **C++**. Score 31/15 by Ton Hospel * **Java**. Score 36/19 by Peter Taylor * **Haskell**. Score 14/8 by alexander-brett [Answer] # C++, Score ~~23/12~~ ~~25/13~~ ~~27/14~~ ~~28/14~~ 31/15 Finally a result with ratio > 2: ``` rows=15,cols=31 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 ``` I completely explored 1 to 14 rows. 15 would take too long to completely explore. The results are: ``` 1/1 = 1 2/2 = 1 4/3 = 1.333 5/4 = 1.25 7/5 = 1.4 9/6 = 1.5 12/7 = 1.714 14/8 = 1.75 16/9 = 1.778 18/10 = 1.8 20/11 = 1.818 23/12 = 1.917 25/13 = 1.923 28/14 = 2 ``` The code given below is an older version of the program. The newest version is at <https://github.com/thospel/personal-propertyX>. ``` /* Compile using something like: g++ -Wall -O3 -march=native -fstrict-aliasing -std=c++11 -g propertyX.cpp -lpthread -o propertyX */ #include <cstdint> #include <climits> #include <ctgmath> #include <iostream> #include <vector> #include <array> #include <chrono> #include <mutex> #include <atomic> #include <thread> using namespace std; const int ELEMENTS = 2; using uint = unsigned int; using Element = uint64_t; using Column = array<Element, ELEMENTS>; using Set = vector<Column>; using Sum = uint8_t; using Index = uint32_t; using sec = chrono::seconds; int const PERIOD = 5*60; int const MAX_ROWS = 54; int const COL_FACTOR = (MAX_ROWS+1) | 1; // 55 int const ROW_ZERO = COL_FACTOR/2; // 27 int const ROWS_PER_ELEMENT = CHAR_BIT * sizeof(Element) / log2(COL_FACTOR); //11 Element constexpr ELEMENT_FILL(Element v = ROW_ZERO, int n = ROWS_PER_ELEMENT) { return n ? ELEMENT_FILL(v, n-1) * COL_FACTOR + v : 0; } Element constexpr POWN(Element v, int n) { return n ? POWN(v, n-1)*v : 1; } Element const ELEMENT_TOP = POWN(COL_FACTOR, ROWS_PER_ELEMENT -1); int const MAX_COLS = ROWS_PER_ELEMENT * ELEMENTS; // 22 atomic<Index> col_next; atomic<uint> period; chrono::steady_clock::time_point start; mutex period_mutex; uint ratio_row; uint ratio_col; mutex ratio_mutex; auto const nr_threads = thread::hardware_concurrency(); // auto const nr_threads = 1; struct State { State(uint cols); void process(Index i); void extend(uint row); void print(uint rows); Index nr_columns() const { return static_cast<Index>(1) << cols_; } Column last_; Element top_; int top_offset_; uint ratio_row_ = 0; uint ratio_col_ = 1; uint cols_; array<Sum, MAX_ROWS + MAX_COLS -1> side; vector<Set> sets; }; ostream& operator<<(ostream& os, Column const& column) { for (int i=0; i<ELEMENTS; ++i) { auto v = column[i]; for (int j=0; j<ROWS_PER_ELEMENT; ++j) { auto bit = v / ELEMENT_TOP; cout << " " << bit; v -= bit * ELEMENT_TOP; v *= COL_FACTOR; } } return os; } State::State(uint cols) : cols_{cols} { sets.resize(MAX_ROWS+2); for (int i=0; i<2; ++i) { sets[i].resize(2); for (int j=0; j < ELEMENTS; ++j) { sets[i][0][j] = ELEMENT_FILL(); sets[i][1][j] = static_cast<Element>(-1) - ELEMENT_FILL(1); } } top_ = POWN(COL_FACTOR, (cols_-1) % ROWS_PER_ELEMENT); top_offset_ = ELEMENTS - 1 - (cols_-1) / ROWS_PER_ELEMENT; } void State::print(uint rows) { for (auto c=0U; c<cols_;c++) { for (auto r=0U; r<rows;r++) { cout << static_cast<int>(side[cols_-c+r-1]) << " "; } cout << "\n"; } cout << "----------" << endl; } void check(uint cols, uint t) { State state(cols); Index nr_columns = state.nr_columns(); while (1) { Index col = col_next++; if (col >= nr_columns) break; state.process(col); auto now = chrono::steady_clock::now(); auto elapsed = chrono::duration_cast<sec>(now-start).count(); if (elapsed >= period) { lock_guard<mutex> lock{period_mutex}; if (elapsed >= period) { cout << "col=" << col << "/" << nr_columns << " (" << 100.*col/nr_columns << "% " << elapsed << " s)" << endl; period = (elapsed/PERIOD+1)*PERIOD; } } } } void State::process(Index col) { last_.fill(0); for (uint i=0; i<cols_; ++i) { Element bit = col >> i & 1; side[i] = bit; Element carry = 0; for (int j=0; j<ELEMENTS; ++j) { auto c = last_[j] % COL_FACTOR; last_[j] = last_[j] / COL_FACTOR + carry * ELEMENT_TOP; if (j == top_offset_ && bit) last_[j] += top_; carry = c; } } // cout << "col=" << col << ", value=" << last_ << "\n"; extend(0); } void State::extend(uint row) { // cout << "Extend row " << row << " " << static_cast<int>(side[cols_+row-1]) << "\n"; if (row >= MAX_ROWS) throw(range_error("row out of range")); // Execute subset sum. The new column is added to set {from} giving {to} // {sum} is the other set. auto const& set_from = sets[row]; auto const& set_sum = sets[row + 1]; auto & set_to = sets[row + 2]; if (set_to.size() == 0) { auto size = 3 * set_from.size() - 2; set_to.resize(size); for (int j=0; j<ELEMENTS; ++j) set_to[size-1][j] = static_cast<Element>(-1) - ELEMENT_FILL(1); } // Merge sort {set_from - last_} , {set_from} and {set_from + last_} auto ptr_sum = &set_sum[1][0]; auto ptr_low = &set_from[0][0]; auto ptr_middle = &set_from[0][0]; auto ptr_high = &set_from[0][0]; Column col_low, col_high; for (int j=0; j<ELEMENTS; ++j) { col_low [j] = *ptr_low++ - last_[j]; col_high [j] = *ptr_high++ + last_[j]; } auto ptr_end = &set_to[set_to.size()-1][0]; auto ptr_to = &set_to[0][0]; while (ptr_to < ptr_end) { for (int j=0; j<ELEMENTS; ++j) { if (col_low[j] < ptr_middle[j]) goto LOW; if (col_low[j] > ptr_middle[j]) goto MIDDLE; } // low == middle // cout << "low == middle\n"; return; LOW: // cout << "LOW\n"; for (int j=0; j<ELEMENTS; ++j) { if (col_low[j] < col_high[j]) goto LOW0; if (col_low[j] > col_high[j]) goto HIGH0; } // low == high // cout << "low == high\n"; return; MIDDLE: // cout << "MIDDLE\n"; for (int j=0; j<ELEMENTS; ++j) { if (ptr_middle[j] < col_high[j]) goto MIDDLE0; if (ptr_middle[j] > col_high[j]) goto HIGH0; } // middle == high // cout << "middle == high\n"; return; LOW0: // cout << "LOW0\n"; for (int j=0; j<ELEMENTS; ++j) { *ptr_to++ = col_low[j]; col_low[j] = *ptr_low++ - last_[j]; } goto SUM; MIDDLE0: // cout << "MIDDLE0\n"; for (int j=0; j<ELEMENTS; ++j) *ptr_to++ = *ptr_middle++; goto SUM; HIGH0: // cout << "HIGH0\n"; for (int j=0; j<ELEMENTS; ++j) { *ptr_to++ = col_high[j]; col_high[j] = *ptr_high++ + last_[j]; } goto SUM; SUM: for (int j=-ELEMENTS; j<0; ++j) { if (ptr_to[j] > ptr_sum[j]) { ptr_sum += ELEMENTS; goto SUM; } if (ptr_to[j] < ptr_sum[j]) goto DONE; } // sum == to for (int j=-ELEMENTS; j<0; ++j) if (ptr_to[j] != ELEMENT_FILL()) { // sum == to and to != 0 // cout << "sum == to\n"; // cout << set_sum[(ptr_sum - &set_sum[0][0])/ELEMENTS-1] << "\n"; return; } DONE:; } // cout << "Wee\n"; auto row1 = row+1; if (0) for (uint i=0; i<row1+2; ++i) { cout << "Set " << i << "\n"; auto& set = sets[i]; for (auto& column: set) cout << column << "\n"; } if (row1 * ratio_col_ > ratio_row_ * cols_) { ratio_row_ = row1; ratio_col_ = cols_; lock_guard<mutex> lock{ratio_mutex}; if (ratio_row_ * ratio_col > ratio_row * ratio_col_) { auto now = chrono::steady_clock::now(); auto elapsed = chrono::duration_cast<sec>(now-start).count(); cout << "cols=" << cols_ << ",rows=" << row1 << " (" << elapsed << " s)\n"; print(row1); ratio_row = ratio_row_; ratio_col = ratio_col_; } } auto last = last_; Element carry = 0; for (int j=0; j<ELEMENTS; ++j) { auto c = last_[j] % COL_FACTOR; last_[j] = last_[j] / COL_FACTOR + carry * ELEMENT_TOP; carry = c; } side[cols_+row] = 0; extend(row1); last_[top_offset_] += top_; side[cols_+row] = 1; extend(row1); last_ = last; } void my_main(int argc, char** argv) { if (!col_next.is_lock_free()) cout << "col_next is not lock free\n"; if (!period. is_lock_free()) cout << "period is not lock free\n"; int min_col = 2; int max_col = MAX_COLS; if (argc > 1) { min_col = atoi(argv[1]); if (min_col < 2) throw(range_error("Column must be >= 2")); if (min_col > MAX_COLS) throw(range_error("Column must be <= " + to_string(MAX_COLS))); } if (argc > 2) { max_col = atoi(argv[2]); if (max_col < min_col) throw(range_error("Column must be >= " + to_string(min_col))); if (max_col > MAX_COLS) throw(range_error("Column must be <= " + to_string(MAX_COLS))); } for (int cols = min_col; cols <= max_col; ++cols) { cout << "Trying " << cols << " columns" << endl; ratio_row = 0; ratio_col = 1; col_next = 0; period = PERIOD; start = chrono::steady_clock::now(); vector<thread> threads; for (auto t = 1U; t < nr_threads; t++) threads.emplace_back(check, cols, t); check(cols, 0); for (auto& thread: threads) thread.join(); } } int main(int argc, char** argv) { try { my_main(argc, argv); } catch(exception& e) { cerr << "Error: " << e.what() << endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } ``` [Answer] # Haskell 14/8 = 1.75 ``` 1 1 0 0 0 1 0 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 0 0 0 1 0 1 1 0 1 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 0 0 0 0 1 0 1 1 1 0 0 0 1 0 ``` ## Previously 9/6 = 1.5 ``` 1 0 1 0 1 1 0 0 1 1 1 0 1 0 1 1 0 0 1 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 1 1 1 1 1 1 1 0 1 0 1 1 1 1 1 1 1 0 1 0 ``` I wrote this, then looked at the answers to the other question and was... discouraged. ``` import Data.List import Data.Hashable import Control.Monad import Control.Parallel.Strategies import Control.Parallel import qualified Data.HashSet as S matrix§indices = [ matrix!!i | i<-indices ] powerset :: [a] -> [[a]] powerset = filterM (const [True, False]) hashNub :: (Hashable a, Eq a) => [a] -> [a] hashNub l = go S.empty l where go _ [] = [] go s (x:xs) = if x `S.member` s then go s xs else x : go (S.insert x s) xs getMatrix :: Int -> Int -> [Int] -> [[Int]] getMatrix width height vector = [ vector § [x..x+width-1] | x<-[0..height-1] ] hasDuplicate :: (Hashable a, Eq a) => [a] -> Bool hasDuplicate m = go S.empty m where go _ [] = False go s (x:xs) = if x `S.member` s then True else go (S.insert x s) xs hasProperty :: [[Int]] -> Bool hasProperty matrix = let base = replicate (length (matrix !! 0)) 0::[Int] in if elem base matrix then False else if hasDuplicate matrix then False else if hasDuplicate (map (foldl (zipWith (+)) base) (powerset matrix)) then False else True pmap = parMap rseq matricesWithProperty :: Int -> Int -> [[[Int]]] matricesWithProperty n m = let base = replicate n 0::[Int] in filter (hasProperty) $ map (getMatrix n m) $ sequence [ [0,1] | x<-[0..n+m-1] ] firstMatrixWithProperty :: Int -> Int -> [[Int]] firstMatrixWithProperty n m = head $ matricesWithProperty n m main = mapM (putStrLn. show) $ map (firstMatrixWithProperty 8) [1..] ``` [Answer] # C Here's an answer which works and is significantly more memory-efficient than the Haskell. Unfortunately, my computer is still too slow to achieve better than 14/8 in any reasonable length of time. Try compiling with `gcc -std=c99 -O2 -fopenmp -o matrices.exe matrices.c` and running with `matrices.exe width height` or similar. The output is an integer, the bits of which form the basis for the matrix in question, for instance: ``` $ matrices.exe 8 14 ... valid i: 1650223 ``` Then, since `1650223 = 0b110010010111000101111`, the matrix in question is: ``` 0 0 1 1 1 0 1 0 0 1 0 0 1 1 0 ... 1 ... 0 1 1 1 1 ``` If someone with 8 cores and time on their hands wants to run this for a while, I think some good things could result :) --- ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* * BEGIN WIKIPEDIA CODE */ const long long m1 = 0x5555555555555555; //binary: 0101... const long long m2 = 0x3333333333333333; //binary: 00110011.. const long long m4 = 0x0f0f0f0f0f0f0f0f; //binary: 4 zeros, 4 ones ... const long long m8 = 0x00ff00ff00ff00ff; //binary: 8 zeros, 8 ones ... const long long m16 = 0x0000ffff0000ffff; //binary: 16 zeros, 16 ones ... const long long m32 = 0x00000000ffffffff; //binary: 32 zeros, 32 ones const long long hff = 0xffffffffffffffff; //binary: all ones const long long h01 = 0x0101010101010101; //the sum of 256 to the power of 0,1,2,3... //This uses fewer arithmetic operations than any other known //implementation on machines with fast multiplication. //It uses 12 arithmetic operations, one of which is a multiply. long long hamming(long long x) { x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... } /* * END WIKIPEDIA CODE */ int main ( int argc, char *argv[] ) { int height; int width; sscanf(argv[1], "%d", &height); sscanf(argv[2], "%d", &width); #pragma omp parallel for for ( /* * We know that there are 2^(h+w-1) T-matrices, defined by the entries * in the first row and first column. We'll let the long long i * represent these entries, with 1s represented by set bits. * * The first (0) and last (1) matrix we will ignore. */ long long i = 1; i < (1 << (height+width-1))-1; i++ ) { // Flag for keeping track as we go along. int isvalid = 1; /* * Start by representing the matrix as an array of columns, with each * non-zero matrix entry as a bit. This allows us to construct them and * check equality very quickly. */ long *cols = malloc(sizeof(long)*width); long colmask = (1 << height)-1; for (int j = 0; j < width; j++) { cols[j] = (i >> j) & colmask; if (cols[j] == 0) { //check no zero rows isvalid = 0; } else { //check no duplicate rows for (int k = 0; k < j; k++) { if (cols[j] == cols[k]) { isvalid = 0; } } } } if (isvalid == 1) { /* * We'll also represent the matrix as an array of rows, in a * similar manner. */ long *rows = malloc(sizeof(long)*height); long rowmask = (1 << width)-1; for (int j = 0; j < height; j++) { rows[j] = (i >> j) & rowmask; } int *sums[(1 << width)]; for (long j = 0; j < 1<<width; j++) { sums[j] = (int*)malloc(sizeof(int)*height); } for ( /* * The powerset of columns has size 2^width. Again with the * long; this time each bit represents whether the * corresponding row is a member of the subset. The nice thing * about this is we can xor the permutation with each row, * then take the hamming number of the resulting number to get * the sum. */ long permutation = 1; (isvalid == 1) && (permutation < (1 << width)-1); permutation ++ ) { for (int j = 0; j < height; j++) { sums[permutation][j] = hamming( rows[j] & permutation); } for (int j = permutation-1; (isvalid == 1) && (j > -1); j--) { if (memcmp(sums[j], sums[permutation], sizeof(int)*height) == 0) { isvalid = 0; } } } for (long j = 0; j < 1<<width; j++) { free(sums[j]); } free(rows); } if (isvalid == 1) { printf ("valid i: %ld\n", i); } free(cols); } return 0; } ``` ]
[Question] [ # Background For the purposes of this challenge, an *`n`-state cellular automaton* is simply a binary function `f` that takes two numbers from the state set `{0, 1, ..., n-1}` as inputs, and returns another number from that set as output. It can be applied to a list of numbers `L = [x0, x1, x2, ..., xk-1]` of length at least 2 by ``` f(L) = [f(x0, x1), f(x1, x2), f(x2, x3), ..., f(xk-2, xk-1)] ``` Note that the resulting list has one fewer element than the original. A *spacetime diagram* of `f` starting from `L` is the list of lists obtained by repeatedly applying `f` to `L`, and collecting the results in a list. The final list has length 1. We say that the list `L` is an *identifying sequence* for `f`, if every two-element list over the state set is a contiguous sublist of some row of the spacetime diagram starting from `L`. This is equivalent to the condition that no other `n`-state CA has that exact spacetime diagram. # Input Your inputs are an `n`-by-`n` integer matrix `M`, a list of integers `L` of length at least 2, and optionally the number `n`. The matrix `M` defines an `n`-state CA `f` by `f(a,b) = M[a][b]` (using 0-based indexing). It is guaranteed that `n > 0`, and that `M` and `L` only contain elements of the state set `{0, 1, ..., n-1}`. # Output Your output shall be a consistent truthy value if `L` is an identifying sequence for the CA `f`, and a consistent falsy value otherwise. This means that all "yes"-instances result in the same truthy value, and all "no"-instances result in the same falsy value. # Example Consider the inputs `n = 2`, `M = [[0,1],[1,0]]`, and `L = [1,0,1,1]`. The matrix `M` defines the binary XOR automaton `f(a,b) = a+b mod 2`, and the spacetime diagram starting from `L` is ``` 1 0 1 1 1 1 0 0 1 1 ``` This diagram does not contain `0 0` on any row, so `L` is not an identifying sequence, and the correct output is `False`. If we input `L = [0,1,0,0]` instead, the spacetime diagram is ``` 0 1 0 0 1 1 0 0 1 1 ``` The rows of this diagram contain all pairs drawn from the state set, namely `0 0`, `0 1`, `1 0` and `1 1`, so `L` is an identifying sequence and the correct output is `True`. # Rules You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases ``` Trivial automaton [[0]] [0,0] 1 -> True Binary XOR [[0,1],[1,0]] [1,0,1,1] 2 -> False [[0,1],[1,0]] [1,0,1,0] 2 -> True [[0,1],[1,0]] [0,1,0,0] 2 -> True Addition mod 3 [[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,0] 3 -> False [[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,1] 3 -> True Multiplication mod 3 [[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,0,0,1,0,1] 3 -> False [[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,2,2,1,0,1] 3 -> True Some 4-state automata [[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,0,1,1,1,1] 4 -> False [[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,1,0,1,1,1] 4 -> False [[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,1,2,3,3,1,2,3,0] 4 -> True [[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,0,1,1,2,2,0,2,1] 4 -> False [[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1] 4 -> False [[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1,2] 4 -> True ``` [Answer] # Python 2: 93 byte ``` M,L,n=input();a=[] while L:z=zip(L,L[1:]);a+=z;L=[M[i][j]for i,j in z] print len(set(a))==n*n ``` Straightforward implementation: Find all pairs by zipping, memorize them for later and apply M to L. Repeat. Compare the number of unique pairs found. Input is of the form `[[0,1],[1,0]], [0,1,0,0], 2`. [Answer] # CJam, ~~53~~ ~~43~~ 42 bytes ``` l~:M;_,({_[\1>]zW<_{M\{=}/}%}*;](_*\L*_&,= ``` This is a very straight-forward implementation of the definition (I took some inspiration from Jakube after my first attempt). It expects input in reverse order on STDIN, using CJam-style arrays: ``` 2 [1 0 1 1] [[0 1][1 0]] ``` [Here is a test harness](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3D'%2CSer~%5DW%25~%0A%0A%3AM%3B_%2C(%7B_%5B%5C1%3E%5DzW%3C_%7BM%5C%7B%3D%7D%2F%7D%25%7D*%3B%5D(_*%5CL*_%26%2C%3D%0A%0Ap%7D%2F&input=%5B%5B0%5D%5D%20%5B0%2C0%5D%201%20-%3E%20True%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%20%5B1%2C0%2C1%2C1%5D%202%20-%3E%20False%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%20%5B1%2C0%2C1%2C0%5D%202%20-%3E%20True%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%20%5B0%2C1%2C0%2C0%5D%202%20-%3E%20True%0A%5B%5B0%2C1%2C2%5D%2C%5B1%2C2%2C0%5D%2C%5B2%2C0%2C1%5D%5D%20%5B0%2C1%2C1%2C0%2C0%2C0%2C1%2C0%2C0%5D%203%20-%3E%20False%0A%5B%5B0%2C1%2C2%5D%2C%5B1%2C2%2C0%5D%2C%5B2%2C0%2C1%5D%5D%20%5B0%2C1%2C1%2C0%2C0%2C0%2C1%2C0%2C1%5D%203%20-%3E%20True%0A%5B%5B0%2C0%2C0%5D%2C%5B0%2C1%2C2%5D%2C%5B0%2C2%2C1%5D%5D%20%5B0%2C1%2C1%2C2%2C0%2C0%2C1%2C0%2C1%5D%203%20-%3E%20False%0A%5B%5B0%2C0%2C0%5D%2C%5B0%2C1%2C2%5D%2C%5B0%2C2%2C1%5D%5D%20%5B0%2C1%2C1%2C2%2C2%2C2%2C1%2C0%2C1%5D%203%20-%3E%20True%0A%5B%5B3%2C2%2C2%2C1%5D%2C%5B0%2C0%2C0%2C1%5D%2C%5B2%2C1%2C3%2C1%5D%2C%5B0%2C1%2C2%2C3%5D%5D%20%5B0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%5D%204%20-%3E%20False%0A%5B%5B3%2C2%2C2%2C1%5D%2C%5B0%2C0%2C0%2C1%5D%2C%5B2%2C1%2C3%2C1%5D%2C%5B0%2C1%2C2%2C3%5D%5D%20%5B0%2C0%2C0%2C1%2C0%2C1%2C1%2C1%5D%204%20-%3E%20False%0A%5B%5B3%2C2%2C2%2C1%5D%2C%5B0%2C0%2C0%2C1%5D%2C%5B2%2C1%2C3%2C1%5D%2C%5B0%2C1%2C2%2C3%5D%5D%20%5B0%2C1%2C2%2C3%2C3%2C1%2C2%2C3%2C0%5D%204%20-%3E%20True%0A%5B%5B0%2C1%2C2%2C1%5D%2C%5B1%2C0%2C2%2C0%5D%2C%5B2%2C2%2C1%2C0%5D%2C%5B1%2C2%2C0%2C0%5D%5D%20%5B0%2C0%2C1%2C1%2C2%2C2%2C0%2C2%2C1%5D%204%20-%3E%20False%0A%5B%5B0%2C1%2C2%2C1%5D%2C%5B1%2C0%2C2%2C0%5D%2C%5B2%2C2%2C1%2C0%5D%2C%5B1%2C2%2C0%2C0%5D%5D%20%5B0%2C3%2C1%2C3%2C2%2C3%2C3%2C0%2C1%5D%204%20-%3E%20False%0A%5B%5B0%2C1%2C2%2C1%5D%2C%5B1%2C0%2C2%2C0%5D%2C%5B2%2C2%2C1%2C0%5D%2C%5B1%2C2%2C0%2C0%5D%5D%20%5B0%2C3%2C1%2C3%2C2%2C3%2C3%2C0%2C1%2C2%5D%204%20-%3E%20True) which runs the code against all inputs (converting them to the correct input format first). The results in the input field aren't actually used. Remove them if you don't trust me. ;) [Answer] # Mathematica, ~~90~~ ~~83~~ 82 bytes ``` f=Length[Union@@Last@Reap[#2//.l_List:>Extract[#,Sow/@Partition[l+1,2,1]]]]==#3^2& ``` Another straight-forward implementation. Usage: ``` f[{{0, 1}, {1, 0}}, {0, 1, 0, 0}, 2] ``` > > True > > > ]
[Question] [ You have to write a program, implementing a function `digitsum(int i)`. The program has to modify its own code (for languages, where this is not possible with f.e. [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29), please be creative) to get itself to solve the goal. You start with ``` function digitsum(int i){ return i; } ``` and implement an [evolutionary algorithm](http://en.wikipedia.org/wiki/Evolutionary_algorithm) that will modify the above function until it returns valid [digitsums](http://en.wikipedia.org/wiki/Digit_sum) on function call. As this is a popularity contest, you have very much free hands, please be creative! **Guidelines:** * Start with the defined function (translated to your language of course). * Print out at least the fittest function of each generation. * Print out your working solution tested for 0 < i < 10000. * Be creative! **Do not:** * Hint your program to the solution, please use your whole language options! * Throw errors to the console. * Use any external input. You can write and save to files created by your program. No internet. The valid solution with the most upvotes wins! [Answer] # C# Almost entirely random and raw assembly solution. As far as C# and pretty much any other platform goes, this is as low level as possible. Luckily, C# allows you to define methods during runtime in IL (IL is intermediate language, the byte-code of .NET, similar to assembly). The only limitation of this code is that I chose some opcodes (out of hundreds) with an arbitrary distribution which would be necessary for the perfect solution. If we allow all opcodes, chances of a working program are slim to none, so this is necessary (as you can imagine, there are many many ways that random assembly instructions can crash, but luckily, they don't bring down the whole program in .NET). Other than the range of possible opcodes, it's completely random slicing and dicing IL opcodes without any kind of hinting. I am pretty surprised but this actually seems to work, some generated programs do not crash and do produce results! ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Reflection.Emit; using System.Diagnostics; using System.Threading; namespace codegolf { class Program { // decompile this into IL to find out the opcodes needed for the perfect algo static int digitsumbest(int i) { var ret = 0; while (i > 0) { ret += i % 10; i /= 10; } return ret; } delegate int digitsumdelegate(int num); static Thread bgthread; // actually runs the generated code for one index // it is invoked in a background thread, which we save so that it can be aborted in case of an infinite loop static int run(digitsumdelegate del, int num) { bgthread = Thread.CurrentThread; try { return del(num); } catch (ThreadAbortException) { bgthread = null; throw; } } // evaluates a generated code for some inputs and calculates an error level // also supports a full run with logging static long evaluate(digitsumdelegate del, TextWriter sw) { var error = 0L; List<int> numbers; if (sw == null) // quick evaluation numbers = Enumerable.Range(1, 30).Concat(Enumerable.Range(1, 70).Select(x => 5000 + x * 31)).ToList(); else // full run numbers = Enumerable.Range(1, 9999).ToList(); foreach (var num in numbers) { try { Func<digitsumdelegate, int, int> f = run; bgthread = null; var iar = f.BeginInvoke(del, num, null, null); if (!iar.AsyncWaitHandle.WaitOne(10)) { bgthread.Abort(); while (bgthread != null) ; throw new Exception("timeout"); } var result = f.EndInvoke(iar); if (sw != null) sw.WriteLine("{0};{1};{2};", num, digitsumbest(num), result); var diff = result == 0 ? 15 : (result - digitsumbest(num)); if (diff > 50 || diff < -50) diff = 50; error += diff * diff; } catch (InvalidProgramException) { // invalid IL code, happens a lot, so let's make a shortcut if (sw != null) sw.WriteLine("invalid program"); return numbers.Count * (50 * 50) + 1; } catch (Exception ex) { if (sw != null) sw.WriteLine("{0};{1};;{2}", num, digitsumbest(num), ex.Message); error += 50 * 50; } } return error; } // generates code from the given byte array static digitsumdelegate emit(byte[] ops) { var dm = new DynamicMethod("w", typeof(int), new[] { typeof(int) }); var ilg = dm.GetILGenerator(); var loc = ilg.DeclareLocal(typeof(int)); // to support jumping anywhere, we will assign a label to every single opcode var labels = Enumerable.Range(0, ops.Length).Select(x => ilg.DefineLabel()).ToArray(); for (var i = 0; i < ops.Length; i++) { ilg.MarkLabel(labels[i]); // 3 types of jumps with 23 distribution each, 11 types of other opcodes with 17 distribution each = all 256 possibilities // the opcodes were chosen based on the hand-coded working solution var c = ops[i]; if (c < 23) ilg.Emit(OpCodes.Br_S, labels[(i + 1 + c) % labels.Length]); else if (c < 46) ilg.Emit(OpCodes.Bgt_S, labels[(i + 1 + c - 23) % labels.Length]); else if (c < 69) ilg.Emit(OpCodes.Bge_S, labels[(i + 1 + c - 46) % labels.Length]); else if (c < 86) ilg.Emit(OpCodes.Ldc_I4, c - 70); // stack: +1 else if (c < 103) ilg.Emit(OpCodes.Dup); // stack: +1 else if (c < 120) ilg.Emit(OpCodes.Ldarg_0); // stack: +1 else if (c < 137) ilg.Emit(OpCodes.Starg_S, 0); // stack: -1 else if (c < 154) ilg.Emit(OpCodes.Ldloc, loc); // stack: +1 else if (c < 171) ilg.Emit(OpCodes.Stloc, loc); // stack: -1 else if (c < 188) ilg.Emit(OpCodes.Mul); // stack: -1 else if (c < 205) ilg.Emit(OpCodes.Div); // stack: -1 else if (c < 222) ilg.Emit(OpCodes.Rem); // stack: -1 else if (c < 239) ilg.Emit(OpCodes.Add); // stack: -1 else ilg.Emit(OpCodes.Sub); // stack: -1 } ilg.Emit(OpCodes.Ret); return (digitsumdelegate)dm.CreateDelegate(typeof(digitsumdelegate)); } static void Main(string[] args) { System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle; var rnd = new Random(); // the first list is just 10 small random ones var best = new List<byte[]>(); for (var i = 0; i < 10; i++) { var initial = new byte[5]; for (var j = 0; j < initial.Length; j++) initial[j] = (byte)rnd.Next(256); best.Add(initial); } // load the best result from the previous run, if it exists if (File.Exists("best.txt")) best[0] = File.ReadAllLines("best.txt").Select(x => byte.Parse(x)).ToArray(); var stop = false; // handle nice stopping with ctrl-c Console.CancelKeyPress += (s, e) => { stop = true; e.Cancel = true; }; while (!stop) { var candidates = new List<byte[]>(); // leave the 10 best arrays, plus generate 9 consecutive mutations for each of them = 100 candidates for (var i = 0; i < 10; i++) { var s = best[i]; candidates.Add(s); for (var j = 0; j < 9; j++) { // the optimal solution is about 20 opcodes, we keep the program length between 15 and 40 switch (rnd.Next(s.Length >= 40 ? 2 : 0, s.Length <= 15 ? 3 : 5)) { case 0: // insert case 1: var c = new byte[s.Length + 1]; var idx = rnd.Next(0, s.Length); Array.Copy(s, 0, c, 0, idx); c[idx] = (byte)rnd.Next(256); Array.Copy(s, idx, c, idx + 1, s.Length - idx); candidates.Add(c); s = c; break; case 2: // change c = (byte[])s.Clone(); idx = rnd.Next(0, s.Length); c[idx] = (byte)rnd.Next(256); candidates.Add(c); s = c; break; case 3: // remove case 4: // remove c = new byte[s.Length - 1]; idx = rnd.Next(0, s.Length); Array.Copy(s, 0, c, 0, idx); Array.Copy(s, idx + 1, c, idx, s.Length - idx - 1); candidates.Add(c); s = c; break; } } } // score the candidates and select the best 10 var scores = Enumerable.Range(0, 100).ToDictionary(i => i, i => evaluate(emit(candidates[i]), null)); var bestidxes = scores.OrderBy(x => x.Value).Take(10).Select(x => x.Key).ToList(); Console.WriteLine("best score so far: {0}", scores[bestidxes[0]]); best = bestidxes.Select(i => candidates[i]).ToList(); } // output the code of the best solution using (var sw = new StreamWriter("best.txt")) { foreach (var b in best[0]) sw.WriteLine(b); } // create a CSV file with the best solution using (var sw = new StreamWriter("best.csv")) { sw.WriteLine("index;actual;generated;error"); evaluate(emit(best[0]), sw); } } } } ``` Sorry I have no results so far because even with testing for 1..99 (instead of 1..9999) is pretty slow and I am too tired. Will get back to you tomorrow. EDIT: I finished the program and tweaked it a lot. Now, if you press CTRL-C, it will finish the current run and output the results in files. Currently, the only viable solutions it produces are programs which always return a constant number. I'm starting to think that the chances of a more advanced working program are astronomically small. Anyway I will keep it running for some time. EDIT: I keep tweaking the algorithm, it's a perfect toy for a geek like me. I once saw a generated program which actually did some random math and didn't always return a constant number. It would be awesome to run it on a few million CPU's at once :). Will keep running it. EDIT: Here's the result of some completely random math. It jumps around and stays at 17 for the rest of the indices. It won't become conscious anytime soon. ![](https://i.stack.imgur.com/E6OLx.png) EDIT: It's getting more complicated. Of course, as you would expect, it looks nothing like the proper digitsum algorithm, but it's trying hard. Look, a computer generated assembly program! ![](https://i.stack.imgur.com/5M9K6.png) [Answer] # C# This might not be completeley what you envisioned, but this is the best I could do right now. (At least with C# and CodeDom). So how it works: 1. It calculates the digitsum base 2 (the base wasn't specified in the statement) 2. It tries to generate an expression with a lot of terms that look like `((i & v1) >> v2)`. These terms will be the genes that will be mutated through the run. 3. The fitness function simply compares the values with a pre-calculated array, and uses the sum of the absolute value of the differences. This means a 0 value means we have arrived to the solution, and the less the value the fitter the solution. The code: ``` using System; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Linq; namespace Evol { class MainClass { const int BASE = 2; static int[] correctValues; static List<Evolution> values = new List<Evolution>(); public static CodeCompileUnit generateCompileUnit(CodeStatementCollection statements) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace samples = new CodeNamespace("CodeGolf"); compileUnit.Namespaces.Add(samples); samples.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration digitSumClass = new CodeTypeDeclaration("DigitSum"); samples.Types.Add(digitSumClass); CodeMemberMethod method = new CodeMemberMethod(); method.Name = "digitsum"; method.Attributes = MemberAttributes.Public | MemberAttributes.Static; method.ReturnType = new CodeTypeReference (typeof(int)); method.Parameters.Add (new CodeParameterDeclarationExpression (typeof(int), "i")); method.Statements.AddRange (statements); digitSumClass.Members.Add(method); return compileUnit; } public static long CompileAndInvoke(CodeStatementCollection statements, bool printCode) { CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add( "System.dll" ); cp.GenerateInMemory = true; CodeGeneratorOptions cgo = new CodeGeneratorOptions (); CodeDomProvider cpd = new CSharpCodeProvider (); CodeCompileUnit cu = generateCompileUnit (statements); StringWriter sw = new StringWriter(); cpd.GenerateCodeFromCompileUnit(cu, sw, cgo); if (printCode) { System.Console.WriteLine (sw.ToString ()); } var result = cpd.CompileAssemblyFromDom (cp, cu); if (result.Errors.Count != 0) { return -1; } else { var assembly = result.CompiledAssembly; var type = assembly.GetType ("CodeGolf.DigitSum"); var method = type.GetMethod ("digitsum"); long fitness = CalcFitness (method); return fitness; } } public static long CalcFitness(MethodInfo method) { long result = 0; for (int i = 0; i < correctValues.Length; i++) { int r = (int)method.Invoke (null, new Object[] { i }); result += Math.Abs (r - correctValues[i]); } return result; } public static CodeStatementCollection generateCodeDomFromString (Term[] terms) { CodeStatementCollection statements = new CodeStatementCollection (); CodeExpression expression = null; foreach (Term term in terms) { CodeExpression inner = new CodeArgumentReferenceExpression ("i"); if (term.and.HasValue) { inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.BitwiseAnd, new CodePrimitiveExpression(term.and.Value)); } if (term.shift.HasValue) { inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(Math.Pow (2, term.shift.Value))); } if (expression == null) { expression = inner; } else { expression = new CodeBinaryOperatorExpression (expression, CodeBinaryOperatorType.Add, inner); } } statements.Add (new CodeMethodReturnStatement (expression)); return statements; } public static void Main (string[] args) { correctValues = new int[10001]; for (int i = 0; i < correctValues.Length; i++) { int result = 0; int num = i; while (num != 0) { result += num % BASE; num /= BASE; } correctValues [i] = result; } values.Add (new Evolution (new Term[] { new Term (null, null) })); Random rnd = new Random (); while (true) { // run old generation foreach (var val in values) { CodeStatementCollection stat = generateCodeDomFromString (val.term); long fitness = CompileAndInvoke (stat, false); val.score = fitness; System.Console.WriteLine ("Fitness: {0}", fitness); } Evolution best = values.Aggregate ((i1, i2) => i1.score < i2.score ? i1 : i2); CodeStatementCollection bestcoll = generateCodeDomFromString (best.term); CompileAndInvoke (bestcoll, true); System.Console.WriteLine ("Best fitness for this run: {0}", best.score); if (best.score == 0) break; // generate new generation List<Evolution> top = values.OrderBy (i => i.score).Take (3).ToList(); values = new List<Evolution> (); foreach (var e in top) { values.Add (e); if (e.term.Length < 16) { Term[] newTerm = new Term[e.term.Length + 1]; for (int i = 0; i < e.term.Length; i++) { newTerm [i] = e.term [i]; } int rrr = rnd.Next (0, 17); newTerm [e.term.Length] = new Term ((int)Math.Pow(2,rrr), rrr); values.Add (new Evolution (newTerm)); } { int r = rnd.Next (0, e.term.Length); Term[] newTerm = (Term[])e.term.Clone (); int rrr = rnd.Next (0, 17); newTerm [r] = new Term ((int)Math.Pow(2,rrr), rrr); values.Add (new Evolution (newTerm)); } } } } public struct Term { public int? and; public int? shift; public Term(int? and, int? shift) { if (and!=0) { this.and = and; } else this.and = null; if (shift!=0) { this.shift = shift; } else this.shift=null; } } public class Evolution { public Term[] term; public long score; public Evolution(Term[] term) { this.term = term; } } } } ``` Tested on OSX with Mono C# compiler version 3.2.6.0. At each iteration it prints the fitness value of the current calculation. At the end it will print the best solution along with its fitness. The loop will run until one of the results have a fitness value of 0. This is how it starts: ``` // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace CodeGolf { using System; public class DigitSum { public static int digitsum(int i) { return i; } } } Best fitness for this run: 49940387 ``` And after a while (takes around 30 minutes), this is how it ends (showing the last and almost last iteration): ``` // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace CodeGolf { using System; public class DigitSum { public static int digitsum(int i) { return ((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 128) / 128)) + ((i & 65536) / 65536)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048)); } } } Best fitness for this run: 4992 Fitness: 4992 Fitness: 7040 Fitness: 4993 Fitness: 4992 Fitness: 0 Fitness: 4992 Fitness: 4992 Fitness: 7496 // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace CodeGolf { using System; public class DigitSum { public static int digitsum(int i) { return (((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 64) / 64)) + ((i & 32768) / 32768)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048)) + ((i & 32768) / 32768)); } } } Best fitness for this run: 0 ``` Notes: 1. CodeDOM doesn't support the left shift operator so instead of `a >> b` I'm using `a / 2^b` 2. The initial iteration is just a `return i;` as required by the problem. 3. In the first few iterations priority is given to adding new terms (genes) to the sum. Later there is more priority in changing values (mutation) in terms randomly. 4. I'm generating terms that look like `i & a >> a` instead of `i & a >> b`, as in the latter case the evolution was simply too slow to be practical. 5. This is also why the solution is limited to finding an answer in the form `return (i&a>>b)+(i&c>>d)+...`, as any other kind (like trying to generate a "proper" code, with loops, assignments, condition checks, etc.) would simply converge too slowly. Also this way it is very easy to define the genes (each of the term), and is very easy to mutate them. 6. This is also the reason why I'm adding the digits in base 2 (the base wasn't specified in the problem statement, so I consider this fine). A base 10 solution would've been just to slow, and also it would've been really hard to define the actual genes. Adding a loop would also mean that you have to manage the running code, and find a possible way to kill it, before it enters a potentially infinite loop. 7. Genes are only mutated, there is no crossover in this solution. I don't know whether adding that would speed up the evolution process or not. 8. The solution is only tested for numbers `0..10000` (if you check the found solution you can see that it won't work for numbers larger than 16384) 9. The whole evolution process [can be checked at this gist.](https://gist.github.com/sztupy/9084074) [Answer] ## Javascript Well, I got some floating point precision issue with my answer - that can probably be solved using a BigDecimal library - when input numbers are larger than `55`. Yes, that's far from `10000` so I don't expect to win but still an interesting method based on [this topic](https://math.stackexchange.com/questions/405609/is-it-possible-to-find-function-that-contains-every-given-point). It compute a [polynomial interpolation] (<http://en.wikipedia.org/wiki/Polynomial_interpolation>) based on a set of points, so it use only multiplication, division and addition, no modulo or bitwise operators. ``` //used to compute real values function correct(i) { var s = i.toString(); var o=0; for (var i=0; i<s.length; i++) { o+=parseInt(s[i]); } return o; } function digitsum(i){return i} //can be replaced by anything like : //function digitsum(i){return (Math.sin(i*i)+2*Math.sqrt(i)))} for (var j=0; j<60; j++) { var p = correct(j+1)-digitsum(j+1); if (p != 0) { var g='Math.round(1'; for (var k=0; k<j+1; k++) { g+='*((i-'+k+')/'+(j+1-k)+')'; } g+=')'; eval(digitsum.toString().replace(/{return (.*)}/, function (m,v) { return "{return "+v+"+"+p+"*"+g+"}"; })); } } console.log(digitsum); ``` Output function : ``` function digitsum(i){return i+-9*Math.round(1*((i-0)/10)*((i-1)/9)*((i-2)/8)*((i-3)/7)*((i-4)/6)*((i-5)/5)*((i-6)/4)*((i-7)/3)*((i-8)/2)*((i-9)/1))+90*Math.round(1*((i-0)/11)*((i-1)/10)*((i-2)/9)*((i-3)/8)*((i-4)/7)*((i-5)/6)*((i-6)/5)*((i-7)/4)*((i-8)/3)*((i-9)/2)*((i-10)/1))+-495*Math.round(1*((i-0)/12)*((i-1)/11)*((i-2)/10)*((i-3)/9)*((i-4)/8)*((i-5)/7)*((i-6)/6)*((i-7)/5)*((i-8)/4)*((i-9)/3)*((i-10)/2)*((i-11)/1))+1980*Math.round(1*((i-0)/13)*((i-1)/12)*((i-2)/11)*((i-3)/10)*((i-4)/9)*((i-5)/8)*((i-6)/7)*((i-7)/6)*((i-8)/5)*((i-9)/4)*((i-10)/3)*((i-11)/2)*((i-12)/1))+-6435*Math.round(1*((i-0)/14)*((i-1)/13)*((i-2)/12)*((i-3)/11)*((i-4)/10)*((i-5)/9)*((i-6)/8)*((i-7)/7)*((i-8)/6)*((i-9)/5)*((i-10)/4)*((i-11)/3)*((i-12)/2)*((i-13)/1))+18018*Math.round(1*((i-0)/15)*((i-1)/14)*((i-2)/13)*((i-3)/12)*((i-4)/11)*((i-5)/10)*((i-6)/9)*((i-7)/8)*((i-8)/7)*((i-9)/6)*((i-10)/5)*((i-11)/4)*((i-12)/3)*((i-13)/2)*((i-14)/1))+-45045*Math.round(1*((i-0)/16)*((i-1)/15)*((i-2)/14)*((i-3)/13)*((i-4)/12)*((i-5)/11)*((i-6)/10)*((i-7)/9)*((i-8)/8)*((i-9)/7)*((i-10)/6)*((i-11)/5)*((i-12)/4)*((i-13)/3)*((i-14)/2)*((i-15)/1))+102960*Math.round(1*((i-0)/17)*((i-1)/16)*((i-2)/15)*((i-3)/14)*((i-4)/13)*((i-5)/12)*((i-6)/11)*((i-7)/10)*((i-8)/9)*((i-9)/8)*((i-10)/7)*((i-11)/6)*((i-12)/5)*((i-13)/4)*((i-14)/3)*((i-15)/2)*((i-16)/1))+-218790*Math.round(1*((i-0)/18)*((i-1)/17)*((i-2)/16)*((i-3)/15)*((i-4)/14)*((i-5)/13)*((i-6)/12)*((i-7)/11)*((i-8)/10)*((i-9)/9)*((i-10)/8)*((i-11)/7)*((i-12)/6)*((i-13)/5)*((i-14)/4)*((i-15)/3)*((i-16)/2)*((i-17)/1))+437580*Math.round(1*((i-0)/19)*((i-1)/18)*((i-2)/17)*((i-3)/16)*((i-4)/15)*((i-5)/14)*((i-6)/13)*((i-7)/12)*((i-8)/11)*((i-9)/10)*((i-10)/9)*((i-11)/8)*((i-12)/7)*((i-13)/6)*((i-14)/5)*((i-15)/4)*((i-16)/3)*((i-17)/2)*((i-18)/1))+-831411*Math.round(1*((i-0)/20)*((i-1)/19)*((i-2)/18)*((i-3)/17)*((i-4)/16)*((i-5)/15)*((i-6)/14)*((i-7)/13)*((i-8)/12)*((i-9)/11)*((i-10)/10)*((i-11)/9)*((i-12)/8)*((i-13)/7)*((i-14)/6)*((i-15)/5)*((i-16)/4)*((i-17)/3)*((i-18)/2)*((i-19)/1))+1511820*Math.round(1*((i-0)/21)*((i-1)/20)*((i-2)/19)*((i-3)/18)*((i-4)/17)*((i-5)/16)*((i-6)/15)*((i-7)/14)*((i-8)/13)*((i-9)/12)*((i-10)/11)*((i-11)/10)*((i-12)/9)*((i-13)/8)*((i-14)/7)*((i-15)/6)*((i-16)/5)*((i-17)/4)*((i-18)/3)*((i-19)/2)*((i-20)/1))+-2647260*Math.round(1*((i-0)/22)*((i-1)/21)*((i-2)/20)*((i-3)/19)*((i-4)/18)*((i-5)/17)*((i-6)/16)*((i-7)/15)*((i-8)/14)*((i-9)/13)*((i-10)/12)*((i-11)/11)*((i-12)/10)*((i-13)/9)*((i-14)/8)*((i-15)/7)*((i-16)/6)*((i-17)/5)*((i-18)/4)*((i-19)/3)*((i-20)/2)*((i-21)/1))+4490640*Math.round(1*((i-0)/23)*((i-1)/22)*((i-2)/21)*((i-3)/20)*((i-4)/19)*((i-5)/18)*((i-6)/17)*((i-7)/16)*((i-8)/15)*((i-9)/14)*((i-10)/13)*((i-11)/12)*((i-12)/11)*((i-13)/10)*((i-14)/9)*((i-15)/8)*((i-16)/7)*((i-17)/6)*((i-18)/5)*((i-19)/4)*((i-20)/3)*((i-21)/2)*((i-22)/1))+-7434405*Math.round(1*((i-0)/24)*((i-1)/23)*((i-2)/22)*((i-3)/21)*((i-4)/20)*((i-5)/19)*((i-6)/18)*((i-7)/17)*((i-8)/16)*((i-9)/15)*((i-10)/14)*((i-11)/13)*((i-12)/12)*((i-13)/11)*((i-14)/10)*((i-15)/9)*((i-16)/8)*((i-17)/7)*((i-18)/6)*((i-19)/5)*((i-20)/4)*((i-21)/3)*((i-22)/2)*((i-23)/1))+12150072*Math.round(1*((i-0)/25)*((i-1)/24)*((i-2)/23)*((i-3)/22)*((i-4)/21)*((i-5)/20)*((i-6)/19)*((i-7)/18)*((i-8)/17)*((i-9)/16)*((i-10)/15)*((i-11)/14)*((i-12)/13)*((i-13)/12)*((i-14)/11)*((i-15)/10)*((i-16)/9)*((i-17)/8)*((i-18)/7)*((i-19)/6)*((i-20)/5)*((i-21)/4)*((i-22)/3)*((i-23)/2)*((i-24)/1))+-19980675*Math.round(1*((i-0)/26)*((i-1)/25)*((i-2)/24)*((i-3)/23)*((i-4)/22)*((i-5)/21)*((i-6)/20)*((i-7)/19)*((i-8)/18)*((i-9)/17)*((i-10)/16)*((i-11)/15)*((i-12)/14)*((i-13)/13)*((i-14)/12)*((i-15)/11)*((i-16)/10)*((i-17)/9)*((i-18)/8)*((i-19)/7)*((i-20)/6)*((i-21)/5)*((i-22)/4)*((i-23)/3)*((i-24)/2)*((i-25)/1))+34041150*Math.round(1*((i-0)/27)*((i-1)/26)*((i-2)/25)*((i-3)/24)*((i-4)/23)*((i-5)/22)*((i-6)/21)*((i-7)/20)*((i-8)/19)*((i-9)/18)*((i-10)/17)*((i-11)/16)*((i-12)/15)*((i-13)/14)*((i-14)/13)*((i-15)/12)*((i-16)/11)*((i-17)/10)*((i-18)/9)*((i-19)/8)*((i-20)/7)*((i-21)/6)*((i-22)/5)*((i-23)/4)*((i-24)/3)*((i-25)/2)*((i-26)/1))+-62162100*Math.round(1*((i-0)/28)*((i-1)/27)*((i-2)/26)*((i-3)/25)*((i-4)/24)*((i-5)/23)*((i-6)/22)*((i-7)/21)*((i-8)/20)*((i-9)/19)*((i-10)/18)*((i-11)/17)*((i-12)/16)*((i-13)/15)*((i-14)/14)*((i-15)/13)*((i-16)/12)*((i-17)/11)*((i-18)/10)*((i-19)/9)*((i-20)/8)*((i-21)/7)*((i-22)/6)*((i-23)/5)*((i-24)/4)*((i-25)/3)*((i-26)/2)*((i-27)/1))+124324200*Math.round(1*((i-0)/29)*((i-1)/28)*((i-2)/27)*((i-3)/26)*((i-4)/25)*((i-5)/24)*((i-6)/23)*((i-7)/22)*((i-8)/21)*((i-9)/20)*((i-10)/19)*((i-11)/18)*((i-12)/17)*((i-13)/16)*((i-14)/15)*((i-15)/14)*((i-16)/13)*((i-17)/12)*((i-18)/11)*((i-19)/10)*((i-20)/9)*((i-21)/8)*((i-22)/7)*((i-23)/6)*((i-24)/5)*((i-25)/4)*((i-26)/3)*((i-27)/2)*((i-28)/1))+-270405144*Math.round(1*((i-0)/30)*((i-1)/29)*((i-2)/28)*((i-3)/27)*((i-4)/26)*((i-5)/25)*((i-6)/24)*((i-7)/23)*((i-8)/22)*((i-9)/21)*((i-10)/20)*((i-11)/19)*((i-12)/18)*((i-13)/17)*((i-14)/16)*((i-15)/15)*((i-16)/14)*((i-17)/13)*((i-18)/12)*((i-19)/11)*((i-20)/10)*((i-21)/9)*((i-22)/8)*((i-23)/7)*((i-24)/6)*((i-25)/5)*((i-26)/4)*((i-27)/3)*((i-28)/2)*((i-29)/1))+620410320*Math.round(1*((i-0)/31)*((i-1)/30)*((i-2)/29)*((i-3)/28)*((i-4)/27)*((i-5)/26)*((i-6)/25)*((i-7)/24)*((i-8)/23)*((i-9)/22)*((i-10)/21)*((i-11)/20)*((i-12)/19)*((i-13)/18)*((i-14)/17)*((i-15)/16)*((i-16)/15)*((i-17)/14)*((i-18)/13)*((i-19)/12)*((i-20)/11)*((i-21)/10)*((i-22)/9)*((i-23)/8)*((i-24)/7)*((i-25)/6)*((i-26)/5)*((i-27)/4)*((i-28)/3)*((i-29)/2)*((i-30)/1))+-1451529585*Math.round(1*((i-0)/32)*((i-1)/31)*((i-2)/30)*((i-3)/29)*((i-4)/28)*((i-5)/27)*((i-6)/26)*((i-7)/25)*((i-8)/24)*((i-9)/23)*((i-10)/22)*((i-11)/21)*((i-12)/20)*((i-13)/19)*((i-14)/18)*((i-15)/17)*((i-16)/16)*((i-17)/15)*((i-18)/14)*((i-19)/13)*((i-20)/12)*((i-21)/11)*((i-22)/10)*((i-23)/9)*((i-24)/8)*((i-25)/7)*((i-26)/6)*((i-27)/5)*((i-28)/4)*((i-29)/3)*((i-30)/2)*((i-31)/1))+3378846240*Math.round(1*((i-0)/33)*((i-1)/32)*((i-2)/31)*((i-3)/30)*((i-4)/29)*((i-5)/28)*((i-6)/27)*((i-7)/26)*((i-8)/25)*((i-9)/24)*((i-10)/23)*((i-11)/22)*((i-12)/21)*((i-13)/20)*((i-14)/19)*((i-15)/18)*((i-16)/17)*((i-17)/16)*((i-18)/15)*((i-19)/14)*((i-20)/13)*((i-21)/12)*((i-22)/11)*((i-23)/10)*((i-24)/9)*((i-25)/8)*((i-26)/7)*((i-27)/6)*((i-28)/5)*((i-29)/4)*((i-30)/3)*((i-31)/2)*((i-32)/1))+-7716754980*Math.round(1*((i-0)/34)*((i-1)/33)*((i-2)/32)*((i-3)/31)*((i-4)/30)*((i-5)/29)*((i-6)/28)*((i-7)/27)*((i-8)/26)*((i-9)/25)*((i-10)/24)*((i-11)/23)*((i-12)/22)*((i-13)/21)*((i-14)/20)*((i-15)/19)*((i-16)/18)*((i-17)/17)*((i-18)/16)*((i-19)/15)*((i-20)/14)*((i-21)/13)*((i-22)/12)*((i-23)/11)*((i-24)/10)*((i-25)/9)*((i-26)/8)*((i-27)/7)*((i-28)/6)*((i-29)/5)*((i-30)/4)*((i-31)/3)*((i-32)/2)*((i-33)/1))+17178273288*Math.round(1*((i-0)/35)*((i-1)/34)*((i-2)/33)*((i-3)/32)*((i-4)/31)*((i-5)/30)*((i-6)/29)*((i-7)/28)*((i-8)/27)*((i-9)/26)*((i-10)/25)*((i-11)/24)*((i-12)/23)*((i-13)/22)*((i-14)/21)*((i-15)/20)*((i-16)/19)*((i-17)/18)*((i-18)/17)*((i-19)/16)*((i-20)/15)*((i-21)/14)*((i-22)/13)*((i-23)/12)*((i-24)/11)*((i-25)/10)*((i-26)/9)*((i-27)/8)*((i-28)/7)*((i-29)/6)*((i-30)/5)*((i-31)/4)*((i-32)/3)*((i-33)/2)*((i-34)/1))+-37189436130*Math.round(1*((i-0)/36)*((i-1)/35)*((i-2)/34)*((i-3)/33)*((i-4)/32)*((i-5)/31)*((i-6)/30)*((i-7)/29)*((i-8)/28)*((i-9)/27)*((i-10)/26)*((i-11)/25)*((i-12)/24)*((i-13)/23)*((i-14)/22)*((i-15)/21)*((i-16)/20)*((i-17)/19)*((i-18)/18)*((i-19)/17)*((i-20)/16)*((i-21)/15)*((i-22)/14)*((i-23)/13)*((i-24)/12)*((i-25)/11)*((i-26)/10)*((i-27)/9)*((i-28)/8)*((i-29)/7)*((i-30)/6)*((i-31)/5)*((i-32)/4)*((i-33)/3)*((i-34)/2)*((i-35)/1))+78299888041*Math.round(1*((i-0)/37)*((i-1)/36)*((i-2)/35)*((i-3)/34)*((i-4)/33)*((i-5)/32)*((i-6)/31)*((i-7)/30)*((i-8)/29)*((i-9)/28)*((i-10)/27)*((i-11)/26)*((i-12)/25)*((i-13)/24)*((i-14)/23)*((i-15)/22)*((i-16)/21)*((i-17)/20)*((i-18)/19)*((i-19)/18)*((i-20)/17)*((i-21)/16)*((i-22)/15)*((i-23)/14)*((i-24)/13)*((i-25)/12)*((i-26)/11)*((i-27)/10)*((i-28)/9)*((i-29)/8)*((i-30)/7)*((i-31)/6)*((i-32)/5)*((i-33)/4)*((i-34)/3)*((i-35)/2)*((i-36)/1))+-160520791904*Math.round(1*((i-0)/38)*((i-1)/37)*((i-2)/36)*((i-3)/35)*((i-4)/34)*((i-5)/33)*((i-6)/32)*((i-7)/31)*((i-8)/30)*((i-9)/29)*((i-10)/28)*((i-11)/27)*((i-12)/26)*((i-13)/25)*((i-14)/24)*((i-15)/23)*((i-16)/22)*((i-17)/21)*((i-18)/20)*((i-19)/19)*((i-20)/18)*((i-21)/17)*((i-22)/16)*((i-23)/15)*((i-24)/14)*((i-25)/13)*((i-26)/12)*((i-27)/11)*((i-28)/10)*((i-29)/9)*((i-30)/8)*((i-31)/7)*((i-32)/6)*((i-33)/5)*((i-34)/4)*((i-35)/3)*((i-36)/2)*((i-37)/1))+321041584713*Math.round(1*((i-0)/39)*((i-1)/38)*((i-2)/37)*((i-3)/36)*((i-4)/35)*((i-5)/34)*((i-6)/33)*((i-7)/32)*((i-8)/31)*((i-9)/30)*((i-10)/29)*((i-11)/28)*((i-12)/27)*((i-13)/26)*((i-14)/25)*((i-15)/24)*((i-16)/23)*((i-17)/22)*((i-18)/21)*((i-19)/20)*((i-20)/19)*((i-21)/18)*((i-22)/17)*((i-23)/16)*((i-24)/15)*((i-25)/14)*((i-26)/13)*((i-27)/12)*((i-28)/11)*((i-29)/10)*((i-30)/9)*((i-31)/8)*((i-32)/7)*((i-33)/6)*((i-34)/5)*((i-35)/4)*((i-36)/3)*((i-37)/2)*((i-38)/1))+-627938339760*Math.round(1*((i-0)/40)*((i-1)/39)*((i-2)/38)*((i-3)/37)*((i-4)/36)*((i-5)/35)*((i-6)/34)*((i-7)/33)*((i-8)/32)*((i-9)/31)*((i-10)/30)*((i-11)/29)*((i-12)/28)*((i-13)/27)*((i-14)/26)*((i-15)/25)*((i-16)/24)*((i-17)/23)*((i-18)/22)*((i-19)/21)*((i-20)/20)*((i-21)/19)*((i-22)/18)*((i-23)/17)*((i-24)/16)*((i-25)/15)*((i-26)/14)*((i-27)/13)*((i-28)/12)*((i-29)/11)*((i-30)/10)*((i-31)/9)*((i-32)/8)*((i-33)/7)*((i-34)/6)*((i-35)/5)*((i-36)/4)*((i-37)/3)*((i-38)/2)*((i-39)/1))+1204809019815*Math.round(1*((i-0)/41)*((i-1)/40)*((i-2)/39)*((i-3)/38)*((i-4)/37)*((i-5)/36)*((i-6)/35)*((i-7)/34)*((i-8)/33)*((i-9)/32)*((i-10)/31)*((i-11)/30)*((i-12)/29)*((i-13)/28)*((i-14)/27)*((i-15)/26)*((i-16)/25)*((i-17)/24)*((i-18)/23)*((i-19)/22)*((i-20)/21)*((i-21)/20)*((i-22)/19)*((i-23)/18)*((i-24)/17)*((i-25)/16)*((i-26)/15)*((i-27)/14)*((i-28)/13)*((i-29)/12)*((i-30)/11)*((i-31)/10)*((i-32)/9)*((i-33)/8)*((i-34)/7)*((i-35)/6)*((i-36)/5)*((i-37)/4)*((i-38)/3)*((i-39)/2)*((i-40)/1))+-2276206770520*Math.round(1*((i-0)/42)*((i-1)/41)*((i-2)/40)*((i-3)/39)*((i-4)/38)*((i-5)/37)*((i-6)/36)*((i-7)/35)*((i-8)/34)*((i-9)/33)*((i-10)/32)*((i-11)/31)*((i-12)/30)*((i-13)/29)*((i-14)/28)*((i-15)/27)*((i-16)/26)*((i-17)/25)*((i-18)/24)*((i-19)/23)*((i-20)/22)*((i-21)/21)*((i-22)/20)*((i-23)/19)*((i-24)/18)*((i-25)/17)*((i-26)/16)*((i-27)/15)*((i-28)/14)*((i-29)/13)*((i-30)/12)*((i-31)/11)*((i-32)/10)*((i-33)/9)*((i-34)/8)*((i-35)/7)*((i-36)/6)*((i-37)/5)*((i-38)/4)*((i-39)/3)*((i-40)/2)*((i-41)/1))+4254673762574*Math.round(1*((i-0)/43)*((i-1)/42)*((i-2)/41)*((i-3)/40)*((i-4)/39)*((i-5)/38)*((i-6)/37)*((i-7)/36)*((i-8)/35)*((i-9)/34)*((i-10)/33)*((i-11)/32)*((i-12)/31)*((i-13)/30)*((i-14)/29)*((i-15)/28)*((i-16)/27)*((i-17)/26)*((i-18)/25)*((i-19)/24)*((i-20)/23)*((i-21)/22)*((i-22)/21)*((i-23)/20)*((i-24)/19)*((i-25)/18)*((i-26)/17)*((i-27)/16)*((i-28)/15)*((i-29)/14)*((i-30)/13)*((i-31)/12)*((i-32)/11)*((i-33)/10)*((i-34)/9)*((i-35)/8)*((i-36)/7)*((i-37)/6)*((i-38)/5)*((i-39)/4)*((i-40)/3)*((i-41)/2)*((i-42)/1))+-7914840120452*Math.round(1*((i-0)/44)*((i-1)/43)*((i-2)/42)*((i-3)/41)*((i-4)/40)*((i-5)/39)*((i-6)/38)*((i-7)/37)*((i-8)/36)*((i-9)/35)*((i-10)/34)*((i-11)/33)*((i-12)/32)*((i-13)/31)*((i-14)/30)*((i-15)/29)*((i-16)/28)*((i-17)/27)*((i-18)/26)*((i-19)/25)*((i-20)/24)*((i-21)/23)*((i-22)/22)*((i-23)/21)*((i-24)/20)*((i-25)/19)*((i-26)/18)*((i-27)/17)*((i-28)/16)*((i-29)/15)*((i-30)/14)*((i-31)/13)*((i-32)/12)*((i-33)/11)*((i-34)/10)*((i-35)/9)*((i-36)/8)*((i-37)/7)*((i-38)/6)*((i-39)/5)*((i-40)/4)*((i-41)/3)*((i-42)/2)*((i-43)/1))+14755713366633*Math.round(1*((i-0)/45)*((i-1)/44)*((i-2)/43)*((i-3)/42)*((i-4)/41)*((i-5)/40)*((i-6)/39)*((i-7)/38)*((i-8)/37)*((i-9)/36)*((i-10)/35)*((i-11)/34)*((i-12)/33)*((i-13)/32)*((i-14)/31)*((i-15)/30)*((i-16)/29)*((i-17)/28)*((i-18)/27)*((i-19)/26)*((i-20)/25)*((i-21)/24)*((i-22)/23)*((i-23)/22)*((i-24)/21)*((i-25)/20)*((i-26)/19)*((i-27)/18)*((i-28)/17)*((i-29)/16)*((i-30)/15)*((i-31)/14)*((i-32)/13)*((i-33)/12)*((i-34)/11)*((i-35)/10)*((i-36)/9)*((i-37)/8)*((i-38)/7)*((i-39)/6)*((i-40)/5)*((i-41)/4)*((i-42)/3)*((i-43)/2)*((i-44)/1))+-27776520662160*Math.round(1*((i-0)/46)*((i-1)/45)*((i-2)/44)*((i-3)/43)*((i-4)/42)*((i-5)/41)*((i-6)/40)*((i-7)/39)*((i-8)/38)*((i-9)/37)*((i-10)/36)*((i-11)/35)*((i-12)/34)*((i-13)/33)*((i-14)/32)*((i-15)/31)*((i-16)/30)*((i-17)/29)*((i-18)/28)*((i-19)/27)*((i-20)/26)*((i-21)/25)*((i-22)/24)*((i-23)/23)*((i-24)/22)*((i-25)/21)*((i-26)/20)*((i-27)/19)*((i-28)/18)*((i-29)/17)*((i-30)/16)*((i-31)/15)*((i-32)/14)*((i-33)/13)*((i-34)/12)*((i-35)/11)*((i-36)/10)*((i-37)/9)*((i-38)/8)*((i-39)/7)*((i-40)/6)*((i-41)/5)*((i-42)/4)*((i-43)/3)*((i-44)/2)*((i-45)/1))+53164054207611*Math.round(1*((i-0)/47)*((i-1)/46)*((i-2)/45)*((i-3)/44)*((i-4)/43)*((i-5)/42)*((i-6)/41)*((i-7)/40)*((i-8)/39)*((i-9)/38)*((i-10)/37)*((i-11)/36)*((i-12)/35)*((i-13)/34)*((i-14)/33)*((i-15)/32)*((i-16)/31)*((i-17)/30)*((i-18)/29)*((i-19)/28)*((i-20)/27)*((i-21)/26)*((i-22)/25)*((i-23)/24)*((i-24)/23)*((i-25)/22)*((i-26)/21)*((i-27)/20)*((i-28)/19)*((i-29)/18)*((i-30)/17)*((i-31)/16)*((i-32)/15)*((i-33)/14)*((i-34)/13)*((i-35)/12)*((i-36)/11)*((i-37)/10)*((i-38)/9)*((i-39)/8)*((i-40)/7)*((i-41)/6)*((i-42)/5)*((i-43)/4)*((i-44)/3)*((i-45)/2)*((i-46)/1))+-103975831339140*Math.round(1*((i-0)/48)*((i-1)/47)*((i-2)/46)*((i-3)/45)*((i-4)/44)*((i-5)/43)*((i-6)/42)*((i-7)/41)*((i-8)/40)*((i-9)/39)*((i-10)/38)*((i-11)/37)*((i-12)/36)*((i-13)/35)*((i-14)/34)*((i-15)/33)*((i-16)/32)*((i-17)/31)*((i-18)/30)*((i-19)/29)*((i-20)/28)*((i-21)/27)*((i-22)/26)*((i-23)/25)*((i-24)/24)*((i-25)/23)*((i-26)/22)*((i-27)/21)*((i-28)/20)*((i-29)/19)*((i-30)/18)*((i-31)/17)*((i-32)/16)*((i-33)/15)*((i-34)/14)*((i-35)/13)*((i-36)/12)*((i-37)/11)*((i-38)/10)*((i-39)/9)*((i-40)/8)*((i-41)/7)*((i-42)/6)*((i-43)/5)*((i-44)/4)*((i-45)/3)*((i-46)/2)*((i-47)/1))+208138306632137*Math.round(1*((i-0)/49)*((i-1)/48)*((i-2)/47)*((i-3)/46)*((i-4)/45)*((i-5)/44)*((i-6)/43)*((i-7)/42)*((i-8)/41)*((i-9)/40)*((i-10)/39)*((i-11)/38)*((i-12)/37)*((i-13)/36)*((i-14)/35)*((i-15)/34)*((i-16)/33)*((i-17)/32)*((i-18)/31)*((i-19)/30)*((i-20)/29)*((i-21)/28)*((i-22)/27)*((i-23)/26)*((i-24)/25)*((i-25)/24)*((i-26)/23)*((i-27)/22)*((i-28)/21)*((i-29)/20)*((i-30)/19)*((i-31)/18)*((i-32)/17)*((i-33)/16)*((i-34)/15)*((i-35)/14)*((i-36)/13)*((i-37)/12)*((i-38)/11)*((i-39)/10)*((i-40)/9)*((i-41)/8)*((i-42)/7)*((i-43)/6)*((i-44)/5)*((i-45)/4)*((i-46)/3)*((i-47)/2)*((i-48)/1))+-425620349055645*Math.round(1*((i-0)/50)*((i-1)/49)*((i-2)/48)*((i-3)/47)*((i-4)/46)*((i-5)/45)*((i-6)/44)*((i-7)/43)*((i-8)/42)*((i-9)/41)*((i-10)/40)*((i-11)/39)*((i-12)/38)*((i-13)/37)*((i-14)/36)*((i-15)/35)*((i-16)/34)*((i-17)/33)*((i-18)/32)*((i-19)/31)*((i-20)/30)*((i-21)/29)*((i-22)/28)*((i-23)/27)*((i-24)/26)*((i-25)/25)*((i-26)/24)*((i-27)/23)*((i-28)/22)*((i-29)/21)*((i-30)/20)*((i-31)/19)*((i-32)/18)*((i-33)/17)*((i-34)/16)*((i-35)/15)*((i-36)/14)*((i-37)/13)*((i-38)/12)*((i-39)/11)*((i-40)/10)*((i-41)/9)*((i-42)/8)*((i-43)/7)*((i-44)/6)*((i-45)/5)*((i-46)/4)*((i-47)/3)*((i-48)/2)*((i-49)/1))+884722839970606*Math.round(1*((i-0)/51)*((i-1)/50)*((i-2)/49)*((i-3)/48)*((i-4)/47)*((i-5)/46)*((i-6)/45)*((i-7)/44)*((i-8)/43)*((i-9)/42)*((i-10)/41)*((i-11)/40)*((i-12)/39)*((i-13)/38)*((i-14)/37)*((i-15)/36)*((i-16)/35)*((i-17)/34)*((i-18)/33)*((i-19)/32)*((i-20)/31)*((i-21)/30)*((i-22)/29)*((i-23)/28)*((i-24)/27)*((i-25)/26)*((i-26)/25)*((i-27)/24)*((i-28)/23)*((i-29)/22)*((i-30)/21)*((i-31)/20)*((i-32)/19)*((i-33)/18)*((i-34)/17)*((i-35)/16)*((i-36)/15)*((i-37)/14)*((i-38)/13)*((i-39)/12)*((i-40)/11)*((i-41)/10)*((i-42)/9)*((i-43)/8)*((i-44)/7)*((i-45)/6)*((i-46)/5)*((i-47)/4)*((i-48)/3)*((i-49)/2)*((i-50)/1))+-1857183748827153*Math.round(1*((i-0)/52)*((i-1)/51)*((i-2)/50)*((i-3)/49)*((i-4)/48)*((i-5)/47)*((i-6)/46)*((i-7)/45)*((i-8)/44)*((i-9)/43)*((i-10)/42)*((i-11)/41)*((i-12)/40)*((i-13)/39)*((i-14)/38)*((i-15)/37)*((i-16)/36)*((i-17)/35)*((i-18)/34)*((i-19)/33)*((i-20)/32)*((i-21)/31)*((i-22)/30)*((i-23)/29)*((i-24)/28)*((i-25)/27)*((i-26)/26)*((i-27)/25)*((i-28)/24)*((i-29)/23)*((i-30)/22)*((i-31)/21)*((i-32)/20)*((i-33)/19)*((i-34)/18)*((i-35)/17)*((i-36)/16)*((i-37)/15)*((i-38)/14)*((i-39)/13)*((i-40)/12)*((i-41)/11)*((i-42)/10)*((i-43)/9)*((i-44)/8)*((i-45)/7)*((i-46)/6)*((i-47)/5)*((i-48)/4)*((i-49)/3)*((i-50)/2)*((i-51)/1))+3909404796652936*Math.round(1*((i-0)/53)*((i-1)/52)*((i-2)/51)*((i-3)/50)*((i-4)/49)*((i-5)/48)*((i-6)/47)*((i-7)/46)*((i-8)/45)*((i-9)/44)*((i-10)/43)*((i-11)/42)*((i-12)/41)*((i-13)/40)*((i-14)/39)*((i-15)/38)*((i-16)/37)*((i-17)/36)*((i-18)/35)*((i-19)/34)*((i-20)/33)*((i-21)/32)*((i-22)/31)*((i-23)/30)*((i-24)/29)*((i-25)/28)*((i-26)/27)*((i-27)/26)*((i-28)/25)*((i-29)/24)*((i-30)/23)*((i-31)/22)*((i-32)/21)*((i-33)/20)*((i-34)/19)*((i-35)/18)*((i-36)/17)*((i-37)/16)*((i-38)/15)*((i-39)/14)*((i-40)/13)*((i-41)/12)*((i-42)/11)*((i-43)/10)*((i-44)/9)*((i-45)/8)*((i-46)/7)*((i-47)/6)*((i-48)/5)*((i-49)/4)*((i-50)/3)*((i-51)/2)*((i-52)/1))+-8195615777370807*Math.round(1*((i-0)/54)*((i-1)/53)*((i-2)/52)*((i-3)/51)*((i-4)/50)*((i-5)/49)*((i-6)/48)*((i-7)/47)*((i-8)/46)*((i-9)/45)*((i-10)/44)*((i-11)/43)*((i-12)/42)*((i-13)/41)*((i-14)/40)*((i-15)/39)*((i-16)/38)*((i-17)/37)*((i-18)/36)*((i-19)/35)*((i-20)/34)*((i-21)/33)*((i-22)/32)*((i-23)/31)*((i-24)/30)*((i-25)/29)*((i-26)/28)*((i-27)/27)*((i-28)/26)*((i-29)/25)*((i-30)/24)*((i-31)/23)*((i-32)/22)*((i-33)/21)*((i-34)/20)*((i-35)/19)*((i-36)/18)*((i-37)/17)*((i-38)/16)*((i-39)/15)*((i-40)/14)*((i-41)/13)*((i-42)/12)*((i-43)/11)*((i-44)/10)*((i-45)/9)*((i-46)/8)*((i-47)/7)*((i-48)/6)*((i-49)/5)*((i-50)/4)*((i-51)/3)*((i-52)/2)*((i-53)/1))+16994979589974346*Math.round(1*((i-0)/55)*((i-1)/54)*((i-2)/53)*((i-3)/52)*((i-4)/51)*((i-5)/50)*((i-6)/49)*((i-7)/48)*((i-8)/47)*((i-9)/46)*((i-10)/45)*((i-11)/44)*((i-12)/43)*((i-13)/42)*((i-14)/41)*((i-15)/40)*((i-16)/39)*((i-17)/38)*((i-18)/37)*((i-19)/36)*((i-20)/35)*((i-21)/34)*((i-22)/33)*((i-23)/32)*((i-24)/31)*((i-25)/30)*((i-26)/29)*((i-27)/28)*((i-28)/27)*((i-29)/26)*((i-30)/25)*((i-31)/24)*((i-32)/23)*((i-33)/22)*((i-34)/21)*((i-35)/20)*((i-36)/19)*((i-37)/18)*((i-38)/17)*((i-39)/16)*((i-40)/15)*((i-41)/14)*((i-42)/13)*((i-43)/12)*((i-44)/11)*((i-45)/10)*((i-46)/9)*((i-47)/8)*((i-48)/7)*((i-49)/6)*((i-50)/5)*((i-51)/4)*((i-52)/3)*((i-53)/2)*((i-54)/1))+-34598925396029428*Math.round(1*((i-0)/56)*((i-1)/55)*((i-2)/54)*((i-3)/53)*((i-4)/52)*((i-5)/51)*((i-6)/50)*((i-7)/49)*((i-8)/48)*((i-9)/47)*((i-10)/46)*((i-11)/45)*((i-12)/44)*((i-13)/43)*((i-14)/42)*((i-15)/41)*((i-16)/40)*((i-17)/39)*((i-18)/38)*((i-19)/37)*((i-20)/36)*((i-21)/35)*((i-22)/34)*((i-23)/33)*((i-24)/32)*((i-25)/31)*((i-26)/30)*((i-27)/29)*((i-28)/28)*((i-29)/27)*((i-30)/26)*((i-31)/25)*((i-32)/24)*((i-33)/23)*((i-34)/22)*((i-35)/21)*((i-36)/20)*((i-37)/19)*((i-38)/18)*((i-39)/17)*((i-40)/16)*((i-41)/15)*((i-42)/14)*((i-43)/13)*((i-44)/12)*((i-45)/11)*((i-46)/10)*((i-47)/9)*((i-48)/8)*((i-49)/7)*((i-50)/6)*((i-51)/5)*((i-52)/4)*((i-53)/3)*((i-54)/2)*((i-55)/1))+68349348631526670*Math.round(1*((i-0)/57)*((i-1)/56)*((i-2)/55)*((i-3)/54)*((i-4)/53)*((i-5)/52)*((i-6)/51)*((i-7)/50)*((i-8)/49)*((i-9)/48)*((i-10)/47)*((i-11)/46)*((i-12)/45)*((i-13)/44)*((i-14)/43)*((i-15)/42)*((i-16)/41)*((i-17)/40)*((i-18)/39)*((i-19)/38)*((i-20)/37)*((i-21)/36)*((i-22)/35)*((i-23)/34)*((i-24)/33)*((i-25)/32)*((i-26)/31)*((i-27)/30)*((i-28)/29)*((i-29)/28)*((i-30)/27)*((i-31)/26)*((i-32)/25)*((i-33)/24)*((i-34)/23)*((i-35)/22)*((i-36)/21)*((i-37)/20)*((i-38)/19)*((i-39)/18)*((i-40)/17)*((i-41)/16)*((i-42)/15)*((i-43)/14)*((i-44)/13)*((i-45)/12)*((i-46)/11)*((i-47)/10)*((i-48)/9)*((i-49)/8)*((i-50)/7)*((i-51)/6)*((i-52)/5)*((i-53)/4)*((i-54)/3)*((i-55)/2)*((i-56)/1))+-126849859681465840*Math.round(1*((i-0)/58)*((i-1)/57)*((i-2)/56)*((i-3)/55)*((i-4)/54)*((i-5)/53)*((i-6)/52)*((i-7)/51)*((i-8)/50)*((i-9)/49)*((i-10)/48)*((i-11)/47)*((i-12)/46)*((i-13)/45)*((i-14)/44)*((i-15)/43)*((i-16)/42)*((i-17)/41)*((i-18)/40)*((i-19)/39)*((i-20)/38)*((i-21)/37)*((i-22)/36)*((i-23)/35)*((i-24)/34)*((i-25)/33)*((i-26)/32)*((i-27)/31)*((i-28)/30)*((i-29)/29)*((i-30)/28)*((i-31)/27)*((i-32)/26)*((i-33)/25)*((i-34)/24)*((i-35)/23)*((i-36)/22)*((i-37)/21)*((i-38)/20)*((i-39)/19)*((i-40)/18)*((i-41)/17)*((i-42)/16)*((i-43)/15)*((i-44)/14)*((i-45)/13)*((i-46)/12)*((i-47)/11)*((i-48)/10)*((i-49)/9)*((i-50)/8)*((i-51)/7)*((i-52)/6)*((i-53)/5)*((i-54)/4)*((i-55)/3)*((i-56)/2)*((i-57)/1))+189776303470473200*Math.round(1*((i-0)/59)*((i-1)/58)*((i-2)/57)*((i-3)/56)*((i-4)/55)*((i-5)/54)*((i-6)/53)*((i-7)/52)*((i-8)/51)*((i-9)/50)*((i-10)/49)*((i-11)/48)*((i-12)/47)*((i-13)/46)*((i-14)/45)*((i-15)/44)*((i-16)/43)*((i-17)/42)*((i-18)/41)*((i-19)/40)*((i-20)/39)*((i-21)/38)*((i-22)/37)*((i-23)/36)*((i-24)/35)*((i-25)/34)*((i-26)/33)*((i-27)/32)*((i-28)/31)*((i-29)/30)*((i-30)/29)*((i-31)/28)*((i-32)/27)*((i-33)/26)*((i-34)/25)*((i-35)/24)*((i-36)/23)*((i-37)/22)*((i-38)/21)*((i-39)/20)*((i-40)/19)*((i-41)/18)*((i-42)/17)*((i-43)/16)*((i-44)/15)*((i-45)/14)*((i-46)/13)*((i-47)/12)*((i-48)/11)*((i-49)/10)*((i-50)/9)*((i-51)/8)*((i-52)/7)*((i-53)/6)*((i-54)/5)*((i-55)/4)*((i-56)/3)*((i-57)/2)*((i-58)/1))+51028516348018696*Math.round(1*((i-0)/60)*((i-1)/59)*((i-2)/58)*((i-3)/57)*((i-4)/56)*((i-5)/55)*((i-6)/54)*((i-7)/53)*((i-8)/52)*((i-9)/51)*((i-10)/50)*((i-11)/49)*((i-12)/48)*((i-13)/47)*((i-14)/46)*((i-15)/45)*((i-16)/44)*((i-17)/43)*((i-18)/42)*((i-19)/41)*((i-20)/40)*((i-21)/39)*((i-22)/38)*((i-23)/37)*((i-24)/36)*((i-25)/35)*((i-26)/34)*((i-27)/33)*((i-28)/32)*((i-29)/31)*((i-30)/30)*((i-31)/29)*((i-32)/28)*((i-33)/27)*((i-34)/26)*((i-35)/25)*((i-36)/24)*((i-37)/23)*((i-38)/22)*((i-39)/21)*((i-40)/20)*((i-41)/19)*((i-42)/18)*((i-43)/17)*((i-44)/16)*((i-45)/15)*((i-46)/14)*((i-47)/13)*((i-48)/12)*((i-49)/11)*((i-50)/10)*((i-51)/9)*((i-52)/8)*((i-53)/7)*((i-54)/6)*((i-55)/5)*((i-56)/4)*((i-57)/3)*((i-58)/2)*((i-59)/1))} ``` This polynomial function (simplified to degree 25 and without rounding) plotted, look at values for whole numbers (readable for [6;19]) : > > ![enter image description here](https://i.stack.imgur.com/QIJZB.png) > > > Tests : ``` for (var i=0; i<60; i++) { console.log(i + ' : ' + digitsum(i)) } 0 : 0 1 : 1 2 : 2 3 : 3 4 : 4 5 : 5 6 : 6 7 : 7 8 : 8 9 : 9 10 : 1 11 : 2 12 : 3 13 : 4 14 : 5 15 : 6 16 : 7 17 : 8 18 : 9 19 : 10 20 : 2 21 : 3 22 : 4 23 : 5 24 : 6 25 : 7 26 : 8 27 : 9 28 : 10 29 : 11 30 : 3 31 : 4 32 : 5 33 : 6 34 : 7 35 : 8 36 : 9 37 : 10 38 : 11 39 : 12 40 : 4 41 : 5 42 : 6 43 : 7 44 : 8 45 : 9 46 : 10 47 : 11 48 : 12 49 : 13 50 : 5 51 : 6 52 : 7 53 : 8 54 : 9 55 : 10 56 : 12 //precision issue starts here 57 : 16 58 : 16 59 : 0 ``` ]
[Question] [ The goal of a [rosetta-stone](/questions/tagged/rosetta-stone "show questions tagged 'rosetta-stone'") challenge is to write solutions in as many languages as possible. Show off your programming multilingualism! In this challenge, you will create a program that will generate spam messages, given an input seed-text. For example, given the input ``` [Thank you/Wow/Great], this [blog/post/writing] [gives/provides/delivers] [great/excellent/wonderful/superior] [content/information/data]. You [may/could] [find/get/retrieve] [similar/related] [content/information/data] at spammysite.com. ``` A possible output could be ``` Thank you, this writing delivers excellent data. You may find similar content at spammysite.com. ``` (idea from <https://security.stackexchange.com/q/37436/29804>) There's a catch, though! You will also have to output a program in a *different* language. This program, when run, will also output the spam text and a program in a different language, which will also output the spam text and a program in a different language... Your score will be `character count / (number of languages ^ 2)`. For example, I could have a Ruby program. It would take the input seed-text as input, and output the random spam text and a Python program. Running this Python program (with no input), it would output another random spam text and a Perl program. Running this Perl program (no input), it would output another random spam text. In this example, my score would be the length of the original Ruby program divided by 9 (I have 3 languages, and 3 ^ 2 is 9). Other miscellaneous things: * You must use at least 2 different programming languages. * Please list each program that is output. This way if someone doesn't have all of the languages, they can still see their sources. You may use this short example text: `[Please/Kindly] [visit/see] my [site/blog].`, or you may just use a placeholder (like `{insert text here}`). * You may assume that there will be no non-alphanumeric characters except `[]/.,`, to simplify some things. * Different versions of languages do not count as different languages (ex. Python 2 == Python 3). * It must be fully random, i.e. not predictable and outputting a different combination every run. It must also be able to output every combination in an arbitrary amount of runs. * Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") as well as [rosetta-stone](/questions/tagged/rosetta-stone "show questions tagged 'rosetta-stone'"), the shortest overall score (`charcount / (langs ^ 2)`) will win. [Answer] # PHP 5.5 -> Ruby 2.0 -> Python 2.7 -> Lua -> C# -> Java -> PdfTeX -> GolfScript 855 / 8^2 = 13.359375 The main ideas were: 1. Instead of actually creating the logic to create the n+1th language in all programming languages do this only one time, and only use the basic random and stdout writing facilities of each programming language 2. To shorten the template generator, just compress it with zLib. Make this generator the second language 3. Use PHP as the first language, as it has built-in zLib decompressor So the initial code is: ``` <?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\[(.*?)\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x).gzuncompress("BINARY_DATA")."__END__\n".$x; ``` Where `BINARY_DATA` is the gzcompressed version of the template generator (e.g. the result of the php code, which is the ruby version) The complete initial code in base64 (should be 855 bytes after decoding): ``` PD9waHAgJHg9ZmlsZV9nZXRfY29udGVudHMoInBocDovL3N0ZGluIik7ZWNobyBw cmVnX3JlcGxhY2VfY2FsbGJhY2soIi9cWyguKj8pXF0vIixmdW5jdGlvbigkbSl7 JHI9ZXhwbG9kZSgiLyIsJG1bMV0pO3JldHVybiAkclthcnJheV9yYW5kKCRyKV07 fSwkeCkuZ3p1bmNvbXByZXNzKCJ42o2UwXKbMBCG7zyFZj0doElV55BLiNJmmump 7aHpTA+Yg4xErA6SGCQSZ4jevZIBx3biTHywzO6y/7+fYRm5uf5zjVtOGS5XWjbY NLWwSZzHKVx4OTa06Z/oE51iRZw6XFzV1FquXiQ/+2TEMKflKsSbViiLfFx4OTbK puYuajpr0OUlBDmIoqrVErVUMX8I2ejWXCIvL0oejVfm0USznk0y4Fx4YWaxsUx3 Fj+0wvJkKE9mPcVCmYaX1qUpuI+wUODlgvzwjeI4XHg5NtSu8CBnOGeJNthcbsmT NN0ToWSnHbatx1DEp3Hv/GyZ0KMyzXfaJWen4Z6aqzu7cmmRZvseknQ8c0JyT2FZ ixKVNTUGUdRPAWOp9ce9Fgz9pEIlqc/dPhrLJf49UGqJ4g9oL1x4OTak2a79Jfl0 JXs5eiHk7AuM5d+0Mrrm+O/G/8zXVKI19hlcXAYXICqUtPgXX9sb7V15OJdzfJ72 R3uYlah2ezheG97DyTKXxQk4D1wiW+YUs64pJiRceGFm9fohFA+THM19hTd5ycDr 1nrId3mBaHtnArx/9J7izop6n99h+N0Iw4M3/JELeAlwATsIlUf4vdbUHhA8bLHP L7R4P8FtXHhhZloNI6wJUMjeGGS0fIFgMX5EpTp5Pp9fTYGGVZ0SlW4l4/eCWn42 n8/R1qqb6oJLNLmcgpXwbtdkjU1XXHg5Ntn0RlxcvULQW17AYnsj4xWafuvG+lEc 6mf9dnD3IVQHvgjgDQxceDAwLyi8audAq3e+MR3g+O7gXHgwMJ4fxgPMR1TZ8zLc yiDIw17YJFx4OTZPEPuBXFwMG4FiZ2GEJUJceDAw+dHiEB1cXIx1x4zAdoTlI98U uciNR1QQ4ndQ5HdeFFZt9B9+DwFHIikuIl9fRU5EX19cbiIuJHg7 ``` Let's go through all of the languages with the test input string `[Thank you/Wow/Great], this is [awesome/wonderful].` # PHP ``` $ cat ti2 | php a.php Great, this is wonderful. d=DATA.read.chomp.split('[').map{|a|a.split(']')}.flatten.map{|a|a.split('/')} d.each{|a|print a.sample} puts <<"DATA" from random import choice import sys #{d.map{|a|"sys.stdout.write(choice(#{a.inspect}))"}*"\n"} print print '''math.randomseed(os.time()) #{d.map{|a|"a=#{a.inspect.tr('[]','{}')};io.write(a[math.random(1,#{a.length})]);"}*"\n"} print() print([==[ public class a { public static void Main() { System.Random r=new System.Random(); #{d.map{|a|b=->m{m.length==1?"System.Console.Write(#{m.first.inspect});":"if (r.NextDouble()<0.5){System.Console.Write(#{m.shift.inspect});}else{"+b[m]+"};"};b[a.dup]}*"\n"} System.Console.WriteLine(); System.Console.WriteLine(@"class a { public static void main(String[] args) { java.util.Random r=new java.util.Random(); #{d.map{|a|b=->m{m.length==1?"System.out.print(\"#{m.first.inspect}\");":"if (r.nextFloat()<0.5){System.out.print(\"#{m.shift.inspect}\");}else{"+b[m]+"};"};b[a.dup]}*"\n"} System.out.println(); #{x="a";d.map{|a|b=->m{m.length==1?m.first: "\\\\\\\\ifnum500>\\\\\\\\pdfuniformdeviate1000 #{m.shift}\\\\\\\\else "+b[m]+"\\\\\\\\fi"};x=x.succ;a.length>1?"System.out.println(\"\"\\\\\\\\def \\\\\\\\opt#{x} {#{b[a.dup]}}%\"\");": ""}*"\n"} System.out.println(""#{x="a";d.map{|a|x=x.succ;a.length>1?"\\\\\\\\opt#{x}{}": a.first}*""}""); System.out.println(); System.out.println(""#{d.map{|a|a.length>1? "[#{a.map{|b|"'#{b}'"}*""}]#{a.length}rand=" : "'#{a.first}'"}*""}""); System.out.println(""\\\\\\\\bye""); } }"); } } ]==]); ''' DATA __END__ [Thank you/Wow/Great], this is [awesome/wonderful]. ``` # Ruby ``` $ ruby a.rb Great, this is awesome. from random import choice import sys sys.stdout.write(choice(["Thank you", "Wow", "Great"])) sys.stdout.write(choice([", this is "])) sys.stdout.write(choice(["awesome", "wonderful"])) sys.stdout.write(choice(["."])) print print '''math.randomseed(os.time()) a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]); a={", this is "};io.write(a[math.random(1,1)]); a={"awesome", "wonderful"};io.write(a[math.random(1,2)]); a={"."};io.write(a[math.random(1,1)]); print() print([==[ public class a { public static void Main() { System.Random r=new System.Random(); if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};}; System.Console.Write(", this is "); if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");}; System.Console.Write("."); System.Console.WriteLine(); System.Console.WriteLine(@"class a { public static void main(String[] args) { java.util.Random r=new java.util.Random(); if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};}; System.out.print("", this is ""); if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");}; System.out.print("".""); System.out.println(); System.out.println(""\\\\def \\\\optb {\\\\ifnum500>\\\\pdfuniformdeviate1000 Thank you\\\\else \\\\ifnum500>\\\\pdfuniformdeviate1000 Wow\\\\else Great\\\\fi\\\\fi}%""); System.out.println(""\\\\def \\\\optd {\\\\ifnum500>\\\\pdfuniformdeviate1000 awesome\\\\else wonderful\\\\fi}%""); System.out.println(""\\\\optb{}, this is \\\\optd{}.""); System.out.println(); System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'""); System.out.println(""\\\\bye""); } }"); } } ]==]); ''' ``` # Python ``` $ python a.py Great, this is wonderful. math.randomseed(os.time()) a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]); a={", this is "};io.write(a[math.random(1,1)]); a={"awesome", "wonderful"};io.write(a[math.random(1,2)]); a={"."};io.write(a[math.random(1,1)]); print() print([==[ public class a { public static void Main() { System.Random r=new System.Random(); if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};}; System.Console.Write(", this is "); if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");}; System.Console.Write("."); System.Console.WriteLine(); System.Console.WriteLine(@"class a { public static void main(String[] args) { java.util.Random r=new java.util.Random(); if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};}; System.out.print("", this is ""); if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");}; System.out.print("".""); System.out.println(); System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%""); System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%""); System.out.println(""\\optb{}, this is \\optd{}.""); System.out.println(); System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'""); System.out.println(""\\bye""); } }"); } } ]==]); ``` # Lua ``` $ lua a.lua Great, this is wonderful. public class a { public static void Main() { System.Random r=new System.Random(); if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};}; System.Console.Write(", this is "); if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");}; System.Console.Write("."); System.Console.WriteLine(); System.Console.WriteLine(@"class a { public static void main(String[] args) { java.util.Random r=new java.util.Random(); if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};}; System.out.print("", this is ""); if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");}; System.out.print("".""); System.out.println(); System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%""); System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%""); System.out.println(""\\optb{}, this is \\optd{}.""); System.out.println(); System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'""); System.out.println(""\\bye""); } }"); } } ``` # C# ``` $ mcs a.cs $ mono a.exe Thank you, this is wonderful. class a { public static void main(String[] args) { java.util.Random r=new java.util.Random(); if (r.nextFloat()<0.5){System.out.print("Thank you");}else{if (r.nextFloat()<0.5){System.out.print("Wow");}else{System.out.print("Great");};}; System.out.print(", this is "); if (r.nextFloat()<0.5){System.out.print("awesome");}else{System.out.print("wonderful");}; System.out.print("."); System.out.println(); System.out.println("\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"); System.out.println("\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"); System.out.println("\\optb{}, this is \\optd{}."); System.out.println(); System.out.println("['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"); System.out.println("\\bye"); } } ``` # Java ``` $ javac a.java $ java a Wow, this is wonderful. \def \optb {\ifnum500>\pdfuniformdeviate1000 Thank you\else \ifnum500>\pdfuniformdeviate1000 Wow\else Great\fi\fi}% \def \optd {\ifnum500>\pdfuniformdeviate1000 awesome\else wonderful\fi}% \optb{}, this is \optd{}. ['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.' \bye ``` # PdfTeX (the code will be inside a.pdf instead of the stdout. I hope this is still okay) ``` $ pdftex a.tex This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012) restricted \write18 enabled. entering extended mode (./a.tex [1{/usr/local/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.ma p}] )</usr/local/texlive/2012/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.p fb> Output written on a.pdf (1 page, 15967 bytes). Transcript written on a.log. $ open a.pdf ``` Result: ![pdftex result](https://i.stack.imgur.com/WM4se.png) In text: ``` Great, this is wonderful. ['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.' ``` # Golfscript ``` $ ruby golfscript.rb a.gs Wow, this is awesome. ``` # Notes 1. It seems PHP is quite forgiving with binary data in string literals, except for hex codes AF and 96. Don't ask why. 2. I could've probably added perl and C++11 code as well easily (as they both support raw string literals), but 8 is a more round number than 10 :) 3. The distribution of values is not uniform, as the first element comes more often than later ones. According to comments this should be okay. 4. The initial code was actually generated using the following PHP 5.5 code. `orig.rb` is actually the same as the Ruby code without the footer (`__END__` and the appended data afterwards) `generator.php`: ``` <?php $d=file_get_contents('orig.rb'); $dc = gzcompress($d,9); echo '<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\\[(.*?)\\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x)'; ?><?php echo ".gzuncompress(\""; for ($i=0;$i<strlen($dc);$i++) { switch($dc[$i]) { case '"': echo "\\\"";break; case "\n": echo "\\n";break; case '\\': echo "\\\\";break; case "\x00":case "\xaf":case "\x96": echo sprintf("\\x%02x",ord($dc[$i])); break; default: echo $dc[$i]; } } echo "\").\"__END__\\n\".\$x;"; ``` (you can potentially use this code to zLib encompress PHP solutions for other challenges) [Answer] # Ruby 1.9 -> Perl 5 -> Python 2, 227/9 = 25.22222... ``` $><<(g=gets).gsub(/\[(.*?)\]/){$1.split(?/).sample}+"say'#{g.chop}'=~s|\\[(.*?)\\]|@a=split'/',$1;$a[rand@a]|reg;say'import re,random;print re.sub(\"\\[(.*?)\\]\",lambda m:random.choice(m.group(1).split(\"/\")),\"#{g.chop}\")'" ``` Output for `[Please/Kindly] [visit/see] my [site/blog].`: ``` Please see my site. say'[Please/Kindly] [visit/see] my [site/blog].'=~s|\[(.*?)\]|@a=split'/',$1;$a[rand@a]|reg;say'import re,random;print re.sub("\[(.*?)\]",lambda m:random.choice(m.group(1).split("/")),"[Please/Kindly] [visit/see] my [site/blog].")' ``` The Perl program (my first ever! :-P) outputs: ``` Kindly see my blog. import re,random;print re.sub("\[(.*?)\]",lambda m:random.choice(m.group(1).split("/")),"[Please/Kindly] [visit/see] my [site/blog].") ``` The Python program outputs: ``` Kindly visit my site. ``` ]
[Question] [ (The \$\mathbb{Q}\$ in the title means rational numbers.) ## Background [**Conway base 13 function**](https://en.wikipedia.org/wiki/Conway_base_13_function) is an example of [a strongly Darboux function](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)#Darboux_function), a function that takes every real number on any open interval \$(a,b)\$. In other words, for any given real numbers \$a, b, y\$, you can find a value \$x\$ between \$a\$ and \$b\$ such that \$f(x) = y\$. The function is defined as follows: 1. Write the input value `x` in base 13 using thirteen symbols `0 .. 9, A, B, C`, without any trailing infinite stream of `C`s. (It is related to the fact `0.9999... = 1` in base 10, or `0.CCC... = 1` in base 13.) 2. Delete the sign and decimal point, if present. 3. Replace `A`s with `+`, `B`s with `-`, `C`s with `.`. 4. Check if some (possibly infinite) suffix of the sequence starts with a sign (`+` or `-`) and contains exactly one `.` and no extra signs. If such a suffix exists, interpret it as a decimal number; it is the value of \$f(x)\$. Otherwise, \$f(x) = 0\$. Some examples: * \$f(123B45.A3C14159\dots \_{13}) = f(0.A3C14159\dots \_{13}) = 3.14159\dots \$ * \$f(B1C234 \_{13}) = -1.234\$ * \$f(1C234A567 \_{13}) = 0\$ ## Task Given three rational numbers \$a = \frac{a\_n}{a\_d}, b = \frac{b\_n}{b\_d}, y = \frac{y\_n}{y\_d}\$ given as integer fractions, find a value of \$x = \frac{x\_n}{x\_d}\$ between \$a\$ and \$b\$ (exclusive) such that \$f(x) = y\$ (where \$f\$ is the Conway base 13 function). There are infinitely many values of \$x\$ that satisfy the condition for any input; just output one of them. You can assume \$a < b\$, \$a\_d, b\_d, y\_d > 0\$, \$y \ne 0\$, and the fractions are given in the reduced form. Negative input numbers are represented using negative numerators. You don't need to reduce the output fraction. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Examples ### `a = 0/1, b = 1/1, y = 1/3` Decimal representation of \$y\$ is \$0.\overline{3}\$ (where the overline is the notation for [repeating decimal](https://en.wikipedia.org/wiki/Repeating_decimal)). To get this value, the minimal base-13 suffix of \$x\$ is \$+.\overline{3}\$ or \$AC\overline{3}\$. An example of such an \$x\$ would be \$0.AC\overline{3}\_{13} = 569/676\$. [Proof by Wolfram|Alpha](https://www.wolframalpha.com/input/?i=569%2F676+in+base+13). ### `a = 2017/2197, b = 2018/2197, y = -1/5` The minimal base-13 suffix of \$x\$ is \$-.2 = BC2\_{13}\$. But the value of `a` is exactly \$0.BC2\_{13}\$, so we can't use that. And the value of `b` is \$0.BC3\_{13}\$, so we're forced to begin with \$0.BC2\$. One possible value of \$x\$ is \$0.BC2BC2\_{13} = 4433366 \; / \; 4826809\$. ### `a = 123/10 = c.3b913b91..., b = 27011/2196 = c.3b93b9..., y = 987/1` One possible answer is \$x = c.3b92a987c\_{13} = 130435909031 \; / \; 10604499373\$. ### `a = -3/2, b = -4/3, y = -1/7` One possible answer is \$x = -1.5bc\overline{142857}\_{13} = -28108919 \; / \; 19316024\$. [Answer] # [Python 2](https://docs.python.org/2/), ~~254 237 219 216~~ 207 bytes *-3 bytes thanks to @KevinCruijssen !* Can save 1 more byte by replacing `X=e**(A+B)` with `X=e**A**B`, but the result will be humongous, and the time taken to run will be very long. ``` e=13 a,A,b,B,y,Y=input() X=e**(A+B) x=a*X/A+2 r=abs(y) s="AB"[y<0]+`r/Y`+"C" R=[] exec"R=[r]+R;r=r%Y*10;s+=`r/Y`;"*-~Y n=~R.index(r) T=e**-n-1 S=e**len(s)*T print(int(s,e)*T+int(s[n:],e))*((x>0)*2-1)+x*S,X*S ``` [Try it online!](https://tio.run/##JY1Ba4QwFITv71eUQCF5eXaNe1v7Ctp/oHtQRFh3N1ChpJJYiJf961a3hxm@GQZmWuavH5etq2VzhIEKulJJC7U8uul3lgoatoiy0KWCyAM2h0Jn4Hm4BrkoCCyKUnTLe9rriz@0Fy0@BVTc9WCjvYmNfK@r3LN/bdGkedD83OUCk0cLjh/V2@juNkqv4Lx/JS4xUO/0bZ0MCs8w@dHNclcguxX6iZ079VtUKGX8SBVmiVE6Yk0N1uuakqEX82/HPw) or [Check all test cases!](https://tio.run/##pVVbb9pKEH7fXzHaKJLXF2xDGxKCI0Fa6VSqqgioRMRBwcZLYh2zdtaQwkv/es7M2gnkpVITHszc9vvGszPjcr95KFT7@eS9P3YCkwcJpS7udbxm78dZFqmECDjnzzIKOyx2B27iDt29ext9@3Hzc2IJNo2kbVsDZyjYLortqT9w2kxHcVJZe8GqiA@GfLbvB3Nnof3bhcOvORtFszmTO7nkKOm5M7rUkT69tcPgsnIiE3fJbe/3LVPR71ErU6ncWVqwCXF5ygvZmKRcKqsS9oTdjCaWlamNVbkSdceIM9Wboypsy9pdBcJue6FwdvbYndpj8YzvxD5S4H9kXkoNq61abrJCVbAqNOiY5DiHJK4kLAv1JHWFFoz/WcnUxGxktcnU/QfIU7kyBGFglS48ip6Wm61WcEfGqbG5EAaCHSI7f4rsNJFvrInoMYCKbt9z@Ky8Cuaokw9NdLmlcM3/ozBxTgSWAfiGtS99gwD4ujzgAhzgLU7H4TSCRxS0XMd0q5oIZoT86yHLsWVBFRvI1FEApXF8oBWXpVQp8htHaUeJEbBx7tLsPjPsje80qslKoqFuOcAI8I5B6xYzmE2NqlnPo5Nzh1vcqWZG6aEmeF2tmix9LSoPwnbn0@ez7vnFYHjNZ@n8UFUqijJFbYKVzYFDrNIjv5@4iXAaXHWa4LV8aAVgo30AABFG2T0uERwm2BRQxU8Sa1Ntc6Pe50WCjf4U6yxOcskaTwQ/CiXNi9NQ1l2HRW3C6yhT5CacIhiL8/xuWWgtl2Sb6K1kLFuXhd5Ata8YzU2eKUmdgXqr2qSZItgTBIpTM1OwpJlb6WKNUeWWSEzuPPrbH3WqYYvMH7LprLSoNVY6XlbRbB2XlnyKc5f0VlXmeF/c50KYAScjJVqfrZ0uF9TkFi5Q4Vq4QvGJS1QghcFEn9mnRBmvkzTuWUe7lqjrl92q160OQAsUaEUz41w@yOV/hwr/iWvnwhTV19j6kilhF8f9iruw2C1cfCV3MV2g6V/F6xSyFUz7QQ92eNrbXRoUb4qOw@XhJ6C/swemt3f2sJ/Y5H97wccaxTXyayY8hj5y9CHpYS6N9zWP/V0YIEizAvcumAJV29Uqo7zI3cJhzeOlxMnF2g@4OBg8NAyPDS00XHNxIDf4ABFSk3hwvFCgoxaplHdh5yWZjkWFPUIyzhqJxDd1IkMLF1n1K9s8WDWe@PtKvThrgKNyHUI4Y@@ehPrg4Pt3mHwdT@BmMB5//UIsR4k9B36In5H60WHtIOz67fCi6wKK543ohf5nhgvSDwO0d4MwJMeZCxfnXT9kXsdvY9Anv2NCuwwfYUChNWz77H8) A program that takes in 6 integers from `STDIN`, and prints out the numerator and denominator of the result. ### Big idea * First, find a number \$c\$ such that \$a < c < b\$ and \$c\$ has finite base-13 representation. Note that \$c\$ should be "sufficiently far away" from \$a\$ and \$b\$. This will be the prefix of \$x\$. For example: \$a = 1.1...\_{13}, b = 1.3...\_{13}\$ then \$c = 1.2\_{13}\$. We say that \$c\$ is sufficiently far away from \$a\$ and \$b\$, since we can add any suffix to \$c\$ and it is guaranteed to stay in the range \$(a,b)\$. * Then find the suffix of \$x\$ by finding the base-10 representation of \$y\$, then replacing `+-.` with `ABC`. E.g with \$y = 1/3\$, the suffix is \$+0.(3)=A0C(3)\$ * Join the prefix and suffix together. E.g \$x = 1.2A0C(3)\$. ### Details **Finding the prefix:** The prefix has the form \$x/X\$, where \$X\$ is a power of 13. Consider the integers \$\Bigl \lfloor \frac{aX}{A} \Big \rfloor \$ and \$\Bigl \lfloor \frac{bX}{B} \Big \rfloor \$ (where \$X = 13^i\$), which are the truncations of \$a/A\$ and \$b/B\$ to a certain base-13 precision. If there is an integer \$x\$ between those 2 numbers such that \$x\$ is at least 2 away from both numbers, then \$x/X\$ can be the prefix. This is because no matter what suffix is added, the value of \$x/X\$ won't change by more than \$1/X\$. \$X=13^{A+B}\$ is guaranteed to be large enough to see a large gap between the truncation of \$a/A\$ and \$b/B\$. This is the part that finds the prefix: ``` X=e**(A+B) x=a*X/A+2 ``` **Finding the suffix:** First, the long division \$y/Y\$ is performed to find the decimal representation (with repeated digit). `r` is the current remainder, and `R` keeps track of the seen remainder after each digit division, in order to detect repeating decimals. \$y/Y\$ is calculated until \$Y+1\$ digits after the decimal point, which is sufficient to detect repeating groups of digits. ``` r=abs(y) s="AB"[y<0]+`r/Y`+"C" R=[] exec"R=[r]+R;r=r%Y*10;s+=`r/Y`;"*-~Y ``` The suffix has the form \$stttt... = s(t)\$, where \$s\$ is the result of truncated \$y/Y\$ above, and \$t\$ is the repeating decimals found in \$s\$. ``` n=~R.index(r) t = s[n:] ``` Thus, our result should have the form \$\frac{x + 0.sttt...\_{13}}{X}\$ (or \$\frac{x - 0.sttt...\_{13}}{X}\$ if \$x\$ is negative) To convert `0.s(t)` in base 13 to fraction, the following formula is used: $$ 0.s(t) = 0.sttt... = \frac{s.(t)}{13^i} $$ $$ s.(t) = s.ttt... = s + \frac{t}{13^j-1} $$ where \$i, j\$ are the number of digits in \$s, t\$. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 156 bytes ``` a=13;b=Floor;c=RealDigits@#~FromDigits~a&;(d=b[+##2/2,e=a^b@Log[a,#3-#2]/a])+If[d<0,-e,e]/a(If[#<0,11,10]+(c[f=b[g=Abs@#]]a+12+c[g-f])/a^IntegerLength@f/a)& ``` [Try it online!](https://tio.run/##RVDBaoNAEL3nK4YshIhr19W2JhiLhRJI6aGkx2UDq9k1QlTQvYn5dTvGlF6GefP2vXk7lbIXXSlb5mo0NSSwHlXCwzhL9temaeM8OWp1/SiL0nYpue3bpprBTa3i9TnJhEtIwAKqE3XK0q@mEIqS0COBZEo67sGI886nnqYaB2uEBCHnlPvSXefCoEORvGdoLqVyeeDmovCMdJg6HWqrC91@6bqwl9Qw5axGJ15Y3dkOk/a9zzgFPpdwoNAHPo9YwLcRBWw3j9bj7GVieRAy7iMV@ZxP3CuF7SZifCK9ED8B3jML74JoGOKFqSzumTLDDlC49JZYYClh9wY/ti3r4lB3urViBp9NWYtH6nkiCGYLJayApfB/yXk8haTgSyG4lBKdn9A@wMfx4hvFf67H0pirFlMYNOlRampBUI0dnnkqg5xWpGkK9@PE4y8 "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes the rational numbers \$y\$, \$a\$, and \$b\$ (in that order) as input and returns the rational number \$x\$ as output. The function directly uses rational arithmetic; I wrote another algorithm which manipulates the individual digits, but it took 192 bytes. I'm pretty sure that another few bytes can be squeezed out of this one, though, since the negative-number handling is somewhat sloppy. Also, here's an ungolfed version to clarify the logic: ``` Block[{y = #, a = #2, b = #3, conv = FromDigits[RealDigits[#], 13] &, pref, prefexp, ipart, sign}, prefexp = 13^Floor[Log[13, b - a]]/13; pref = Floor[(a + b)/2, prefexp]; ipart = Floor[Abs[y]]; pref + If[pref < 0, -1, 1] prefexp/ 13 (If[y < 0, 11, 10] + 13^-(IntegerLength[ipart] + 1) (13 conv[ipart] + 12 + conv[Abs[y] - ipart]))] & ``` ]
[Question] [ *Infinite Snake* is just like the video game [Snake](https://en.wikipedia.org/wiki/Snake_(video_game_genre)), except for that the snake is infinitely long, there are no items to eat, and the Snake needs to move in a repeating `n`-step move pattern (e.g. right, up, right, up, right, down). The only constraint is that you can't crash back into yourself. ## Challenge Your goal is to write code that counts the number of valid move patterns of length `n`, where two patterns are considered the same if you can get from one to the other through a series of rotations, reflections, and reversals. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes wins. --- ## Origin This sequence is based on the On-Line Encyclopedia of Integer Sequence's lastest "nice" sequence, [A334322](https://oeis.org/A334322). > > Number of endless self-avoiding walks of length n for the square lattice. > > > An "endless self-avoiding walk" (i.e., *valid move pattern*) is defined in the paper [Endless self-avoiding walks](https://arxiv.org/abs/1302.2796) by Nathan Clisby on the arXiv. Roughly speaking, an \$n\$-step self-avoiding walk (in the usual sense) is called *endless* if you can concatenate it with itself head-to-tail an infinite number of times and remain self-avoiding. ## Example For example, Figure 2.1 in the paper gives an example of an endless self-avoiding walk (of length six) on the left and a non-example on the right. [![endless self-avoiding walks](https://i.stack.imgur.com/RrVTP.png)](https://i.stack.imgur.com/RrVTP.png) --- # Small test cases ``` f(1) = 1: ----> f(2) = 2: ---->----> and ----> | v f(3) = 3: ---->---->---->, ---->---->, and ----> | | v v----> f(4) = 7: ---->---->---->---->, ---->---->---->, ---->----> , | | v v----> ---->---->, ----> ^, ----> , and ----> . | | | | | v v----> v----> v | | | v v v----> ``` More small values: ``` f(5) = 16 f(6) = 39 f(7) = 96 f(8) = 245 f(9) = 631 f(10) = 1642 ``` [Answer] # JavaScript (ES6), 240 bytes Returns the \$n\$-th term of the sequence. ``` f=(n,p=[],s=[])=>n?[-1,0,1,2].map(d=>f(n-1,[...p,[d%2,~-d%2]],s))|N:N=[...p,...p].every(o=([h,v])=>o[[n+=h,y+=v]]^=1,y=0)&&s.every(P=>(g=j=>!j||P.reverse().some(([h,v],i)=>(j&4?h:-h)-p[i][j&1]|(j&2?v:-v)-p[i][~j&1])&g(j-.5))(8))?s.push(p):N ``` [Try it online!](https://tio.run/##LZDRisIwEEXf/YosuGWGJsHKLuzWnfYPxPeQxaLRttQkNG5BrP66m6Iw3Atn7tyHaauhCru@8Wdh3d48DhQHLPekNA9RkApbKpHxBc/4UstT5WFPxQFsZEpK6bnavy/5XUTV8QZxXOdreq4m0dIMpr@AI1A1H6ZGp5RNqeaXlAatfynjF1pgkoRXdEMFHKml4q0dx43sJxoMoAzuZOBZw5tYBG3yUda5qFF41WjVJpkeI1yWQy6GF7xPFJMjtEJ@IsIXYhmk/ws1eMzXj4ProTNnZhmxbBXth9h39DRFdp0xtnM2uM7Izh1hW8H8am8Yo/NrfALetria3R7/ "JavaScript (Node.js) – Try It Online") ## A334322 (133 bytes) This is a version where the tests on symmetries of the square and reversals of the path have been removed. So, it generates [A334322](https://oeis.org/A334322) instead. This is just meant as a verification of the main algorithm. ``` f=(n,p=[],s=[])=>n?[-1,0,1,2].map(d=>f(n-1,[...p,[d%2,~-d%2]],s))|N:N=[...p,...p].every(o=([h,v])=>o[[n+=h,y+=v]]^=1,y=0)?s.push(p):N ``` [Try it online!](https://tio.run/##JY5NCsIwEEb3niILhRk6Ddad1tEb9AIhYrGpVWoSGi2UWq9eI27eg29@@O5lX4ZLd/PP1LrKzHPNYMmz0hQikA/2qNKM1pTRRstH6aHiQw02ZkpK6UlVqw190kgdbxDfxa7g/@gHLU1vugEcg2qo/310StmEGxoS7rU@cUYDr/EYpH@FBjzuirl2HbTmKaxgkeVRexbb6CRBMS6EuDgbXGtk665wLmE52gnj6nKMzXA6Y76Y5i8 "JavaScript (Node.js) – Try It Online") ## Commented ### Main algorithm This is the main algorithm, which generates A334322. ``` f = ( // f is a recursive function taking: n, // n = input p = [], // p[] = current path as a list of (dx, dy) s = [] // s[] = array of solutions ) => // n ? // if n is not equal to 0: [-1, 0, 1, 2] // list of directions .map(d => // for each direction d: f( // do a recursive call: n - 1, // decrement n [ // new path: ...p, // copy all previous entries [ // add a new pair (dx, dy): d % 2, // with dx = d mod 2 ~-d % 2 // and dy = (d - 1) mod 2 ] // (NB: sign of mod = sign of dividend) ], // end of new path s // pass s[] unchanged ) // end of recursive call ) | N // end of map(); yield N : // else: N = // update N: [...p, ...p] // append the path to itself .every(o = // o is an object used to store the positions ([h, v]) => // for each (h, v) = (dx, dy): o[[ // update o for the new position: n += h, // add dx to n y += v // add dy to y ]] ^= 1, // if a position was already visited, this XOR gives 0 y = 0 // start with y = 0 (we already have n = 0) ) ? // end of every(); if the path is self-avoiding: s.push(p) // push it into s[] : // else: N // leave N unchanged (see the note below) ``` **Note:** The first iteration always leads to a valid straight path. Because of that, \$N\$ is guaranteed to be defined when we encounter an invalid path for the first time. (Otherwise, this `N = N` could be a problem, as \$N\$ is not explicitly defined anywhere else.) ### Additional tests Below are the additional tests that are performed to detect symmetries of the square and reversals of the path. There are \$16\$ different tests whose parameters depend on the bits of a counter \$j\$ going from \$8\$ to \$0\$. We subtract \$1/2\$ from \$j\$ between each iteration so that each set of parameters is tested twice: once with the path \$P[\:]\$ reversed and once with \$P[\:]\$ put back in the original order. ``` s.every(P => // for each previous path P[] in s[]: ( g = j => // g is a recursive function taking a counter j: !j || // success if j = 0 P.reverse() // otherwise, reverse P[] .some(([h, v], i) => // for each (h, v) at position i in P[]: (j & 4 ? h : -h) // compare either h or -h with - p[i][j & 1] | // either p[i][0] or p[i][1] (j & 2 ? v : -v) // compare either v or -v with - p[i][~j & 1] // the other component of p[i] ) & // end of some() g(j - .5) // do a recursive call with j - 1/2 )(8) // initial call to g with j = 8 ) // end of every() ``` ]
[Question] [ Given two contiguous shapes of the same area, determine the optimal way to divide the first shape into a minimum number of contiguous segments such that they can be rearranged to form the second shape. In other words, find the minimum number of segments required that can form both of the shapes. "Contiguous" means that every square in the shape can be reached from any other square by walking across edges. Shapes and segments are allowed to have holes. "Rearrange" means you move the segments around; you can translate, rotate, and reflect them. The shapes are contained on a grid; in other words, each shape consists of a collection of unit squares joined by their corners/edges. # Input Specifications The input will be provided in some reasonable format - list of points, array of strings representing each grid, etc. You can also take the sizes of the grid if requested. The grids will have the same dimensions and the two shapes are guaranteed to have the same area, and the area will be positive. # Output Specifications The output should just be a single positive integer. Note that there will always be a positive answer because in the worst case scenario, you just divide the shapes into `N` unit squares. # Examples The examples are presented as a grid with `.` representing a blank and `#` representing part of the shape. ## Case 1 **Input** ``` ..... .###. .#.#. .###. ..... ###.. ..#.. ..#.. ..### ..... ``` **Output** ``` 2 ``` **Explanation** You can divide it into two L-shaped blocks of 4: ``` # ### ``` ## Case 2 **Input** ``` #... ##.. .#.. .##. .##. #### .... .... ``` **Output** ``` 2 ``` **Explanation** You can split the shapes like so: ``` A... AA.. .A. .BB. .AA. BBAA .... .... ``` You could also do: ``` A... AA.. .B.. .BB. .AB. AABB .... .... ``` ## Case 3 **Input** ``` #....# ###### .####. .####. ``` **Output** ``` 2 ``` **Explanation** ``` A....B AAABBB .ABBB. .AAAB. ``` (This test case demonstrates the necessity to rotate/reflect shapes for optimal output) ## Case 4 **Input** ``` .###. ..#.. .##.. .##.. ``` **Output** ``` 2 ``` **Explanation** No matter how you select blocks, selecting a 2x1 from the first shape necessarily prevents the other two from being grouped together; thus, you can use one 2x1 and two 1x1s. However, (thanks @Jonah), you can split it into a 3-block L shape and a single square like so: ``` .AAB. ..A.. .AA.. .BA.. ``` ## Case 5 **Input** ``` ## #. #. ## ``` **Output** ``` 1 ``` **Explanation** The input and output shapes may be identical. ## Case 6 **Input** ``` #.. ##. .## ##### ``` **Output** ``` 3 ``` **Explanation** There is no way to divide the original shape into two pieces such that both pieces are straight, so at least three are needed. [Answer] # [Python 3.6](https://docs.python.org/3/), ~~799~~ 791 bytes 7 bytes saved by Jonathan Frech and motavica ``` B=frozenset M=min X={} T=lambda s:((x,y)for y,x in s) N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s) G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s} C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1)) F=lambda s:N([(-x,y)for x,y in s]) P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t def U(s): k=P(s) if k in X:return j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j} for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t) V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1 A=lambda s,t:U(s)or U(t)or V(P(s),P(t)) ``` [Try it online!](https://tio.run/##jVRtb@IwDP6eXxERaUpuBY2XT93yYUza9oUJaS9C6nqnHoQug7WoCTs4xv11zk4KLaedNECJ7dh@HtsJi7V9ybPubteX0yL/rTKjLBnIN52RkdxsyYOcJ28/Jwk1IeerYC2meUHXwYrqjBpB7qrjPpw3B9yI6CwO1iA9gIyKC4HQMuSmCtm4jKE5AaHZBjHgq9NyhxRtv5@2xRZSOF9MsSVX@xRpYAItz0J9Iecq46lIsgn3knQWIwD7ioNfa5npPOPf3pIFT1upsgGwCzQkF@S6onTHI97c17knHQsyPLgAYC8c8OgOkgfXuAz5tS820MA5DmZqLefaWKGnVFM1N4oacl8lsLLPheNtP@65CUAr2S0/NguslS4R11IUF45CEyxTqOTG@4gAlxpAn0fwy9TKcm1VgWxi@LoC9bT5R1/4djhnSyZqSh9BDQmdySEIBNPPEGoUFsoui4zQVxl5Chbt93wmSgqzpgUCFRjqYivi81E0i@VmyK2A6yAOoa9bUuV5DdErQqf4QzreQ58hFuePYIUFVfJU61jYPh3wJ/4e/BKH9vT5KILRnOBu/S17dwWANVrGqP/yukUdyZvv1rerTS7r2R/9RUF02J740I8VOO0YHefZuyqsofZF0bTQEzpP1vnSUptTHDPNp3SRG21hgsZ19hbuH3Q2lWnLLOba8sZz1oAW@8ZGh3fkXlGRZKnylxYfi39g/xzgpBusIWUareNoFceEkHFiVPtHm0r6TBqNRgs/pMUYw7XFDjJ@4Hwf0NkH4CkeH62M1QIWhc4sv@S3vMQSAd3LHQHvhowg2WZLKYPS4I/DdWicjF@UA@tU7BiS84B@YRWnTsUJ7eBWsiD/YdKpMel8iUn3mEmLORDGDhy6RxxY2T32GXq3ht79EnqvNqVyJqw2k95x/b47nyH3asg9h7z7Cw "Python 3 – Try It Online") ## Usage `A(s, t)` takes in two shapes where each shape is given by a list of `x, y` grid positions. A helper function to convert the graphical representation to a list of positions is below: ``` def H(g): g=g.split("\n") return[(x,y)for x in range(len(g[0]))for y in range(len(g))if"#"==g[y][x]] ``` Example: ``` case1_1 = \ """..... .###. .#.#. .###. .....""" case1_2 = \ """###.. ..#.. ..#.. ..### .....""" print(A(H(case1_1), H(case1_2))) # Prints 2 ``` ## Explanation The algorithm used here is a little better than brute force by caching sub-shapes. For a given shape, it caches all the ways to split that shape into two contiguous shapes, I then normalise these shapes (shift the coordinates so it starts at the origin, then find a rotation/reflection of it which is used in the cache) and store them in the cache to look up quickly later. All sub-shapes then have their sub-shapes cached as well until it gets to the single block shape. These sub-shapes are generated by converting it to a graph adjacency list and using a BFS to generate all sub-graphs. We can then filter these subgraphs to ones where the vertices which weren't included are a connected component. Determining whether the graph is connected is done with another BFS. After the cache is complete, the solution is found by comparing the two shapes to find the sub-shapes that it has in common. Once it has these list of sub-shapes, it takes the pair of sub-shapes left over after removing the common shape and recursively applies the same algorithm again to find the minimum number of blocks needed to reconstruct the shape. This then returns the sub-shape with the minimum of all those values and we have our solution. I've put an annotated version below to kinda explain what each line is doing. ``` B=frozenset M=min # Shapes are stored as a frozenset of tuples where each tuple represents an (x, y) position # Cache of shape partitions. This is a two-level dictionary where the outer key is a shape, and the inner key is a sub-shape where the value is a list of the shapes left when the sub-shape is removed. # there may be multiple shapes in the inner-most list if the sub-shape appears multiple times X={} # Transpose list of coords (flip around diagonal axis) T=lambda s:((x,y)for y,x in s) # Translate shape so its upper-left corner is at the origin N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s) # Convert shape to graph in adjacency list form G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s} # Check if graph is connected given a set of nodes, s, known to be connected C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1)) # Flip shape around vertical axis F=lambda s:N([(-x,y)for x,y in s]) # Converts shape to the minimal reflection or rotation. rotation is equivalent to transpose then flip. P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s # returns all the contiguous sub-shapes of s that contain the first pos, given by next(iter(s)) S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t # updates the sub-shape cache, X, recursively for an input shape s def U(s): k=P(s) if k in X:return j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j} for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t) # Gets the minimum number of partitions for two shapes V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1 # The function to run, will update the cache for the two input shapes then return the minimum number of partitions A=lambda s,t:U(s)or U(t)or V(P(s),P(t)) ``` [Answer] # Python3, 788 bytes: ``` import itertools as I E=enumerate R=lambda x,n=4:set()if n==0 else{str(x),*R([i[::-1]for i in zip(*x)],n-1)} S=lambda t:{(x,y)for x,k in E(t)for y,p in E(k)if p} V=lambda x:1==len(x)or all(any((j+J,k+K)in x for J,K in[(0,1),(0,-1),(1,0),(-1,0)])for j,k in x) G=lambda p,i,F=min:F(j[i]for j in p) N=lambda p:[(x-G(p,0),y-G(p,1))for x,y in p] M=lambda j:[[int((x,y) in j)for y in range(G(j,1,max)+1)]for x in range(G(j,0,max)+1)] O=lambda j:{*R(m:=M(j)),*R([i[::-1]for i in m])} def P(b,n): q=[(b,[],n)] while q: b,C,n=q.pop(0) if n==0 and not b:yield C if n and b: for i,_ in E(b,1): for c in I.combinations(b,i): if V(c):q+=[(b-{*c},C+[N(c)],n-1)] def f(a,b): c=0 while c:=c+1: if any(all(O(J)&O(K)for J,K in zip(x,y))for x in P(S(a),c)for y in P(S(b),c)):return c ``` [Try it online!](https://tio.run/##dZRLb6MwEIDPy6@wirSxGweFJq1Wlnyq2qqt@lAr9cJGERCyNQFDwNXCRv3tWY8dSCM1ORh75puHZ8YpW/VeyMmvstpuRV4WlUJCJZUqiqxGYY1unSueyI88qUKVOC88C/NoEaKGSj5ldaIwEUskOR@jJKuTTa0q3BB6@oIDETA28mfLokICCYn@iRKfNmRG5cgnn85r50qxDW5oSwBs6ArQK6zMsaWlPa4gSvnpvPXxmc95lkgdTHNhluFQthinwzu6Gt4TbdQg8HBH77WHAI@pT6heR/Dx6VivI/jMTJzUhm2Ic9MFKKmg1zwXkl3jNBDmGilAJXEee4gFuBnd4BIctmbjk91FWgPPnIcOTlkQCKmwuSwoU3tH2Fah/JPgG5xSn@ZhQ4Y@MRGbQ@W4VzpPe7cbXe2c8Qecku8rn890vRfJEj3jiErCHLTmgd4GuhfaFfr7LrIErbUcRfRSd3btlUWJx0QLuu6GcoFkoVDEWpFkC3S50xlFBKam3oLObcciXQkjNeIYhLdeXOSRkKEShaw1IXYEOHrDMWHrIeQ12pzGn/RyGDxqmR2XmUl/iUMagU3Mx13WMePx0Gc2G5gBmIUnfEd@PuF7sh8BM35QedLX9Rm/4pDQeN8GkEQgIaxK1EclUbytfcTRycmJ48HP8VzXhdVz@72RA1H78w4GDagOVtf9Cp9xA8LZwnZxO/XcN4CRuJ2tWYx@0pt7rtFrwir2hu4uSdeYOPUUFF3WbpfI1Bp4bpeADXAOQu3U3R13bk02RnJhAJs@2FmhxUw@IIC@qWIeFWG1wFG10O37sautfQ4rxDkauANiBsW8QzFD/ewuRab/jvBjIROKtL1Xl5lQePBbDogeC8cpK/CyxH2QWj9x9OU010@SfIOdHWBnx7DJATY5hk0PsOkx7PwAOz@GXRxgFwbb/gc) ]
[Question] [ Challenge Taken with permission from my University Code Challenge Contest --- The dependence we have on mobile phones makes us charge them every night up to the maximum level of the battery, so we do not run the risk of running out of power by the middle of the next day. There are even people who, when they see a free outlet during the day, put it to charge for what may happen. I am one of them. Over the years, I have refined my technique to not charge the battery to the maximum every night. With my perfectly known repetitive routines, I am clear on what times of the day I will be able to do those partial recharges (and how many units the level will increase) and what lowers the battery level between each charge. With these data, every night I calculate the minimum battery level I have to leave the house the next day with so that it never falls below my self-imposed threshold of two units. What I have not yet managed to master is that same calculation when I leave the established routine and I have several alternatives to do things. It happens, for example, on the days when I'm en route to another city to which I can arrive in different ways. In my first approach to the problem, I am assuming that I want to move around a "chessboard", from the upper-left corner to the lower-right corner. In each "cell" I can either charge the mobile a specific amount, or I cannot and its load level goes down. **Challenge** Given a FxC matrix of integers, output the minimal battery level amount I need to go from the top-left corner to the bottom-right without the load level ever falling below 2 units. In the matrix, a positive number indicates how much I can charge my mobile phone before I have to resume following my path, while a negative number indicates that there are no outlets and that the mobile's battery drops its charge level by that amount. It is guaranteed that the quantities in the source and destination cells (top-left and bottom-right corner) are always 0 and that the rest of the values (absolute value) do not exceed 100. **Example** Given: $$ \begin{bmatrix} 📱&-1&1&-1 \\ -1&-1&-1&-1 \\ -1&1&-1&-1 \\ 1&1&-1&0 \end{bmatrix}$$ The path I need less battery is: $$ \begin{bmatrix} 📱&-1&1&-1 \\ \color{blue}{-1}&-1&-1&-1 \\ \color{blue}{-1}&1&-1&-1 \\ \color{blue}{1}&\color{blue}{1}&\color{blue}{-1}&0 \end{bmatrix}$$ And the minimal battery level amount I need is 4 **Notes** * The Start is always going to be the top-left corner * The End is always going to be the bottom-right corner * You cannot go to a cell you've already passed. Example: Once in position (0,1), you cannot go to the initial point (0,0) * Your battery level cannot (for any reason) go under 2 * You can assume there will always be a beginning and an end * You can take the 1-dimensional arrays as multidimensional if you need to `[1,2,3] == [[1,2,3]]` * There can be multiple correct (minimal needed charge) paths * Your goal is to only output the lowest initial battery level needed, not the route * You can only go vertically and horizontally (not diagonally) **Test Cases** ``` [0, 0] => 2 [0, 1, 0] => 2 [0, -1, 0] => 3 [0, 15, -20, 5, 0] => 7 [[0, -3],[-5, 0]] => 5 [[0, -5, -9, 5], [-3, 5, 2, -2], [2, -4, -4, 0]] => 5 [[0, -1, 1, -1], [-1, -1, -1, -1], [-1, 1, -1, -1], [1, 1, -1, 0]] => 4 ``` [Answer] # JavaScript (ES7), ~~ 162 156 ~~ 154 bytes ``` m=>(M=g=(x,y,n,k)=>m.map((r,Y)=>[r[x+1]]+[m[y+1]]?r.map((v,X)=>r[1/v&&(x-X)**2+(y-Y)**2==1&&g(X,Y,u=v+n,k<u?k:u,r[X]=g),X]=v):M=M>k?M:k))(0,0,0)|M<0?2-M:2 ``` [Try it online!](https://tio.run/##fVDLboMwELznK3xCdrADNkFVUQxfwB1k@YDyQC0BIlIQSP13ui5phUISW7bGszOzWn9mXXbdNx@XL1bVh@N4kmMpQxzLXOKeDrSiBZFhuSmzC8YNTeGhGtXbXGtblWowIGqmckcTKDeKO51l4Z4lZL0WNh5YaoCU3LJynNCUtrKzIXjXRkXQ0kYlWuaEwt2RIJZxWERxUBCCXQqbfMc7NxIsDsS4r6trfT5uznWOT1itEFIuRa7WhKD5chwkVo/FfKF/IWYLNYi9Z8k@GAQA/88E4rdHYmSiPU0NZqBeTABG/6nRtHkHk38L8AyGI0z7ifvF2@n8h78MhUHN1zB@C@UTx@44dMehGTdvtB1/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` m => ( // m[] = input matrix M = // initialize M to a non-numeric value g = (x, y, n, k) => // g = recursive depth-first search function m.map((r, Y) => // for each row r[] at position Y in m[]: [r[x + 1]] + // if either r[x + 1] [m[y + 1]] ? // or m[y + 1] is defined: r.map((v, X) => // for each value v at position X in r[]: r[ // 1 / v && // if v is numeric (x - X) ** 2 + // and the squared Euclidean distance (y - Y) ** 2 == 1 // between (x, y) and (X, Y) is 1: && // g( // do a recursive call: X, Y, // with (X, Y) u = v + n, // with n = n + v k < u ? k : u, // with k = min(k, n + v) r[X] = g // set r[X] to a non-numeric value ), // end of recursive call X // then restore r[X] ] = v // to its initial value ) // end of inner map() : // else (we've reached the bottom right corner): M = M > k ? M : k // update M to max(M, k) ) // end of outer map() )(0, 0, 0) | // initial call to g with x = y = n = 0 and k undefined M < 0 ? 2 - M : 2 // return 2 - M if M is negative, or 2 otherwise ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~208~~ 202 bytes ``` lambda s:2-f(s) def f(s,x=0,y=0): if x>-1<y<s[y:]>[]<s[y][x:]!="">s[y][x]:k=s[y][x];s[y][x]="";return k+min(0,max([len(s[y+1:]+s[y][x+1:])and f(eval(`s`),x+a/3-1,y+a%3-1)for a in 7,1,5,3])) return-9e9 ``` [Try it online!](https://tio.run/##VZDhaoMwFIX/@xR3hUGCCTNaGaaNL5IFmmHspJoWzYY@vUu0sOVHuN8599x7IY/Ffd1tvl7Fx9rr4bPRMPGctmjCSWNa8EBmkZFFZJgn0LUw15Sdl/MkF65qqQIoOXP1Ig6HeheK38STTs/qm6fRuO/Rwi0dOosyMugZyd5Y5CMp4yrdowGxto0/bX50jy7TBZM51W8FZWRJ9auvuL2PoKGz8E4YKUmhME5g308rU62h70JfSpkRyJQisBH7L2ikWOmd3EMZZYpANPZCsvLBrVVsE3kYDjrAcX/xJRbKNsF2g0ZOZPxpv0P5j4fH2FkHV@Tw@gs "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~217~~ 211 bytes ``` i=input() X,Y=len(i[0]),len(i) s=[[0]*4+[i]];r=[] for m,l,x,y,g in s: if X>x>-1<y<Y<"">g[y][x]:r+=[m]*(Y-y<2>X-x);l+=g[y][x];g[y][x]="";s+=[[min(m,l),l,x+a/3-1,y+a%3-1,eval(`g`)]for a in 7,1,5,3] print 2-max(r) ``` [Try it online!](https://tio.run/##VU9Na8IwGL7nV7wEBq1NmGktY7bpzV132UEJATsXNaxfxLo1v75LqjB7CM9Hnvers/25beLx0H4p4IAxHjXXTXftgxBtyY5Xqgm0WMqQTCxEFy6cXKwioaXMDBcSHVsDNanIQCw5gW7gskagj7AthoKy3Oa7HOPiJKwUg1ybiItaLoIdtXlcbOkQZlXE77/ZHTnG2cUFRa2bwPUOffuofE4oIzYqnzyqn7IK9qd9KP0CpR/8QhhJSSJRZ3TTQ0zrcghMOLq7EPo960rBh7kqtx70xnoAUIM6gL8feX5QXQ@b97eNMa25BT6NKr9HdzWBpZRoIuyB00fBUmfEjqSPiUQSQWeOj726lCQgaDLFY1/ptSer25sNYR6mAnYz6MyZGf/atfgD "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~224~~ ~~220~~ ~~217~~ ~~213~~ 210 bytes ``` f=function(x,m=rbind(0,cbind(0,x,0),0),i=2,j=2,p=F,k=c(1:-1,0,0,-1:1),b=Inf,`^`=min){m[i,j]=0 for(h in 1:4)b=b^'if'(all(c(R<-i+k[h],C<-j+k[h+4])>dim(x)),max(2,2-cumsum(p)^0),if(v<-m[R,C])b^f(x,m,R,C,c(p,v))) b} ``` [Try it online!](https://tio.run/##pZFPa8IwGIfvfopAD74vvoGmtshKs4sw2NVradFGgqmmiptSGPvsXdIOhpVdNH/Im9/hyZPk3HVa6kujPs2xgZasPFem2UJI6ndtKUQ/jIyodvMk32gvFYiUCwpd5yIVSJV8bzSty7W0psEvmxuqCxlO9PEMO2YaJtIYK1mVU6OnsDkcQMEq42a2z3cFLTNe@2oWF/i6NRZaRLKbFiKKuLrYj4uFE5ZeQ8M14zZf0bLAqtTemdyGFJzoioiT6rvTMNxCOX8WupA91QIWTW6Q4mnqHZI/zQzYfGSZOGzkiuRRdMAWI8s5uofmyeOuAUtGSG/54iSRmEPPe93Im/eBr@Jh/nfkPVL0X8TFgBRDwm@j2@Qv6E8JWNz9AA "R – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 242 bytes ``` a=>{int m=1<<31,n=~m;void g(int w,int x,int y,int z){for(int i=4,t,c,d,e;i-->0;)try{t=a[c=i<1?w-1:i<2?w+1:w,d=i>2?x-1:i>1?x+1:x];n=t==0&z<n?z:n;a[c,d]=m;e=y+t<2?2-y-t:0;if(t!=m)g(c,d,y+t+e,z+e);a[c,d]=t;}catch{}}a[0,0]=m;g(0,0,2,2);return n;} ``` [Try it online!](https://tio.run/##fVLLboMwELz7K9xLBYqtYEhUFWO49dx7xAEBSXzAkcAJL7m/TtcgUkVNe8DMzszOygt5Q/NGTh9XlUdS6QNJCbzio5gyEY8AcSVYFAWMKPFV8dtFFvjkWL61RtzNZz@fgzseL/UsSrEjmuSkICWXlMYed3Xdj1pkh1zIiCUtZaGM/KTdsLAlhZCxn3SWi1nSAdelXAkthPc6RCoZQsWhkxSpqHgp@o2GVp/2VIcel0dHv4jKPTl2Hmibkgyb0l07NDd5pvPzaEx28IhnM04OAOIT3@V1qa@1woqbiSO7ghSWgHXZ6AYLrMoWr@SI1sri0SPYMwRvt9hHhvzSmJX/VOldDp4278HiA9ivtrenKQGQI72b9k9NNusdomZvMGf6Nt7WFuyW578INt@HsjmCLQR9YB6In3oJ3SGDDEfwd5RZfnZuWT0vGGYsi3ZH9FnDQAc@JdSuy5GZvgE "C# (Visual C# Interactive Compiler) – Try It Online") ``` //a: input matrix a=>{ // m: marker for used cells // n: result, initialized to a huge value int m=1<<31,n=~m; // recursive function // w: 1st dim coordinate // x: 2nd dim coordinate // y: current charge level // z: initial charge for current path void g(int w,int x,int y,int z){ // i: loop variable // t: temp holds overwritten value // c: adjacent 1st dim coordinate // d: adjacent 2nd dim coordinate // e: delta charge needed for(int i=4,t,c,d,e;i-->0;) // avoid index out of range errors // by using try/catch try{ // determine neighbor // coordinates and save value t=a[c=i<1?w-1:i<2?w+1:w, d=i>2?x-1:i>1?x+1:x]; // if we have found a 0, check if // initial charge is lower than the // lowest so far. save it if it is. n=t==0&z<n?z:n; // mark current cell used a[c,d]=m; // determine if we need to // increase the initial charge e=y+t<2?2-y-t:0; // make recursive call if current // cell was not previously in use if(t!=m)g(c,d,y+t+e,z+e); // restore current cell value a[c,d]=t; }catch{} } // mark starting cell used a[0,0]=m; // start the recursive function g(0,0,2,2); // return the result to the caller return n; } ``` ]