text
stringlengths
180
608k
[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/24182/edit). Closed 2 years ago. This post was edited and submitted for review 16 days ago and failed to reopen the post: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/24182/edit) ## Explanation ¡Hola! For those of you who don't take Spanish, a verb is conjugated based on the person who does the action. Here's a chart: ``` English Spanish I Yo You Tú He Él She Ella You (formal) Usted We all Nosotros You all Vosotros They (masculine, plural) Ellos They (feminine, plural) Ellas You (plural) Ustedes ``` In Spanish, all verbs end with `ar`, `er`, or `ir`. Here's another helpful chart: ``` Ar Er Ir Yo o o o Tú as es es Él a e e Ella a e e Usted a e e Nosotros amos emos imos Vosotros áis éis ís Ellos an en en Ellas an en en Ustedes an en en ``` ## Challenge Given a pronoun and an unconjugated verb, **write the shortest program or function** that outputs the verb conjugated for the pronoun in the present tense. Conjugations are given in the tables above, where it is a process of replacing the `ar/er/ir` ending with its respective conjugated ending. You do not need to worry about accented output (i.e. "Vosotros" verbs can be conjugated as `ais eis is`). You also do not need to worry about stem changing and irregular verbs. --- ## Examples ``` Input Output Yo escribir Escribo Tu enseñar Enseñas Ella querer Quere (It should be quiere but ignore stem changes) ``` You can find more words with which to test here: <http://spanish.speak7.com/spanish_vocabulary_verbs.htm>. Note that contester should be contestar. --- ## Challenge: Stem Changes In Spanish, some verbs have stem changes. Let's take the verb `querer` for example. In all forms *except nosotros and vosotros*, the first `e` changes to `ie`. So, `yo quiero`, but `nosotros queremos`. **If your program can account for stem changes, you may subtract twice the length of each word you support from your final score**. For example, if you support the `i` -> `ie` change `querer` and only `querer`, you can subtract twice the length of `querer`, or 12, from your score. For some stem-changing verbs, try this: <https://conjuguemos.com/chart.php?language=spanish&id=2&etre=no&commands=no&all=no&source=public> --- (As I am not a native Spanish speaker, please correct me on any mistakes) [Answer] # Python, ~~172~~ ~~168~~ 743 characters - 1796 bonus = -1053 Updated to take the stem-changing challenge. ``` p,v=raw_input().split() y="aee";z=y+'n' x=["ooo",y+'s',y,y,y,"aeimos","ae\x00is",z,z]["YoTuElEaUdNsVsEsUs".index(p[0]+p[-1])/2] s=v[:-2] X=v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g=='.decode('base64').decode('zip') if s in X: j=X.index(s)<326 s=(s.replace('oe'[j],'ui'[j]+'e'),s)[p[0]in'NV'] print s+x["aei".index(v[-2])]+x[3:] ``` **Usage**: ``` $ echo "Ellas querer" | python conj_golf2.py quieren ``` **Test on non-stem-changing inputs**: ``` Yo ensenar -> enseno Yo escribir -> escribo Tu ensenar -> ensenas Tu escribir -> escribes El ensenar -> ensena El escribir -> escribe Ella ensenar -> ensena Ella escribir -> escribe Usted ensenar -> ensena Usted escribir -> escribe Nosotros ensenar -> ensenamos Nosotros escribir -> escribimos Vosotros ensenar -> ensenais Vosotros escribir -> escribis Ellos ensenar -> ensenan Ellos escribir -> escriben Ellas ensenar -> ensenan Ellas escribir -> escriben Ustedes ensenar -> ensenan Ustedes escribir -> escriben ``` **Stem-changing input examples**: It does both e->ie changes and o->ue changes, properly avoiding the nostros + vostros cases: ``` $ echo "Yo abstenir"|python conj_golf2.py abstieno $ echo "Nostros abstenir"|python conj_golf2.py abstenimos $ echo "Tu almorzar"|python conj_golf2.py almuerzas $ echo "Vostros almorzar"|python conj_golf2.py almorzais ``` Here is how the bonus was determined and the data string generated, from which you can deduce the verbs on which it works: ``` e="absten.acert.adher.adquer.advert.apret.asent.atraves.calent.cerr."+\ "circunven.comenz.confer.confes.consent.conten.contraven.conven.convert."+\ "difer.diger.discern.disent.freg.gobern.hed.hel.her.herv.infer.inger."+\ "invern.invert.malher.manifest.ment.neg.nev.obten.ofend.pens.perd."+\ "quer.recomend.reg.seg.sembr.sent.serr.sosegsosten.soterr.subarrend."+\ "suger.tembl.tend.ten.tent.transfer.tropez.ven.vert" u="absolv.acord.acost.almorz.along.amobl.apost.aprob.asol.avergonz."+\ "coc.col.colg.cont.cost.degoll.demol.demostr.desaprob.descolg.descontr."+\ "desos.destorc.devolv.disolv.dol.dorm.encontr.engros.envolv.forz.holg."+\ "holl.llov.mol.mor.mostr.mov.ol.pobl.prob.record.reforz.remord.remov.renov."+\ "repobl.resolv.resoll.reson.retorc.revolc.revolv."+\ "rod.rog.sol.sold.sol.solt.son.torc.tost.tron.vol.volc.volv" words = e.split(".") + u.split(".") bonus = 0 for word in words: bonus += (len(word)+2)*2 print "Bonus: %d from %d stem-changing verbs" % (bonus, len(words)) s=(e+"|"+u).replace(".","") zipped = s.encode('zip') b64 = zipped.encode('base64') print "The separator is at index %d" % s.index("|") print "Uncompressed: %d chars, %d repr" % (len(s), len(`s`)) print "Compressed: %d chars, %d repr" % (len(zipped), len(`zipped`)) print "Comp+B64: %d chars, %d repr" % (len(b64), len(`b64`)) print "v="+`b64` ``` Which gives: ``` $ python conj_help.py Bonus: 1796 from 127 stem-changing verbs The separator is at index 326 Uncompressed: 645 chars, 647 repr Compressed: 331 chars, 1015 repr Comp+B64: 450 chars, 458 repr v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g==\n' ``` [Answer] # Python, 240 bytes - (extremely large) bonus ``` from re import*;import urllib2 as u,sys;x=sys.argv try: print search('>.*?'+sub('a','o',sub('ella','el',x[1]))+'.*? ([^<]*)',sub(u'\u00e9','e',sub(u'\u00fa','u',u.urlopen("http://smarturl.it/xz?word="+x[2]).read()))).group(1) except: pass ``` Sample Output: ``` Input | Output yo escribir | escribo tu escribir | escribes tu ensenar | ensenas ella querer | quiere ellas querer | quieren nosotros vive | vi tu acordar | acuerdas ``` Explanation: This code uses an existing free conjugation website (<http://www.conjugation.org/>) that returns various conjugations from a large database of verbs. I reduced the URL slightly by using a free online URL shortener that allows parameters to be passed through the redirection (<http://smarturl.it/>). I simply make a HTTP request based on the verb specified, remove the accents from the `u` and `e` in the source, find the pronoun in the HTML using regular expressions, then return associated conjugation. It's impossible to tell how many verbs have stem changes without polling the entire database against a dictionary. It's probably safe to assume the negative bonus from this database is much larger than any bonus from encoded lists passed in (which increase the length of the code). I could obviously have handled the accented characters better, but it would've required encode/decode and extra handling within the regular expressions. [Answer] # Freepascal, 218 chars -30 = 189 It's a tough call to beat the (original) python answer, especially with Pascal. I may try and improve tomorrow, possibly with a similar concept in a different language. I will not be submitting a stem-changing answer, as I see this as a linguistic rather than programming challenge. ``` var y,p,v:string;BEGIN y:='amosemosimosais eis is as eso eso o an en en';readln(p);readln(v);writeln(copy(v,1,length(v)-2),copy(y,6*(7-pos(p[1],' yt v n'))+pos(v[length(v)-1],y),pos(p[length(p)],'u s')+1));END. ``` Ungolfed version: ``` var y,p,v:string; BEGIN y:='amosemosimosais eis is as eso eso o an en en'; readln(p);readln(v); writeln(copy(v,1,length(v)-2), copy(y,6*(7-pos(p[1],' yt v n'))+pos(v[length(v)-1],y),pos(p[length(p)],'u s')+1)); END. ``` **Explicación (In Spanish for the -30 bonus since you asked)** el primer `copy` extrae la raíz del verbo, teniendo como parámetros el *string*, el indice para empezar (en este caso 1) y la cantidad de letras (en este caso *length-2.*) El segundo extrae su desinencia. `6*(7-pos(p[1],' yt v n')` se evalúa según la primera letra del pronombre. Si el pronombre es él/ella(o/s) o usted(es),`pos` se evalúa a cero, así que el valor dentro de los paréntesis es 7. `pos(v[length(v)-1],y` busca la penúltima letra del infinitivo en `amosemosimos` así que avanza 4 por cada tipo de verbo, formando un ciclo de 12. El resto de `y` consiste en todas las desinencias. Se ha logrado intercalar parcialmente las desinencias para "tu" y "yo." Sin embargo queda cierta cantidad de espacio en blanco que me gustaría eliminar. Así se define el indice para buscar la desinencia en y. `pos(p[length(p)],'u s')+1)` determina el numero de caracteres para imprimir. si el pronombre no termina en `s` o `u` solo se imprime un cáracter. De esta manera suprimimos la segunda letra de `an en en` en el caso de un pronombre de tercera persona singular: él, ella, usted. **Output** ![enter image description here](https://i.stack.imgur.com/qVdzH.png) [Answer] # JavaScript (V8), 191 bytes ``` p=>v=>v.replace(/.r$/,e=>({"Yo":"o","Él":x=e[0]=="a"?"a":"e","Tú":x+"s","Ea":x,"Ud":x,"Ns":e[0]+"mos","Vs":({"a":"áis","e":"éis","i":"ís"})[e[0]],"Es":n=x+"n","Us":n})[p[0]+p.slice(-1)]) ``` [Answer] # perl, 243 chars This time focusing on hash lookup. I'm fairly surprised I couldn't get this smaller. ``` $_=<>;s/^(ustede|ell[oa])s\b/x/;s/^(él|ella|usted)\b/w/;%t=(yo,[o,o,o],"tú",[es,as,es],w,[e,a,e],x,[en,an,en],nosotros,[imos,amos,emos],vosotros,[qw(ís áis éis)]);@t=keys%t;$"="|";s/^(@t)\s+(\S*)([aei])r$/$2.$t{$1}[ord($3)%3]/e||die;print ``` And if input validation isn't important, 186 chars: ``` $_=<>;s/^[ue].*s /x /;s/^[éeu].* /w /;%_=(y=>[o,o,o],t,[es,as,es],w,[e,a,e],x,[en,an,en],n,[imos,amos,emos],v,[qw(ís áis éis)]);s/^(.)\S*\s+(.*)([aei])r$/$2.$_{$1}[ord($3)%3]/e;print ``` [Answer] # perl, 155 chars Just a bunch of regular expressions this time. You can get shorter code by rearranging things slightly so that the pronoun comes after the verb, since we only really care about the end of the verb: ``` $_=<>;s/(.+) (.*)(.)r/$2$3 $1/;s/. yo/o/||s/ tú/s/||s/ n.*/mos/||s/ v.*/is/||s/ .*s$/n/||s/ .*//;s/i(n?)$/e$1/;s/ais$/áis/;s/eis$/éis/;s/iis$/ís/;print ``` Seems like the above is currently the winner of code that ignores the bonus. ``` ski@anito:~$ c='$_=<>;s/(.+) (.*)(.)r/$2$3 $1/;s/. yo/o/||s/ tú/s/||s/ n.*/mos/||s/ v.*/is/||s/ .*s$/n/||s/ .*$//;s/i(n?)$/e$1/;s/ais$/áis/;s/eis$/éis/;s/iis$/ís/;print'; for p in yo tú él ella usted ellos ellas ustedes vosotros nosotros ; do for v in mar mer mir ; do echo "$p $v" | perl -e "$c" ; done ; done ; echo -n "$c" | wc -c mo mo mo mas mes mis ma me me ma me me ma me me man men men man men men man men men máis méis mís mamos memos mimos 155 ``` [Answer] # Bash, 301 ~~309 (bugfix)~~ ~~307~~ 299 including new lines Not great compared to the other ones out there. Could be improved. It exploits some convenient coincidences. The bugfix relies on no Spanish verb having "ii" anywhere, due to the way it saves characters when handling vosotros with -ir verbs. Please correct me if that's wrong. Assumes valid input: first argument is the lower case pronoun, with any necessary accents; second argument is the infinitive of the verb. No stem changes implemented. Outputs the conjugated verb, in lower case, without accents. ``` e=`tail -c3<<<$2` f=`echo ${e:0:-1}` s=`echo ${2:0:-2}` if [ $1 = yo ];then o="$s"o;elif [ $1 = nosotros ];then o="$s$f"mos;elif [ $1 = vosotros ];then o="$s$f"is;else if [ $f = i ];then f=e;fi if [ $1 = tú ];then o="$s$f"s;elif [ `tail -c2<<<$1` = s ];then o="$s$f"n;else o=$s$f;fi fi tr -s i<<<$o ``` Explained. ` ` is an obscure notation for `$( )`, saving one char. ``` e=`tail -c3<<<$2` ``` get the verb ending ``` f=`echo ${e:0:-1}` ``` get the first char of the verb ending ``` s=`echo ${2:0:-2}` ``` get the verb stem ``` if [ $1 = yo ]; then o="$s"o; ``` Verb stem+o. $o is our output ``` elif [ $1 = nosotros ]; then o="$s$f"mos; ``` take stem+first letter of ending+mos ``` elif [ $1 = vosotros ]; then o="$s$f"is; ``` stem+first letter of ending+is (no accents) ``` else if [ $f = i ];then f=e;fi ``` in all scenarios except the two above, -ir verbs behave as -er verbs. change $f to e if it is i. ``` if [ $1 = tú ]; then o="$s$f"s; ``` stem+$f+s ``` elif [ `tail -c2<<<$1` = s ]; then ``` if the last letter of the ending is s. this includes ellos, ellas, ustedes which all have the same endings. how convenient. ``` o="$s$f"n; ``` stem+$f+n ``` else o=$s$f;fi ``` we are assuming valid input, so the only other possibilities are Él, Ella and Usted, all with the same endings ``` fi tr -s i <<< $0 ``` print output, removing double i's (which appear when you use vosotros with an ir verb) [Answer] ## Java – Too Long I'm not even going to bother counting. If anyone would like to better golf this, please do. I'll eventually implement the stem-changing challenge. ``` public class Conjugator { public static void main(String[] args) { setup(); String p = args[0].toLowerCase(), v = args[1]; String e = v.substring(v.length() - 2); v = v.substring(0, v.length() - 2); String f = data.get(e).get(p); System.out.println(v + f); } static HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>(); public static void add(String ending, String pronoun, String fin) { HashMap<String, String> hm = data.get(ending); if (hm == null) { hm = new HashMap<String, String>(); hm.put(pronoun, fin); data.put(ending, hm); return; } hm = data.get(ending); hm.put(pronoun, fin); } public static void setup() { add("ar", "yo", "o"); add("ar", "tu", "as"); add("ar", "el/ella/usted", "a"); add("ar", "nosotros", "amos"); add("ar", "vosotros", "ais"); add("ar", "ellos/ellas/ustedes", "an"); add("er", "yo", "o"); add("er", "tu", "es"); add("er", "el/ella/usted", "e"); add("er", "nosotros", "emos"); add("er", "vosotros", "eis"); add("er", "ellos/ellas/ustedes", "en"); add("ir", "yo", "o"); add("ir", "tu", "es"); add("ir", "el/ella/usted", "e"); add("ir", "nosotros", "imos"); add("ir", "vosotros", "is"); add("ir", "ellos/ellas/ustedes", "en"); } } ``` [Answer] # perl, 298 characters ``` $_=<>;($p,$b,$x)=/^\s*(yo|tú|él|ellas?|ellos|usted|ustedes|[nv]osotros)\s+(\S*)([aei])r\s*$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v ``` or if we can throw caution to the wind and assume valid input, 246 chars: ``` $_=<>;($p,$b,$x)=/^(\S+)\s+(\S*)([aei])r$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v ``` test output: ``` ski@anito:~$ c='$_=<>;($p,$b,$x)=/^(\S+)\s+(\S*)([aei])r$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v'; for p in yo tú él ella usted ellos ellas ustedes vosotros nosotros ; do for v in mar mer mir ; do echo "$p $v" | perl -le "$c" ; done ; done ; echo -n "$c" | wc -c mo mo mo mas mes mes ma me me ma me me ma me me man men men man men men man men men máis méis mís mamos memos mimos 246 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 195 bytes ``` (p,v)=>(x=v.charAt(v.length-2))&&(y=p.charAt(0))&&v.substring(0,v.length-2)+(p=='Yo'?'o':p.endsWith('ros')?x+(y=='N'?'mos':(x=='i'?'':'i')+'s'):(x=='i'?'e':x)+(y=='T'?'s':p.endsWith('s')?'n':'')) ``` [Try it online!](https://tio.run/##fZNBbsIwEEXXzSmiLBhbhAh1mcqgLrplRalYhjBAqtRObSeiqnqonqEHS01DIXGCV5b/mxmPvr5fkypRqcwKPeFii/WO1aQIK8pm5MiqKD0k8lGTKsqR7/Vhck/paEQ@WPFPpiehilS5UVpmfE@mYat4TArGYC1gDgLiIkK@VS@ZPhCQQgGdH8dmFoOF4W9GiM2bDDJzg9gcdAym6CoixEfadCzNVXUnnuYBN41Aab0reaozwX2NSpNCCi5KHvoVyg31P727VHAlcoxyse/S0Ac2g9DfWU30wfvyvL9pwVoEoR8gV/jzncjAoEZflsP6U35Lz5Nh8qw0bofRQiihjXvDdOWk5kEHSpRjGbSh73ltE011x533EiX2vLHVxpm@2vhi6xdXbND2xGYrB7v4MbSBurkCWshpBJ5@1ybrx6Snn2MyoJ9j0iPXmPRQJyY9unLSa0wGd1GOZdCG9S8 "JavaScript (Node.js) – Try It Online") Doesn't handle the stem changes. It would cost a few more bytes to add the accents to the Vosotros form conjugations. If the input has accents, the output will include them. Also, it doesn't matter if accents are included in the pronouns or not; my program happens to ignore the characters that have accents on them. ]
[Question] [ Well, when I buy gifts for my two wives, I want them to feel equally important to me, but it's hard to go shopping with fixed budgets. Instead, I buy a bunch of stuff and divide them into two groups with as equal value as possible. Then I buy a bunch of chocolates to fix the rest. But I don't want do all the hard lifting when my computer can do it. And you don't either. So solve this problem so that the next time you need to divide gifts among your wives, you know it would be easy. ### Input 1 array of (N\*2) elements where N\*2 is specified in the 1st line. The elements of the array in the following line. ### Output 2 array of N elements each such that: Difference of (Sum of elements of array 1) and (Sum of elements of array 2) is as close as possible to 0. ## Example ### Input ``` 4 1 2 3 4 ``` ### Output ``` 1 4 2 3 diff=0 ``` **Disclaimer**: I don't have two wives. But when I feel bad, I imagine having two wives. And suddenly, I am thankful and happy that I have only one. :D [Answer] # Java Trying to solve this problem in two phases: 1. Build two equally sized lists by adding the remaining biggest to the currently smaller list and the next to the other. Repeat. 2. Identify items from both lists that can be switched to reduce the difference in value Input like > > > ``` > 8 > 1 2 3 4 5 6 7 8 > > ``` > > is already solved after phase 1 as e.g. > > > ``` > 2 3 5 8 > 1 4 6 7 > diff=0 > > ``` > > and input like > > > ``` > 6 > 1 4 5 6 7 8 > > ``` > > will need both phases so that > > > ``` > 1 5 8 > 4 6 7 > diff=3 > > ``` > > (after phase one) becomes the result of > > > ``` > 1 6 8 > 4 5 7 > diff=1 > > ``` > > While I can guarantee this attempt will always provide a solution, I can not prove that a optimal solution is found in all cases. With the restriction of equally sized lists it however feels quite realistic that there are no corner cases left behind. Prove me wrong ;-) Program on [ideone.com](http://ideone.com/9Hf7dL#stdin) ``` import java.util.*; /** * Created to solve http://codegolf.stackexchange.com/q/23461/16293 . */ public class EqualSums { public static void main(String[] args) { final Scanner s = new Scanner(System.in); // Read number of elements to divide final int count = s.nextInt(); if (count % 2 == 1) { throw new IllegalStateException(count + " can not be divided by 2. Consider adding a 0 value."); } // Read the elements to divide final SortedList valueStack = new SortedList(count); for (int i = 0; i < count; i++) { valueStack.add(s.nextLong()); } final SortedList targetOne = new SortedList(count / 2); final SortedList targetTwo = new SortedList(count / 2); // Divide elements into two groups addInPairs(targetOne, targetTwo, valueStack); // Try to ensure groups have equal value retaliate(targetOne, targetTwo); // Output result System.out.println(targetOne); System.out.println(targetTwo); System.out.println("diff=" + Math.abs(targetOne.getSum() - targetTwo.getSum())); } private static void addInPairs(SortedList targetOne, SortedList targetTwo, SortedList valueStack) { SortedList smallerTarget = targetOne; SortedList biggerTarget = targetTwo; while (!valueStack.isEmpty()) { // Add biggest remaining value to small target smallerTarget.add(valueStack.removeLast()); // Add second biggest remaining value to big target biggerTarget.add(valueStack.removeLast()); // Flip targets if roles have changed if (smallerTarget.getSum() > biggerTarget.getSum()) { final SortedList temp = smallerTarget; smallerTarget = biggerTarget; biggerTarget = temp; } } } private static void retaliate(SortedList targetOne, SortedList targetTwo) { long difference; boolean changed; outer: do { difference = Math.abs(targetOne.getSum() - targetTwo.getSum()); if (difference == 0) { return; } changed = false; // Try to find two values, that reduce the difference by changing them between targets for (Long valueOne : targetOne) { for (Long valueTwo : targetTwo) { final Long tempOne = targetOne.getSum() + valueTwo - valueOne; final Long tempTwo = targetTwo.getSum() - valueTwo + valueOne; if (Math.abs(tempOne - tempTwo) < difference) { targetOne.remove(valueOne); targetTwo.add(valueOne); targetTwo.remove(valueTwo); targetOne.add(valueTwo); changed = true; continue outer; } } } } while (changed); } public static class SortedList extends AbstractList<Long> { private final ArrayList<Long> list; private long sum = 0; public SortedList(int count) { list = new ArrayList<>(count); } // the next functions access list-field directly @Override public Long get(int index) { return list.get(index); } @Override public boolean add(final Long t) { final int i = Collections.binarySearch(list, t); if (i < 0) { // No equal element present list.add(-i - 1, t); } else { list.add(afterLastEqual(i, t), t); } sum += t; return true; } @Override public Long remove(int index) { final Long old = list.remove(index); sum -= old; return old; } @Override public int size() { return list.size(); } // the next functions access list-field only through the functions above this point // to ensure the sum is well kept public long getSum() { return sum; } private int afterLastEqual(final int start, Object o) { int found = start; while (found < size() && o.equals(get(found))) { found++; } return found; } private int beforeFirstEqual(final int start, final Object o) { int found = start; while (found >= 0 && o.equals(get(found))) { found--; } return found; } @Override public int indexOf(Object o) { try { final int i = Collections.binarySearch(this, (Long) o); if (i >= 0) { return beforeFirstEqual(i, o) + 1; } } catch (ClassCastException e) { // Object was not instance of Long } return -1; } @Override public int lastIndexOf(Object o) { try { final int i = Collections.binarySearch(this, (Long) o); if (i >= 0) { return afterLastEqual(i, o) - 1; } } catch (ClassCastException e) { // Object was not instance of Long } return -1; } @Override public boolean remove(Object o) { if (o == null) { return false; } final int i = indexOf(o); if (i >= 0) { remove(i); return true; } return false; } public Long removeLast() { return remove(size() - 1); } public Long removeFirst() { return remove(0); } @Override public String toString() { Iterator<Long> it = iterator(); if (!it.hasNext()) { return ""; } StringBuilder sb = new StringBuilder(); for (; ; ) { Long e = it.next(); sb.append(e); if (!it.hasNext()) { return sb.toString(); } sb.append(' '); } } } } ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) 2 ``` pᶠḍᵐ{+ᵐo-}ᵒh ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/wcNuChzt6H26dUK0NJPJ1ax9unZTx/3@0sY6hjgkQm@pYxv6PAgA "Brachylog – TIO Nexus") This is a popularity contest, but that doesn't necessarily mean that golfing languages are a bad fit. (Really, I should have answered in Jelly because Jelly answers tend to get a disproportionate number of upvotes for some reason regardless of who submits them or how golfed they are, but Brachylog is more readable.) We start off by taking the list of all permutations of the input (`pᶠ`), and splitting each (`ᵐ`) into two equal pieces (`ḍ`; we could give it a subscript if you had more than two wives for some reason). Then we order the split permutations (`{…}ᵒ`) by taking the sum (`+`) of each (`ᵐ`) half, taking the absolute difference (i.e. `o-`, "ordered difference"), and using those differences to define the sort order. The best result is the first one, so we take the head of the list with `h` to get the result. [Answer] # Mathematica Input forms The input string is to be taken through STDIN. `assets` refers to the amounts to be distributed among the wives (or twins). `length` is the number of assets. ``` assets=ToExpression[Rest[s=StringSplit[input]]] length=ToExpression[First[s]] ``` For the present purposes we will assume that the assets consist of the integers from 1 through 20. ``` assets=Range[20]; length=Length[Range[20]] ``` **Processing** ``` (* find all possible distributions to one wife; the other presumably gets the remaining assets *) r=Subsets[assets,{length/2}]; (*order them according to the difference with respect to the total of half of the assets. Remove the first set of assets. One wife will get these.*) s=SortBy[r/.{{a__Integer}:> {{a},Abs[Tr[Range[20]/2]-Tr[{a}]]}},Last][[1]]; (*The other wife's assets will be the complement. The difference is carried over from the sorting routine. *) Grid[{{Grid[{s[[1]],Complement[assets,s[[1]]]}]},{"difference = "<>ToString[s[[2]]]}}] ``` ![r20](https://i.stack.imgur.com/1vNyl.png) --- ## Is the distribution unfair? So, choose another. @The Constructor notes that wife 2 may contest the fact that wife 1 got all the best assets. So the following produces all of the "fair" (difference = lowest difference) shares for wife 1; wife 2 gets the remaining assets; the zero refers to the difference in assets for the wives. There are 5448 ways to distribute assets weighted 1 through 20. Only a few lines are displayed. The format is ``` s=SortBy[r/.{{a__Integer}:> {{a},Abs[Tr[Range[20]/2]-Tr[{a}]]}},Last]; z=Cases[s,{_List,x_}/;x==s[[1,2]]]; Short[z,10] Length[z] ``` > > {{{1,2,3,4,5,16,17,18,19,20},0},{{1,2,3,4,6,15,17,18,19,20},0},{{1,2,3,4,7,14,17,18,19,20},0},{{1,2,3,4,7,15,16,18,19,20},0},{{1,2,3,4,8,13,17,18,19,20},0},{{1,2,3,4,8,14,16,18,19,20},0},{{1,2,3,4,8,15,16,17,19,20},0},{{1,2,3,4,9,12,17,18,19,20},0},{{1,2,3,4,9,13,16,18,19,20},0},{{1,2,3,4,9,14,15,18,19,20},0},{{1,2,3,4,9,14,16,17,19,20},0},{{1,2,3,4,9,15,16,17,18,20},0},{{1,2,3,4,10,11,17,18,19,20},0},{{1,2,3,4,10,12,16,18,19,20},0}, > <<5420>>, > {{5,6,7,8,9,11,13,14,15,17},0},{{5,6,7,8,9,12,13,14,15,16},0},{{5,6,7,8,10,11,12,13,14,19},0},{{5,6,7,8,10,11,12,13,15,18},0},{{5,6,7,8,10,11,12,13,16,17},0},{{5,6,7,8,10,11,12,14,15,17},0},{{5,6,7,8,10,11,13,14,15,16},0},{{5,6,7,9,10,11,12,13,14,18},0},{{5,6,7,9,10,11,12,13,15,17},0},{{5,6,7,9,10,11,12,14,15,16},0},{{5,6,8,9,10,11,12,13,14,17},0},{{5,6,8,9,10,11,12,13,15,16},0},{{5,7,8,9,10,11,12,13,14,16},0},{{6,7,8,9,10,11,12,13,14,15},0}} > > > 5448 > > > --- The prior submission can be found among the edits. It is far more inefficient, relying as it does on `Permutations`. [Answer] # J There's a cheat sheet of all the J primitives at [this link](http://www.jsoftware.com/help/dictionary/vocabul.htm), in case you want to follow along at home. Remember: J is generally read from right to left, so that `3*2+1` is 7, not 9. Every verb (J for function) is either monadic, so in front like `f y`, or dyadic, so in between like `x f y`. ``` N =: (". 1!:1 ] 1) % 2 NB. number of items per wife S =: ". 1!:1 ] 1 NB. list of items to distribute bins =: #: i. 2 ^ 2*N NB. all binary strings of length 2n even =: bins #~ N = +/"1 bins NB. select those with row-sum 1 NB. all distributions of equal numbers of items to each wife NB. resultant shape: a list of 2xN matrices NB. this /. adverb is where all the magic happens, see below dist =: even ]/."1 S diff =: | -/"1 +/"1 dist NB. difference in wives' values idx =: (i. <./) diff NB. index of the lowest difference 1!:2&2 idx { dist NB. print the winning distribution of items 1!:2&2 'diff=', idx { diff NB. and the difference of that distribution ``` Notes and explanations: * `u/` means "fold `u` over", so perform the binary operation over each element in the list. So for example: `+/` means *Fold Plus*, or **Sum**; `<.` is *Lesser Of*, so `<./` means *Fold Lesser Of*, or **Minimum**. * `u"1` means "perform `u` on 1-dimensional cells", i.e. over every row. Normally the verbs in J are either atomic, or apply to the whole argument. This applies to both arguments if the verb is used dyadically (with two arguments). Consider the following: ``` i. 2 3 NB. just a 2x3 matrix of numbers 0 1 2 3 4 5 +/ i. 2 3 NB. Sum the items 3 5 7 +/"1 i. 2 3 NB. Sum the items of each row 3 12 ``` * `#:` is a verb that expands a number into its binary representation. When you use it on a list with more than one element, it will also align all the numbers properly, so that `#:i.2^n` will get you every binary string of length `n`. * `/.`, when used dyadically, is called *Key*. It uses the elements of the list on the left side as keys, and those on the right side as values. It groups together each set of values that share a key, and then performs some operation on them. In the case of `]/.`, the operation is just the identity verb, so nothing altogether special is happening there, but the fact that `/.` will partition up the list for us is the important bit. This is why we create the binary lists: so that for each list (`"1`), we can divvy up the gifts for the wives in all possible ways. * `1!:1]1` and `1!:2&2` are the read-in and write-out operations, respectively. The `1!:n` part is the verb and the other number is the file handle. `1` is console in, `2` is console out, and `3 4 5` are stdin, stdout, and stderr. We also use `".` when reading so that we convert the input strings to numbers. [Answer] # Clojure ``` (defn divide [n] (loop [lv [] rv [] d (reverse (sort n))] (if (empty? d) [lv rv] (if (> (reduce + lv) (reduce + rv)) (if (>= (count lv ) (count rv)) (recur lv (conj rv (first d)) (into [] (rest d))) (recur (conj lv (last d)) rv (pop d))) (if (<= (count lv ) (count rv)) (recur (conj lv (first d)) rv (into [] (rest d)) ) (recur lv (conj rv (last d)) (pop d))))))) (defn display [[f s]] (println f) (println s) (println (str "Diff " (- (reduce + f) (reduce + s))))) ``` Test ``` (->> [5 1 89 36 2 -4 20 7] divide display) =: [89 -4 1 2] [36 20 7 5] Diff 20 ``` [Answer] ## MATLAB Here is my solution: ``` %input array presents=zeros(2,8); presents(1,1)=8; %number of presents presents(2,:)=[1 2 7 4 5 3 2 8]; %list of presents %calculate the cumulative sum of all permutations %its all about the gift values how_many=presents(1,1); options=perms(presents(2,:); subtotals=cumsum(options,2); %find the first index where the difference between the two parts is minimal %makes both wives happy!! [~, double_happiness] = min(abs(sum(presents(2,:))/2-subtotals(:,how_many/2))); %create the present lists for Jennifer and Kate :) for_jennifer=options(double_happiness,1:how_many/2) for_kate=options(double_happiness,how_many/2+1:end) ``` For example the present list in my source code results in: ``` for_jennifer = 8 2 5 1 for_kate = 4 7 2 3 ``` which is both 16. If I golf my code, which is less fun I get a very unoptimised 132 chars. Beat that ;) ``` function f(p);o=perms(p(:,2));s=cumsum(o,2);[~,d]=min(abs(sum(p(:,2))/2-s(:,p(1,1)/2)));a={o(d,1:p(1,1)/2);o(d,p(1,1)/2+1:end)};a{:} ``` [Answer] ## PHP **Warning:** Very dirty code It tries every possible permutation of the input array. Ideone sample for `4/1 2 3 4`: <http://ideone.com/gIi174> ``` <?php // Discard the first input line! It's useless :) fgets(STDIN); $numbers = explode(' ', rtrim(fgets(STDIN))); $valuePerWife = array_sum($numbers) / 2; // Taken from here: http://stackoverflow.com/a/13194803/603003 // Credits to dAngelov: http://stackoverflow.com/users/955185/dangelov function pc_permute($items, $perms = array( )) { if (empty($items)) { $return = array($perms); } else { $return = array(); for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $return = array_merge($return, pc_permute($newitems, $newperms)); } } return $return; } foreach (pc_permute($numbers) as $permutation) { $sum = 0; $rest = []; for ($i=0; $i<count($permutation); $i++) { $sum += $permutation[$i]; if ($sum == $valuePerWife) { $rest = array_slice($permutation, $i + 1); break; } } if (array_sum($rest) == $valuePerWife) { echo implode(' ', array_slice($permutation, 0, $i + 1)), "\n"; echo implode(' ', array_slice($permutation, $i + 1)), "\n"; echo 'diff=0'; exit; } } exit('DIDNT FOUND ANY COMBINATION!'); ``` [Answer] ## Python: ``` import itertools as t raw_input() a=[int(i) for i in raw_input().split()] a=list(t.permutations(a)) b=len(a[0])/2 c=[(d[b:],d[:b]) for d in a] d=[abs(sum(d[b:])-sum(d[:b])) for d in a] e=zip(d,c) e.sort() print " ".join([str(i) for i in e[0][1][0]]) print " ".join([str(i) for i in e[0][1][1]]) print "diff",e[0][0] ``` or a bit golfified: ``` import itertools as t b=int(raw_input())/2 e=[(abs(sum(d[b:])-sum(d[:b])),(d[b:],d[:b])) for d in t.permutations([int(i) for i in raw_input().split()])] e.sort() f=e[0] g=f[1] print " ".join([str(i) for i in g[0]]),"\n"," ".join([str(i) for i in g[1]]),"\n","diff=",f[0] ``` Or even further golfified, since half the lines is just makeup. (assuming I can just dump the raw internal array, since this isn't specified in the op) You can leave away the `print` in (for example) the interactive shell, and add a `[::-1]` (on the very end, after `[0]`) if you really want the diff last. ``` import itertools as t b=int(raw_input())/2 print sorted([(abs(sum(d[b:])-sum(d[:b])),(d[b:],d[:b])) for d in t.permutations([int(i) for i in raw_input().split()])])[0] ``` (results in `(0, ((1, 2, 7, 8), (3, 4, 5, 6)))`) This, however, is just bruteforcing all posible combinations, and shouldn't be considered remotely efficient. However, if the list being equal lengths doesn't matter, this would also work (on large arrays): ``` raw_input() a,b=[],[] for i in sorted([int(i) for i in raw_input().split()])[::-1]: b.append(i) if sum(b)>sum(a): b,a=a,b print a,b,abs(sum(b)-sum(a)) ``` With the code under this for example, it runs with barely a difference at all: 500k on 10^10 max value isn't a lot, so to say. This is also a lot faster: where the other code probably wouldn't finish in under a year (and that's very optimistic), this runs in about half a second, even though your milage may vary. ``` def raw_input(): import random return " ".join([str(random.randint(1,10**10)) for _ in range(10000)]) raw_input() a,b=[],[] for i in sorted([int(i) for i in raw_input().split()])[::-1]: b.append(i) if sum(b)>sum(a): b,a=a,b print a,b,abs(sum(b)-sum(a)) ``` [Answer] ## Literate Haskell ``` > import Data.List > import Data.Function ``` I made use of the list monad to split it up. ``` > divide []=return ([], []) > divide (x:xs)=do > (w1, w2) <- divide xs > [(x:w1, w2), (w1, x:w2)] ``` Then we make a rater. ``` > rating (w1, w2)=abs $ (sum w1) - (sum w2) ``` And then a function that will minimize the difference. ``` > best = minimumBy (compare `on` rating) . filter (\(x,y)->length x == length y) ``` And something that combines them all. ``` > bestDivison=best . divide ``` Next a parser. ``` > parse::String->[Int] > parse=fmap read . words ``` And an output formatter. ``` > output (w1,w2)=unlines [unwords (map show w1) > , unwords ( map show w2) > , "diff="++(show $ abs $ (sum w1) - (sum w2))] ``` And now the program ``` > main = do > getLine --Ignored, I don't need the arrays length > input <- fmap parse getLine > putStrLn "" --For readability > putStrLn $ output $ bestDivison input ``` Example: ``` λ <*Main>: main 8 5 1 89 36 2 -4 20 7 5 36 20 7 1 89 2 -4 diff=20 ``` ]
[Question] [ ## Task Write a program or a function that calculates a week-day name of a date which a user inputs. ## Input & Output Input is a string, `YYYYMMDD`. Example of input values: ``` 20110617 : June 17, 2011 19040229 : February 29, 1904 06661225 : December 25, 666 00000101 : January 1, 0 99991231 : December 31, 9999 ``` You may assume that all inputs are valid. Note that [year zero](http://en.wikipedia.org/wiki/0_%28year%29) is valid. Output is an integer between `0` and `6`. Each integer represents a week-day name. You can decide freely which integer represents a week-day name, like this one ``` 0 : Monday 1 : Tuesday 2 : Wednesday ... 6 : Sunday ``` (in order) or this one ``` 0 : Monday 1 : Wednesday 2 : Sunday ... 6 : Saturday ``` (not in order). ## Test Cases ``` Input Week-day Output ([0..6 -> Monday..Sunday] is used in this example.) 20110617 Friday 4 19500101 Sunday 6 22220202 Saturday 5 19000228 Wednesday 2 19000301 Thursday 3 19450815 Wednesday 2 19040229 Monday 0 19040301 Tuesday 1 17760704 Thursday 3 20000228 Monday 0 20000229 Tuesday 1 20000301 Wednesday 2 20121223 Sunday 6 00000401 Saturday 5 66660606 Wednesday 2 59161021 Saturday 5 ``` ## Restriction You **must not** use **any** kind of function/class/... which are related to timestamp or date, like `Date` class in `Java`/`JavaScript`/`ActionScript`, or `getdate` function in `PHP`. You should use [Gregorian calender](http://en.wikipedia.org/wiki/Gregorian_calendar), which is used by many people now. Of course, shortest code wins. If two code have same length, then the code with highest votes wins. (Due: When there's more than 5 codes which has more than (or equal) `+1` votes.) [Answer] # PHP - ~~101~~ ~~97~~ ~~103~~ 125 characters * Sakamoto Algorithm * 0 = Sunday ## Code ``` <?php fscanf(STDIN,"%4d%2d%2d",$y,$m,$d);@$a=a032503514624;$y-=$m<3;$z=$y+1;echo($y+$y/4%$z-$y/100%$z+$y/400%$z+$a[$m]+$d)%7; ``` ### Note Unfortunately, due to PHP's dynamic, weak typing, the Sakamoto algorithm doesn't function properly without explicitly flooring each division operation. [Answer] ## Ruby, 95 92 characters Plain straightforward ruby implementation with 0:Monday, ... ``` p ((y=(d=gets.to_i)/(k=100)/k-((m=d/k%k)<3?1:0))+y/4-y/k+y/400+"squsptrotqro"[-m].ord+d%k)%7 ``` [Answer] ## C - 129 ``` main(y,m,d,s) { scanf("%04d%02d%02d",&y,&m,&d); y-=s=86400; d+=y+"-addgbegcfadf"[m]; m>2?y++:0; putchar(48+(d+y/4-y/100+y/400+s+s)%7); } ``` This abuses how division rounds toward zero, at least on my system (Linux x86). The magic constant, `86400`, serves two purposes: * Subtract from the year to make it negative, without affecting the day of the week. This makes it so the divisions will round up instead of down. * Shift the day number so Monday will be 0. It also happens to be the number of seconds in a day. [Answer] ## Javascript, 126 123 characters Using Sakamoto's algorithm with 0 = Sunday: ``` prompt().replace(/(....)(..)(..)/,function(_,y,m,d){y-=m<3;alert((+d+y-~(y/4)+~(y/100)-~(y/400)+ +".621462403513"[+m])%7)}) ``` I suspect the divisions can be collapsed, but right now I'm not seeing it. *Edit:* Improved the divisions (no need to `~~` when you can just `~`). [Answer] # [Python 2](https://docs.python.org/2/), ~~83~~ ~~116~~ ~~113~~ 109 bytes Implements [Sakamoto's algorithm](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Implementation-dependent_methods). Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/python2#LU5BCoMwELz3FUugmBDFXU1im7YvkdxU8KAtiaXk9TapnYFlZnYOsw/jBB8ehF0e87rx0CtrnLjFcvh7q5yo@HJvRXkExqa/H7e3X3mUsVZVrAkxq3Rzp8C20dhqUqZRRb9U5IQcxLnbp6eHAPMKPWuQCA11rARGV41ISFk3CZh45ErjJXWcPUHCy/8mgASWKCFsnufxQuxf "Python 2 – TIO Nexus") **Edit:** ~~I should have fixed this ages ago.~~ -6 bytes from Jonathan Allan's suggestions +2 bytes to actually fixing the code. ``` def w(s):m=int(s[4:6]);y,d=int(s[:4])-(m<3),int(s[6:]);return(y+y/4-y/100+y/400+int('032503514624'[m-1])+d)%7 ``` [Answer] # C (126 bytes) ``` main(y,m,d){scanf("%4d%2d%2d",&y,&m,&d);y%=400;putchar(((5*y+3)/4-y/100+"-KGGJLHJFIKGI"[m]+(!(y%4)&&m>2&&y%100||!y)+d)%7+48);} ``` [Try it online!](https://tio.run/##FcpLCsIwEADQszSQYcakNI0RlaJLa1tvIF2UBD@LFPGzGKxnjwpv@Xx@9j6lOFxHZB11oPfDD@MJhXRB2j@hgTVEDYEqlhtnTHV7Pf1luCPiYsZqToXLuSiNUSLv6ro97Ntd09WNOMZeYYYsHQHErQVg@WvTlDGpQHKp3IqqT0rWWGtKu/4C "C (gcc) – Try It Online") [Answer] ## Perl -- 110 bytes Here is a solution to be run with perl -p source.pl OR perl -pe 'here-is-code'. ``` s/((..)(..))(..)(..)/(1+3*$1+$2-2*($1%4+$2%4)-(2<$4?$4+(1&$4&&4-(8&$4)):(2^$4)+(!($3%4)-!-$3+!($2%4)))+$5)%7/e ``` Simply copy-paste the test cases to stdin. This seems to be the only code without variables, string constants and divisions. ]
[Question] [ This part is somewhat detached from the actual array manipulation side of the challenge, scroll down for an explanation that is much more array-based You've been [learning how to shuffle poker chips](https://www.wikihow.com/Shuffle-Poker-Chips) recently, but, as you're still learning, you don't always get the perfect alternating shuffle that you're aiming for. Instead, they often get grouped into pairs or triples of chips between each shuffle. Now, to make things easier, you've been practicing with 2 colors of chips, black and white, so you can see the outcome of the shuffle. One of your recent shuffles has produced this stack of 10 chips (where the left most element of the array is the top chip): ``` W B W W B B B W B W ``` Now, you want to unshuffle these chips and get them back to being two "blocks" of colors, either of these two: ``` W W W W W B B B B B B B B B B W W W W W ``` Unfortunately for you, the only way you like to unshuffle chips is by taking a number of chips off the top, flipping that "substack" of chips over, then adding back to the top: ``` W B W W B B B W B W [W B W W]B B B W B W W W B W B B B W B W ``` Here, we flipped the top 4 chips over (reversed the prefix of length 4). Indeed, it is possible to unshuffle this stack in 5 flips: ``` W B W W B B B W B W [W B]W W B B B W B W [B W W W]B B B W B W [W W W B B B B]W B W [B B B B W W W W]B W [W W W W B B B B B]W B B B B B W W W W W ``` In fact, a greedy approach should, in this case, always generate the fewest number of flips when only using two colors of chips. However, what if we instead use three colors? In this case, a strictly greedy approach (i.e. the lengths of the prefixes are always increasing) doesn't work. Consider, with green chips added in, ``` G W G W W B B G G W B B ``` This can be solved in 5 flips as well: ``` G W G W W B B G G W B B [G W G W W B B]G G W B B [B B W W G W G G G W]B B [W G G G W G]W W B B B B [G W]G G G W W W B B B B [W G G G G]W W W B B B B G G G G W W W W B B B B ``` Once we start adding in even more colors, it gets even more complicated. For example, with 5 different colors (`W`, `B`, `R`, `G`, `Y`), we might have, say: ``` R G B B G W B G R W W Y Y R Y ``` which can be done in 8 flips, in at least 2 ways, shown below: ``` R G B B G W B G R W W Y Y R Y R G B B G W B G R W W Y Y R Y [R G B B G W B G R W W Y Y]R Y [R G B B G W B G R W W Y Y]R Y [Y Y W W R G B W G B B G R R]Y [Y Y W W R G B W G B B G R R]Y [R R G B B G W B G]R W W Y Y Y [R R G B B G W B G]R W W Y Y Y [G B W G B B]G R R R W W Y Y Y [G B W]G B B G R R R W W Y Y Y [B B G W]B G G R R R W W Y Y Y [W B G G B B G R R R]W W Y Y Y [W G B B B G G R R R]W W Y Y Y [R R R G B B G G B]W W W Y Y Y [R R R G G]B B B G W W W Y Y Y [B G G]B B G R R R W W W Y Y Y [G G R R R B B B]G W W W Y Y Y [G G B B B]G R R R W W W Y Y Y B B B R R R G G G W W W Y Y Y B B B G G G R R R W W W Y Y Y ``` --- Alternatively, in more array manipulation based terms: given a list of integers, we can rearrange it by repeatedly reversing prefixes of given lengths ("flips"). For example, ``` [3, 2, 3, 1, 1, 2] -> [2, 3, 3, 1, 1, 2] -> [1, 1, 3, 3, 2, 2] -> [3, 3, 1, 1, 2, 2] -> [2, 2, 1, 1, 3, 3] -> [1, 1, 2, 2, 3, 3] ``` Here, we sorted the list by reversing the prefixes of lengths \$2\$, \$5\$, \$4\$, \$6\$ and then \$4\$. In this case, 5 flips is the minimum number possible to sort this list in ascending order. In this challenge, we don't require the final list to be sorted into ascending order. Instead, we simply want the list to be sorted so that equal elements are all adjacent to one another, in any order. For example, the previous example can be shortened to 2 flips: ``` [3, 2, 3, 1, 1, 2] -> [2, 3, 3, 1, 1, 2] -> [1, 1, 3, 3, 2, 2] ``` --- Your task is to, given a list of digits representing a chip stack, output the minimum number of flips required to arrange the list into a series of blocks of identical digits. For example, we could represent our 5 color example above as ``` [1,2,3,3,2,4,3,2,1,4,4,5,5,1,5] ``` or even as the integer `123324321445515`. You may assume that the input does not contain more than 9 distinct digits (so all will be from `123456789`), and that the numbers of each digit are equal. You may take input in any reasonable manner or format. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins! ## Test cases ``` array -> output [1,2] -> 0 [1,2,1,2] -> 2 [2,1,1,2] -> 1 [3,1,2,1,2,3] -> 3 [3,2,3,1,1,2] -> 2 [3,3,1,1,2,2,4,4] -> 0 [1,2,1,1,2,2,2,1,2,1] -> 5 [2,3,2,3,3,1,1,2,2,3,1,1] -> 5 [3,1,3,1,1,2,2,3,3,1,2,2] -> 5 [1,2,3,3,2,4,3,2,1,4,4,5,5,1,5] -> 8* [2,5,1,1,5,3,1,5,2,3,3,4,4,2,4] -> 8* [5,5,1,3,4,1,3,4,5,5,3,3,2,3,4,2,2,1,5,1,2,4,4,1,2] -> 15* ``` `*`: These are currently only an upper bound, and aren't proven to be the minimal number (just suspected). If you can get a lower value, please provide the list of flips to verify that value [Answer] ## Python3, 186 bytes: ``` import itertools as I def f(a): q=[(a,0)] while q: j,c=q.pop(0) if len(set(t:=[u for u,_ in I.groupby(j)]))==len(t):return c for i in range(2,len(j)):q+=[(j[:i][::-1]+j[i:],c+1)] ``` [Try it online!](https://tio.run/##VVLBbtswDD1XX0HkYilhjdiOgMKAd@@lP@AZhZLJrQzVVmSlQ78@E2V76yBAEB/f4yNEuq/wPo3Vk/P3u/lwkw9ggvZhmuwMaoZn9kv30HMlagbXpuUKj6Jj8PvdWA3XCMKAl@aau8nxo4ih6cHqkc868FA37Q36ycMNX8GM8Jy/@enmzl98EJ0QTUPMIGqvw82PcIlyYhviejW@aV4iUQYh6ushug9tbbq2rh@L7jC0pu7wcihEt7Wu5sDmZrfbtQWWHTz@gCOjJ25hyVoKtrBgbYVrHqsEVQTF4BurJGgF4jnh6f/SC7wUKVJKks1S5p8uvbY0Bd9TSxvlli5WkNyqVDq6ooynQJlIT3vykKmETHK5aohZrj0Sa1ERvtwy8ZfuTmvjMtmfEmf9GrmP/8j@jqM3Nu4Ff5lGjTDns7Mm8OznmMXRsAeFZ2jgQzkeR5BbWiFlX/Wnsggm99pZddE822cIWSY2NflEPXtw3oyB05YhnMX9Dw) The code above is a basic brute-force approach. However, the solution below, while longer, uses dynamic programming to produce results for all the test cases in about six seconds: ## Python3, 542 bytes ``` import itertools as I E=enumerate P=lambda a:[(j,[*k])for j,k in I.groupby(a)] L=lambda a:[u for u,_ in P(a)] V=lambda r:len(set(t:=L(r)))==len(t) def f(a): q,s,R,H=[(a,0)],[a],[],[len(L(a))] while q: j,c=q.pop(0) if V(j):R+=[c];continue for x,(_,A)in E(r:=P(j)): for y,(_,B)in E(r): if x<y and A[-1]==B[0]: J=j[:(i:=sum(len(k[1])for k in r[:x])+len(A))][::-1]+j[i:] if(O:=J[:(Y:=i+sum(len(k[1])for k in r[x+1:y]))][::-1]+J[Y:])not in s: if(M:=len(L(O)))<=min(H):q+=[(O,c+1+(J!=j))];s+=[O];H+=[M] return min(R) ``` [Try it online!](https://tio.run/##pVNNT@MwED2TX@HlUrsxVdM2EjJ4JZCQoIIt4oCEvBFyi7u4pE7qOGz769mZfAj2sKdVPmfemzcvE7s8hNfCTU9L//Fht2XhA7HB@FAUeUV0RW6iK2lcvTVeBxPdy1xvly@aaKHohqvhW8bWhScb/kasIzejX76oy@WBapZFt1/INUFazZ@Rdt/Ajz3sRW4crUygQchb6hljUmIqsOjFrMka6CIiO17xB34tFdV8zDKuNFxwIvMWKCBJfr/a3JAdsMHSSu5GZVHSMYPQrskj3TDxEEu1ys5WhQvW1QYQNLbn9JlfMPB2Rb2Q98DEli14QPCyA9s0yu3PD0S7F3KhTpJMyks1zlqMzOVGCWqFrOotRXtvKmnn1EzJK7HPWIzABbhWQoBAvFFWZG29XdOFkHPQeBLSxv9S2ceJOGSfCnP1JDLmioBw1XlBsTsh2yEtYLTncmsdvWZiB5OgC76Kk5jOv0n44uysgtwiO7uGxx2Y8SbU3hEseGD98tBViCp5fHysEj7JyMl3Mo7wlffhJFIY9GESqSnvcD5tUlNMQfCFNcFUl4Bjxmd/S7fpViRpoBTbtDKfdc1bD2PwFWptTHo46ZLYbdpIQ1eewpHwtCGdDrFH2kikTXna1SBz0nlEVluF@faeNvzW3awznjbtZw2nG006hDlGVYLj/E8RXBgW//za5rCB6Y/CGU6qUVXmNtDBTzfAJX2k@ZJIstUlhf84ynGv6/zZvOucEzvypsz1ytDBcMDJYMD6auwD9dFR6a0LFHckJ0v28Qc) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` ⊞υ⟦⁰S⟧Fυ¿¬ⅉ«≔⊟ιθ¿⊙θ⁻✂θ⌕θκλ¹κFLθ⊞υ⟦⊕Σι⁺⮌…θ⊕κ✂θ⊕κ⟧Iι ``` [Try it online!](https://tio.run/##XY9Pa8MwDMXPzafQUQYPmvbYUwkMCt0Iy6mMHYKrJqau0vhPoYx@dk/eoYOdJKGn33syY@/N1Luc2xRGTBo@lxp2fE2xi97ygOpLbarT5AGTAnsCfJ8iHlApBd/VYhuCHRjb6YpWaZhFuyiiLd9x1vBmOQXsnDVUxlfLx1LPInUaalVaAf3i98RDHHGW@Zllx8bThTjSEbt0EQ85aZ0wP@hGPhA2d@OoGcV/Lrn/5AWs4Wn9fyVfAblA0MqXEZs@xELfVI@c63q1Xq3zy839AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of characters. Explanation: Uses brute force, in particular it always tries flipping one character, which is pointless. ``` ⊞υ⟦⁰S⟧Fυ ``` Start a breadth-first search with `0` flips and the initial input. ``` ¿¬ⅉ« ``` Stop when a solution has been found. ``` ≔⊟ιθ ``` Remove the current string from the search term, leaving the flip count. ``` ¿⊙θ⁻✂θ⌕θκλ¹κ ``` If there is a character that exists in a disjoint range, then... ``` FLθ⊞υ⟦⊕Σι⁺⮌…θ⊕κ✂θ⊕κ⟧ ``` ... reverse each nontrival prefix of the string and push the result to the search list with an incremented flip count, otherwise... ``` Iι ``` ... output the flip count as a string. 99-byte faster version based on @Ajax1234's second version, assuming it's correct (it only flips nontrivial proper prefixes), can easily deal with the second longest test case on TIO: ``` ≔Lθη⊞υ⟦⁰θ⟧Fυ¿¬ⅉ«≔⊟ιθ≔ΦLθ∧κ⁻§θκ§θ⊖κζ¿¬›Lζη«≔Lζη≔Φζ∨⁼§θκ§θ⁰‹κ⌈⌕Aθ§θ⊖κζ¿ζF⁻Eζ⁺⮌…θκ✂θκLθ¹Eυ§κ¹⊞υ⊞O⊕ικIι ``` [Try it online!](https://tio.run/##fZHJbsIwEIbP8BQ@jiVXIhROPUXpIiQoUXuqEAcrDMTCOMQLoql49tQ2a3vAlrzMeH5/M1OUXBcVl22bGiNWCsaoVraEmjJS0qdu7kwJjpFZj5F67g3LShNwlIglgffKwhdQSslPt3OKz6stCB9c@7dn26uQFvWtdKoWsGZkIpQzkNqRWuAeakbWwXe9PmOhcYPKon9Ow2CkCcLn39808hvpJlIfeTp/E2pOCXX@QTWMTDW81I7LeyS98PUYjYnYfC82buMl1CKVMvjvQl@wI3dDSSziMfkJ3waGXPrzB@5QG4Tsu5CYlb6SEcRHf0pRYLwFiksZkygdJNwVYX20U3LuXdinW9TcVhpG6koX@uTlAxhKgyTXQlnIuLHeFcyH7qFtZ7OE9dmjn302iGvi9wEb@pmw4XzePuzkLw "Charcoal – Try It Online") Link is to verbose version of code. Works with both strings and lists. Explanation: ``` ≔Lθη ``` Keep track of the minimum number of runs found so far. ``` ⊞υ⟦⁰θ⟧Fυ ``` Start a breadth-first search with `0` flips and the initial input. ``` ¿¬ⅉ« ``` Stop when a solution has been found. ``` ≔⊟ιθ ``` Remove the current string from the search term, leaving the flip count. ``` ≔ΦLθ∧κ⁻§θκ§θ⊖κζ ``` Get the list of indices of starts of new runs (excluding the first run). ``` ¿¬›Lζη« ``` If this does not exceed the minimum number of runs found so far: ``` ≔Lζη ``` Update the minimum number of runs in case this entry has fewer. ``` ≔Φζ∨⁼§θκ§θ⁰‹κ⌈⌕Aθ§θ⊖κζ ``` Keep only those runs which are potentially worth reversing, of which there are two sorts: either the first element is the same as that of the run, or the previous run is not the last run of its element. ``` ¿ζ ``` If there are any such runs, then: ``` F⁻Eζ⁺⮌…θκ✂θκLθ¹Eυ§κ¹ ``` For each run, compute the result of flipping up to that run, but then delete any results seen previously. ``` ⊞υ⊞O⊕ικ ``` Push the new run with the incremented flip count to the search list. ``` Iι ``` If there were no such runs, this can only happen when there are no disjoint runs of an element, which means that we've found a solution, so output its flip count. [Answer] # JavaScript (ES6), ~~124~~ 109 bytes Expects a string. Performs a breadth-first search. ``` f=(s,n=N=0,r)=>!/(.)(?!\1).+\1/.test(s)|[...s].some((c,i)=>n&&f((r=c+[r])+s.slice(i+1),n-1))?N:n==N&&f(s,++N) ``` [Try it online!](https://tio.run/##dc5BbsIwEAXQfU8BLNCMbCbYphsklxvkAsACuQ4KSm2Uibri7mFShBCEzmJWT///0@H3wKGtz90i5e/Y95UH1smXfqlb9F/TAghhM90ZJLUzBXWRO2C8bImI98T5JwIEXYtN83kF0Pqgtu0eFRM3dYhQK4M6LQziplwn78uBsVaqxD7kxLmJ1OQjVDAzdoY4eVxRTJYfI/OsxNhXY83ImFfjhiD3UGLcyFj3lPSuyw3ErlZ39c9mMdJnbkrM52izlP1FyRvUO@PMTch2ezf9FQ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: s, // s = input string n = // n = remaining number of iterations N = 0, // N = total number of iterations r // r = reversed prefix, initially undefined ) => // !/(.)(?!\1).+\1/ // success if there isn't any character appearing .test(s) | // twice with some other characters in between [...s].some((c, i) => // for each character c at position i in s: n && f( // unless n = 0, do a recursive call: (r = c + [r]) + // update the reversed prefix s.slice(i + 1), // append the non-reversed suffix n - 1 // decrement n ) // end of recursive call ) ? // end of some(); if truthy: N // we've found a solution: return N : // else: n == N // if it was the root call of the attempt with && // N iterations: f(s, ++N) // increment N and try again ``` [Answer] # [C(GCC)](https://gcc.gnu.org/) ~~218~~ ~~210~~ 203 bytes? *-8 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*, *-7 bytes thanks to myself* ``` f(int*x){int*c,*y=x,o=0,h,i,p=0;while(*y){for(c=y;*y==*++c;);while(*y-*++c&&*c);if(*c){if(y-x)for(c=y,p++;*y==*++c;);for(i=0;i+x<c;x[i++]=*--c,*c=h)h=i[y=x];o++;}else for(c=y;*c==*++y;);}return o-p+p%2;} ``` [Try it online](https://tio.run/##jZDJboMwFEXX7VegVIk8UTF55bg/QllUDgRLFBAhKgjx7fTZQJpVQRYe8Hn3vmvlXpWa3nSpivslPd/ai67e848pQ7psSYcHsyhGetmxSnosZ5rV0hM/uS5SRHo8ZFWDlOwFIJJQqgR@XLrmfDoRhYXOECwDLL3b4aWG1ZQ@15nfGsQ17c5KdLGmNJHEdcFfyRznUsfQRyIqKBvT4pY6D3NlRXoQGZu0vTelU7k1rY@BGCeI4Hx/6RLh4fWlbuCYocNRf5YHliGTM07w4LOAeSPG4n9kB2agHVjIVr1wGzXQTtUVDFgEY1ekGQ@Whjbjze38@cy7HXGfS8Jlt6PB0DpGdvZtKg7Dh2@zVW4duXXji5QRCLafZvYw@DxzKzNnj5bn4jZEZJk1yjj9Ag) This code is based on idea of creating a machine, that always does the right shuffle, or at least after finishing can decide, how it is improvable. For some strange reason, it works. The most effective way to unshuffle the poker chips would be to link two pieces (at one place) of the same value every round, without breaking any. However, this is not always possible (the 10th and 11th test case). When the machine runs into a such situation, where nothing can be linked, it will do a sneaky shuffle that brings a linkable block of numbers on the top. The fact that this machine runs only on one path means it can choose the wrong one, and do more (still less than types of numbers) sneaky shuffles, but the right amount of normal shuffles. My theory is, that every deck can be unshuffled with at most one sneaky shuffle, because every two of these are basically a shift, that can be created by rearranging the previous shuffles. That is, why the output is `o-p+p%1`, where o is the total amount of shuffles and p the amount of sneaky shuffles. But, sadly, I don't have the mathematical tools needed to prove this last theory, so I would be really grateful, if someone could find a counterexample, or correct my naive maths. [Answer] # [Python](https://www.python.org), 157 bytes ``` def f(x): X=[x,0];n=len(x);m=n//max(x);r=range(1,n) while X: x,c,*X=X if all(x[j]==x[j//m*m]for j in r):return c for i in r:X+=[x[i::-1]+x[i+1:],c+1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVJRbsIwDNU-6Sm88tNC2EghEirqzlGpqqaqpCOoBNSGrTvLNImf7U7b504yOwkCRY3s5_ds187H9_HdbA_6fP46mWa2-vncyAaaaIjTYJRnxcDm5VpnrdQIrfeZfnzcVwPZXdZV-kVGnOk4GL1tVSshR9FoYDWb5FmOpmqgattoKHZlluGN4sm-bA4d7EBp6OK0k-bUaaiRTLCycJpPsXKh0nTGyykaU56WrJ7y0jX5e_dnZG-e66qXPWQQhmFQcJaUMHuCuTXZxU2CgpyLy4NiwXycLSy0IAidG1ZCkAfwLNnSpx6DT-4CLg23QUFBSkPfVWutK4Hc26BrJrkSuIep6sIWwOpM4OFMWNrKFRI2i7AZhBcRNfHNWprTUcDdwgpcj0v_A8K2sLQcPyQR0EgD2oihjVyn_dAfW2VapWUf4RMBwBUbqPQGTDEv4R6XMQ4JxwjrcDf76hjJ16plYJw2CqlEGMeWNCCliZRzjp3SJkIdG-LArfryLv8B) Note: it is extremely inefficient, but it eventually terminates correctly. ]
[Question] [ In [Super Auto Pets](https://teamwoodgames.com/s), players build teams of animals that face off in battles to ~~the death~~ unconsciousness. Each animal has an Attack and Health value, and combat occurs in iterations of the following process: 1. The front animals of each team deal damage to each other equal to their Attack at the same time. 2. Both animals lose Health points equal to the damage taken. Health points are never restored in battle. 3. Animals with 0 Health or less faint and are removed from the battle. As an example consider two teams A and B, which will be represented by a list of tuples (Attack, Health). A: [(2, 3), (2, 2), (3, 1)] B: [(1, 3), (3, 4), (1, 2)] To illustrate the battle, the teams will be displayed so that the front animals are facing each other. I will also label each animal for convenience. A battle between these teams would go as follows: ``` Pig Beaver FishA Duck FishB Otter Step 0: (3, 1) (2, 2) (2, 3) -> <- (1, 3) (3, 4) (1, 2) A and B line up opposite each other, with their first animals ready to attack . The arrows show the direction each team is facing. Step 1: (3, 1) (2, 2) (2, 2) | (1, 1) (3, 4) (1, 2) FishA and Duck attack each other, with FishA dealing 2 damage, and Duck dealing 1. Both are still conscious, so they will attack again next step. Step 2: (3, 1) (2, 2) (2, 1) | (3, 4) (1, 2) This time FishA leaves Duck with -1 HP, so Duck faints, but FishA survives its attack. Next for B is FishB, but FishA is still alive. Step 3: (3, 1) (2, 2) | (3, 2) (1, 2) FishB knocks out FishA and survives FishA's attack with 2 HP. Now Beaver gets to attack Step 4: (3, 1) | (1, 2) Beaver and FishB both drop to 0 HP and faint, leaving only Pig and Otter Step 5: | Otter and Pig knock each other out, leaving no more pets. ``` Since neither A or B was resilient enough to survive the battle, the result is a draw. If A had any pets left when B's Otter fainted, A would have won (and similar for B in the opposite case). ### The Challenge Your challenge is to write a program or function which takes two teams of pets and outputs the result of their battle. The teams may be empty, and do not have to have the same number of pets. Your input format may consist of any structure(s) describing the order of each team and the Health and Attack of each animal in that order. Above I have used a list of tuples, each list representing a team in order, and each tuple representing one animal. However, you do not have to conform to this format as long as your input contains the necessary data. Your solution should output one of three distinct values (which you should specify!) corresponding to a win by the first team, a win by the second team, or a draw. To fulfill this, you also must specify which parts of your input correspond to which team [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply, and this is Code Golf, so shortest answer wins. ### Examples The examples take input in the first method described, and output either "A wins!", "B wins!", or "Draw!". I have created a [reference implementation in Python 3](https://tio.run/##nZNLb9swDIDv/hVcerEBNchj7YBiGSChvfUwbL0ZRiCk8izUlgWJRloU/e0Zrbh@pEgP1UGUyY8URdL2BYvarA@5qyvAF6vNP9CVrR3CvfbI4KGxpYoi9SwrOnjYQBoBrTjs7UrjJYN1wiBeM1h2ctXKVSevGVy18orBjyRjI893j@UgV2P5vY2cBYeEfbg3xJ/EO2rO8BMy3Hg28uRFX844yg4X8CCfqGy4r6Gkgnqoc8AmlDLmiHL3xOBW5cp4lczhTu6Koxmcsk55ZVoXo8AqnEePKoe//PfW66opJeraxPwmNCoNfUq1oZbRlmUMxBlLApe/wKO7CUnuC02XcZDmkTz6h17A3TM6uUPAQhEtu8zpI9fOI/G6kmWrUyFnJavemW9l9zK@LZQssaCx4eki6wnRE2IgREuMgnSGy02Pj/wHIz816nxw/rmBxfCqEHduaxsvkjEuzuNijEcdb2rsStaeRmVzChtnYHbr5P7bLKhV2ebzGcxhr40f46LH@UdcdPghrx1wqiC1Fd7/zyNuHXU6zmc0HK/8bZZMlDQXr@JU@Uf5pkSynI4XxU@mcBId/gM) on TIO. ``` A: [(1, 3), (3, 1), (3, 2), (2, 2), (6, 5), (5, 7)] B: [(3, 1), (1, 1), (1, 2), (1, 2), (4, 3)] Result: A wins! A: [(2, 2)] B: [(2, 2)] Result: Draw! A: [] B: [(1, 1)] Result: B wins! A: [(1, 3), (3, 1)] B: [(3, 1), (1, 1), (1, 2), (1, 2), (4, 3)] Result: B wins! ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` UMθ⮌ιW⌊θ«≔Eθ⊟κιUMιEκ⎇ν⁻μ§§ι¬λ⁰μF²¿›⌊§ικ⁰⊞§θκ§ικ»I↨Eθ¬ι±¹ ``` [Try it online!](https://tio.run/##TY8xb4MwEIVn@BU3niVXKqRph0xphihDIlR1QwxW4oQT2AQb0lZVfzv1qZSw@JN87717dyyVOzaqHoa9um4aY5Q9YSvhTd@08xpJiFX8UVKtAfdkyfQGWyHgO47W3tPFYvCxIWuuWAkhgYIhmoWRBJZUEt61s8p9oQ0/ZHuPRsK629mT/sR/BvWh6bDmpEd@jOAG0blxgKkAOgNunVaddlOfmbcafZD1vpwGLQ/uu/50q/gnzhzZDjfKd/iqwrXjLdyAOOmgL2ETJoJLDEOe55hIWIQJLiQkI1NmOvJZwpK5lPAiCgn5pEzuTOd84sSiKIaHW/0L "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of lists of tuples and outputs `1` if `A` wins, `-1` if `B` wins and `0` for a draw. Explanation: ``` UMθ⮌ι ``` Reverse each list so that the front animals are now at the end of the lists. ``` W⌊θ« ``` Repeat while both teams have animals. ``` ≔Eθ⊟κι ``` Pop the front animals from both of the lists. ``` UMιEκ⎇ν⁻μ§§ι¬λ⁰μ ``` Perform an attack. ``` F²¿›⌊§ικ⁰⊞§θκ§ικ ``` Push those animals that still have positive health back to their team. ``` »I↨Eθ¬ι±¹ ``` Output the final result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` z0_ṚŻ€$Ṗ€Ɗ€1¦»0ZȦƇ€µƬẈ€ẠÞḢIṠ ``` A monadic Link that accepts a list of the teams as lists of animals each of which is a list of positive integers, `[attack, health]`, and yields `[-1]` if the first team wins, `[0]` if there is a draw, or `[1]` if the second team wins. **[Try it online!](https://tio.run/##y0rNyan8/7/KIP7hzllHdz9qWqPycOc0IHWsC0gYHlp2aLdB1Illx9qBvENbj615uKsDyHq4a8HheQ93LPJ8uHPB////o6M1DHUUjDV1FDSMdRQMobQRiDaC0mY6CqYg2lRHwVwzlksnGq7SEEEbIdMmIBNjuWIB "Jelly – Try It Online")** ### How? ``` z0_ṚŻ€$Ṗ€Ɗ€1¦»0ZȦƇ€µƬẈ€ẠÞḢIṠ - Link: teams µƬ - collect up input while distinct, repeatedly applying: z0 - transpose the teams with filler 0 (pair up animals) Ɗ€1¦ - apply to the first pair of animals: $ - last two links as a monad: Ṛ - reverse Ż€ - prefix each with a zero _ - animals subtract that (vectorises) Ṗ€ - remove the last (third) value from each »0 - max with zero (vectorises) Z - transpose back to teams ȦƇ€ - for each team keep those without zeros Ẉ€ - length of each for each collected input ẠÞ - sort by: all? Ḣ - head I - forward differences Ṡ - sign (vectorises) ``` [Answer] # [Perl 5](https://www.perl.org/), 112 bytes ``` sub{($A,$B)=@_;while(@$A&&@$B){map$_[$_][0][1]-=$_[1-$_][0][0],0,1;map$$_[0][1]<1&&shift@$_,@_}@$A?A:@$B?B:Draw} ``` [Try it online!](https://tio.run/##rVLbToNAEH3nKybNysVspbTWJiDhkr6Z2BffKBJMl5YoF6GkMYi/jrMUrFEfTHSyyZmdnXNmGCZnxdO8JZHZltVDLROHElcx7cA47OInJtvEEUUbQ3US5iTwSOB7E9/T/LGJN23c3yc@nVDN4DkY7hKuNVEsd3G0t0lA7aBBJcvRUcpy9WURHprWEKKskAUPJEeigObh0SjMfArejILW45TjtMcrCnOOcwoLH8CnAnwY5w887YTTz3jJ9ZF3YqEEtsBbwi64RFfqB@khDr@2o7Q7fN03xa7Jvyh@mdf/zENQahRJXmTC6LAPJDAwVpUMluE@1PVlleSsMACXBjZJXm9YFKds0/186/go51mumG@lui5fDVXdFty/vzi31p7qqYVepUhqukpA4jQ3y7yI0300wh4cHc7Gs0WJrtu5WjmivBAuqNI7rmL05K0pkqhfXR7rdIAwYM/4CBZI2aMEOki3qztY3eDwRrwgih@yVMeUdToyhKZ9Bw "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [D€gW_#\‚ε`нUćXR0Dǝ-W1@išë\]`.S ``` Assumes the attacks of animals are always positive. Input as a pair of lists of pairs, where the first inner pairs are the attacking animals. Outputs `-1` if team A wins; `0` if it's a draw; and `1` if team B wins. [Try it online](https://tio.run/##yy9OTMpM/f8/2uVR05r08HjlmMNNjxpmnduacGFv6JH2iCADl@NzdcMNHTKPLjy8OiY2QS8YqDg62kjHOFYHSBoBSWMdw9hYHYXoaEOwoLGOCZA0BErFxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/2iXR01r0sPjlWMONz1qmHVua8KFvaFH2iOCDFyOz9UNN3TIPLrw8OqY2AS94P9KemE6/6OBwEjHOFYHSBoBSWMdw1ggFW0IFjPWMQGShkAZoKBCNELYEEwawbWZ6ZgCSVMdc7BmiLwhlDSCkyZA3VCDQNpASo3gZkNsNcS0ibCJsQA). **Explanation:** ``` [ # Loop indefinitely: D # Duplicate the current pair of lists # (which is the implicit input in the first iteration) €g # Pop the copy, and get the length of each inner list W # Push the minimum length (without popping) _ # If this smallest length is 0 (so a team is without animals): # # Stop the infinite loop \ # If not, discard the list of lengths  # Bifurcate; short for Duplicate & Reverse copy ‚ # Pair the two together ε # Map over each pair of lists: ` # Pop and push the two lists separated to the stack н # Pop and push the first pair of the top lists, # which is the attacking animal U # Pop and store this pair in variable `X` ć # Extract head on the other list; push remainder-list and first # item separated to the stack, which is the animal that's being # attacked X # Push the attacking animal-pair from variable `X` R # Reverse its [ATK,HP] to [HP,ATK] 0Dǝ # Replace its HP (at index 0) with 0: [0,ATK] - # Subtract this from the animal that's being attacked W # Push the minimum of this animal (without popping) 1@i # If it's >=1 (so the animal is still conscious): š # Prepend it back to the list ë # Else: \ # Discard the unconscious animal from the stack ] # Close the if-statement and loop ` # Pop and push the lists separated to the stack .S # Compare the two lists (-1 if a<b; 0 if a==b; 1 if a>b) # (which is output implicitly as result) ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~124~~ 123 bytes ``` a->f(a,b),b->f(b,a) a=\ans_1 b=\ans_2 o=sign(a.length-b.length) k=B[1].x f(A,B)=\join(\{A[1].y>k:[A[1]-(0,k)],[]\},A[2...]) ``` Exits upon error. Output is `o`, with its value being `-1` if `B` wins, `0` if tie, and `1` if `A` wins. Input is two lists of points. The graphs will further specify how to input the lists. I had a lot of fun solving this in Desmos! Actions are super fun to mess around with, and this was the perfect challenge to showcase that. [Try It On Desmos!](https://www.desmos.com/calculator/ovvheziqp7) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/yhyajwsdeg) ### Explanation I'm going to explain the expressions a little out of order so that it makes more sense. I don't know why I didn't order it properly initially but whatever. --- ``` a=\ans_1 b=\ans_2 ``` Takes in input. ``` k=B[1].x f(A,B)=\join(\{A[1].y>k:[A[1]-(0,k)],[]\},A[2...]) ``` This function essentially simulates one "half-turn" of the game. By "half-turn", I mean one of the teams attacking the other. In this case, the inputs are the lists `A` and `B` representing the teams of the same name, and it will simulate team `B` attacking team `A`. `k=B[1].x` is the attack of the first animal on team `B`. `\{A[1].y>k:[A[1]-(0,k)],[]\}` basically means: if the health of the first animal on team `A` (`A[1].y`) is greater than `k`, then return the list `[A[1]-(0,k)]`, which simulates team `A`'s first animal taking `k` damage. If `A[1].y>k` is false, then that means the first animal on team `A` does not survive the hit, so we return an empty list to represent that. You might be wondering why we have to return a list for `[A[1]-(0,k)]` instead of a number, since you can join a number with a list. This is because of Desmos's underlying vectorization for almost anything that you do with lists. In this case, if I had just returned `A[1]-(0,k)` instead of `[A[1]-(0,k)]`, then Desmos will vectorize the entire piecewise expression based on the empty list, which will, in turn, always make the piecewise expression equal to an empty list. By making the number into a list, we avoid this issue completely and it behaves as expected. `f(A,B)=\join( . . . ,A[2...])`: The newly calculated stats of the first animal of team `A` is then prepended with the rest of `A`. The function `f(A,B)` returns this updated list. ``` a->f(a,b),b->f(b,a) ``` The ticker runs these actions continually, which simulates the game, updating the input lists in place. `a->f(a,b)`: Team `b` attacks team `a` and updates list `a` after the attack. `b->f(b,a)`: Team `a` attacks team `b` and updates list `b`. Conveniently, the value of `a` used in this action is actually the old value of `a` before the attack on team `a` (`a->f(a,b)`) occurred, which essentially simulates the two teams attacking each other at the same time. If it used the newly updated `a`, then it would be harder to simulate the attacks as you would most likely need to keep track of list `a` before the attack, so that you can accurately apply the attack on team `b` (or else it would be team `b` attacks team `a`, then team `a` attacks team `b`, instead of attacking at the same time). Once at least one of the lists becomes empty, then the ticker errors out, because when calling the function `f(A,B)`, either `A[1]` or `B[1]` would be undefined because one of them would be empty, which will cause `A[1].y` or `B[1].x` to throw an error. When the ticker throws an error, we will know that the game is over, since the error indicates that one or both teams have no more animals. ``` o=sign(a.length-b.length) ``` Returns the final output. If `a.length > b.length` (indicates that `a` wins), then `a.length-b.length` will be positive, so `o=1`. If `a.length < b.length` (indicates that `b` wins), then `a.length-b.length` will be negative, so `o=-1`. If `a.length = b.length` (indicates that it was a tie), then `a.length-b.length` will be `0`, so `o=0`. ]
[Question] [ If we have a binary matrix then we will say that a \$1\$ is stable if it is in the bottom row or it is directly adjacent to a \$1\$ which is stable. In other words there must be a path to the bottom row consisting only of \$1\$s. So in the following matrix the \$1\$s highlighted in red are not stable. $$ 0110\color{red}{1}0\\ 0100\color{red}{11}\\ 110000\\ $$ A matrix is stable if every \$1\$ in it is stable. Your task is to take a matrix or list of rows and determine if there is someway to rearrange the rows into a stable matrix. The example above can be if we swap the top and bottom row: $$ 110000\\ 011010\\ 010011\\ $$ But the following matrix cannot: $$ 01010\\ 10101\\ 00000 $$ You may take input in any reasonable format. You may also assume that there is at least one row and that all rows are at least 1 element long. You should output one of two distinct values if it is possible to rearrange the rows into a stable matrix and the other if it is not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code with answers being scored in bytes. ## Test cases ``` 000 000 000 -> True 1 -> True 011010 010011 110000 -> True 01010 10101 00000 -> False 01010 10101 01110 -> True 01010 01100 00011 10101 -> False 10 01 -> False ``` [Answer] # [J](http://jsoftware.com/), 60 bytes ``` 1 e.i.@!@#(1*/@,@([:+./ .*^:_~1>:[:|@-/~$j./@#:I.@,)@,])@A.] ``` [Try it online!](https://tio.run/##dU5NC4JAEL3vr5g08Hvc7bhhTAhB0Cm6iUmEUl466DH86zZrUWLF8pY3M4/3Xt1b6FSQaHAgBAmaESGk@92mV1DiFWlGtqv8mEJyMx1gDOgfddGplc70naK4m9cYk623SKFHYe7RGvPeE6I8X25QgYVWsMRiAbnxl0IqfsJ8irli7j2lzqFsWkhPTdk4QrQ8JAjmQglkeuQkFJjr21B@wLGToxriGMwEDy@VnKhGneQfo@/aP11M4lDG5A3yL@Gg4nX/AA "J – Try It Online") Feels like there's a trick I'm missing, but this takes a brute force approach as follows: * For each permutation of rows... * Prepend of row of all ones... * Check if the "distance of 1" graph of the 1 positions is fully connected. * If it is, we've found a solution. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~27~~ ~~26~~ 24 bytes ``` Zy:Y@!"2G@Y)tQ&v4&1ZImvA ``` Input is a binary matrix. Output is `0` if stable, `1` otherwise. Try it at [MATL online!](https://matl.io/?code=Zy%3AY%40%21%222G%40Y%29tQ%26v4%261ZImvA&inputs=%5B0+1+1+0+1+0%3B+0+1+0+0+1+1%3B+1+1+0+0+0+0%5D&version=22.4.0) Or [verify all test cases](https://matl.suever.net/?code=%60%0AZy%3AY%40%21%222G%40Y%29tQ%26v4%261ZImvA%0A%5DDZxT&inputs=%5B0+0+0%3B+0+0+0%3B+0+0+0%5D%0A%5B1%5D%0A%5B0+1+1+0+1+0%3B+0+1+0+0+1+1%3B+1+1+0+0+0+0%5D%0A%5B0+1+0+1+0%3B+1+0+1+0+1%3B+0+0+0+0+0%5D%0A%5B0+1+0+1+0%3B+1+0+1+0+1%3B+0+1+1+1+0%5D%0A%5B0+1+0+1+0%3B+0+1+1+0+0%3B+0+0+0+1+1%3B+1+0+1+0+1%5D%0A%5B1+0%3B+0+1%5D&version=22.4.0). ### Explanation ``` Zy % Input (implicit): binary matrixz. Size. Gives [r, c], where r and c % are the numbers of rows and of columns : % Range. Gives [1, 2, ... r] (c is ignored) Y@ % All permutations of numbers 1, 2, ..., r. Gives an r-column matrix % where each row is a permutation !" % For each row 2 % Push 2 G % Push input @Y) % Apply current permutation to the rows of the input tQ % Duplicate, add 1. Gives a matrix the same size as the input with % all entries different from 0 &v % Concatenate the two matrices vertically. This has the effect of % adding a "bottom" of nonzeros to the permutation of the input 4&1ZI % Connected components, using 4-neighbourhood (i.e. not diagonals) % Each connected component of nonzeros is labelled 1, 2, ... m % Ismember: gives true if there is a connected component labelled % with 2. This can only happen if some 1 in the input is not % connected to the bottom, meaning that the current permutation % is not stable vA % Concatenate vertically. All. This acts as a cumulative "and". % The result is 1 if and only if all permutations so far were % not stable % End (implicit). Display (implicit) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 159 bytes ``` lambda l:any(f(0,len(l[0]),*sum(p,[]))for p in permutations(l)) f=lambda p,a,x,*t:a>len(t)or-(p:=p+t[a-1])-len(t)%a*t[0]+x<f(x*p,a,*t)>0 from itertools import* ``` [Try it online!](https://tio.run/##XU/NTgMhEL7zFJMmJkBZA3oxG7dHn8DbygFTtiVhgcDUtE@/wlbrzwGY@f5mSBc8xvD4lPJyGN4Wb@b3vQHfm3ChE5XC20D9KDUTvJxmmsSoGZtihgQuQLJ5PqFBF0OhnjEyDV8JSRhxFhx7s2sRyGLuaOqHtMXRdEqz7grfGY41fnt@nuiZNxdHtpNkynEGhzZjjL6Am1PMyJfrC@VSiBtGTdomvm1SkfuCexd6Am6CtnKDN1JtKgJuO4wjn02iLqDwVZpdooxpTcD6YpsmwwD2w/j634des4qkXNXUiQN1TOSGtKGLlJJ8n24Hr/lkibpVUimpKqlkrUhtfsvkyrVLNfuVeTF1g7@Uqr5/ppa7zmypq@pmXdmf9hM "Python 3.8 (pre-release) – Try It Online") Takes input as a 2d list. `f` is a function that checks if a matrix is stable. Then we just try every permutation, until we find a matrix that works. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 167 bytes ``` f=(a,...b)=>a[0]?a.some(h=>f(a.filter(_=>_!=h),h,...b)):b[b=b.map(x=>[...x]),0].map(g=(y,x)=>(e=b[~y]||0)[x]&&++e[a=2,x]+[-1,1].map(i=>g(y+i,x)+g(y,x+i)))|!/1/.test(b) ``` [Try it online!](https://tio.run/##XU7PbsIgGL/7FPOiECiFnZYlsJsvsN2QKK20smDbFVzaxOzVO4rTLTtAvu/393vXn9qXve1C1rQHM00VBxoTQgrIhZZUvWji25MBRy4qoEllXTA92HGxW/IjxMerFj4XsuAFOekODFzICA4KYqoSUnMw4iEGAsML@TWqy4VCOajVCiEjNX/Eg0IyY5hd9ZaLGozIRg@qZyuyEMLLMmc5CcYHUMCpNx9n2xuwrvwakt7ow8Y68zo2JaB4fQ7VU4I7p0sDcknZtlEor3G8rmwb3zpDXFuDCgzEd86G/bbZp/LARfiB9rdrsrkfwolSuri9TDy89WezYPeJMkZZJBmN0yIuf2U0cfPHZvuV2Wjn/1Es@v6Z5tzUOacm1d2a2N/1Gw "JavaScript (Node.js) – Try It Online") Input `-1` for true and `0` for false [Answer] # Python3, 265 bytes: ``` lambda b:any(v(i)for i in permutations(b)) from itertools import* E=enumerate def p(b,c,d): if c==len(b)-1:return 1 try: for x,y in[(0,1),(0,-1),(1,0)]: if(y:=d+y)*b[c+x][y]:return 1 except:return 0 v=lambda b:all(p(b,x,y)for x,l in E(b)for y,s in E(l)if s) ``` [Try it online!](https://tio.run/##pVHLbsMgELzzFSiXQEIqyEuVJR9z7Q84PviBVSQMCHAUvt4Fu0mj9lT5YMzszOwOWhP8p1aHd2PHLr@OsurrtoJ1VqmAbkjgTlsooFDQcNsPvvJCK4dqjEFndQ@F59ZrLR0UvdHWb8Al52roua08By3voEE1aUiLMwBFB5s8l1xF/45llvvBKsgA9DZEGqZZdxLitAJRwjCJ5y79GKG4TIrYAoUsb7cBb@qi2d7LIpQvjfi94cY/ChTc8p8HSYlSljgAz4NketYlZkkwEDdDiWNMh0eXr1YrQCl9fgk7NpXZDPazhjHKooTReAMRPMWHbz7R6WCpz4M8/iVZNM/k6YVM/acEqfsknCTnOUnip4KxQnnUoaLY9JVBERCBy@f@OiHjrtCHVpy4N2ek8Gh9VWuMy7jM/5jZIvd@kfuwyH1c5D4tcp9/u8cv) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 116 bytes ``` f=(a,p=1)=>a.some((r,j)=>r.every((c,i)=>c?(s|=p[i],l=1):!(l=s=l>s),l=s=0)&l<=s|p&&f(b=[...a],b.splice(j,1)[0]))||++a ``` [Try it online!](https://tio.run/##XVDLTgMhFN3PV9wubO9NKQWXKnVhdGF8LHQ3kogjozS0M4Gxahy/vcKY1McCck7Og8tdmo2JVXBtN1s3j3a7rRUa1ipJamF4bFYWMbBlYoHbjQ3viBVziVbHGHvVlk4zn9wHI/QqKr@IxDIQNPZHKvbteFzjgyo550azBx5b7yqLSyapFJqo76dTs@1s7CoTbQQF94UQYndmC7gNL7aQOySkFDKJUiRUJPLbJgYtXzLHv5Uz4@M/Sabcv1DuHd7MrYNrFx3UH3rPu@BWSMNnOpwnAXNRP8g0J157012aFvGNgWNgCNQCHOzBPhxDWZrSzaT@2zK5W0@Ir1IoZHNeWNAD32Q@3RAxOL@5vuKtCdHiG@@ai@bVhpO0NyTSGg6g1HRY7JbJ6yacmuoZsUxDWD1M8VEAVM06Nt5y3zzhaFSjS4oCyyDD1PBJh9sv "JavaScript (Node.js) – Try It Online") Input 0/1 matrix. Output true vs NaN. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œʒ¬!ªÐU˜!ƶsgäΔ0δ.ø¬0*šĆ2Fø€ü3}εεÅsyøÅs«à}}X*}˜0KÙg}gĀ ``` [Try it online](https://tio.run/##yy9OTMpM/f//6ORTkw6tUTy06vCE0NNzFI9tK04/vOTcFINzW/QO7zi0xkDr6MIjbUZuh3c8alpzeI9x7bmt57Yebi2uPLwDSB5afXhBbW2EVu3pOQbeh2em16Yfafj/PzraQMcQCEGkQawOmGcA5hkCeYZQHhDGxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5NPTTq0RvHQqsMTQk/PUTy2rTj98JJzUwzObdE7vOPQGgOtowuPtBm5Hd7xqGnN4T3Gtee2ntt6uLW48vAOIHlo9eEFtbURWrWn5xh4H56ZXpt@pOG/zv/o6GgDHSCM1UGjY3UUoqMNIZSBjiEQgkiIPIgNFgPyDKE8uB4DJKVQFlihAbHKDCG2YSqDOQPuSLgTYNohjoYpjo2NBQA). **Explanation:** In pseudo-code, I do the following steps (with the code-parts behind it - as you can see, the flood-fill takes up most of the bytes): 1. Get all permutations of rows of the input-matrix (`œ`) 2. Check if any permutation is truthy for the following steps (`ʒ...}gĀ`): 1. Append a row of 1s to the matrix as new bottom (`¬!ª`) 1. E.g. the permutation we want to check is: ``` 0,1,1,0,1,0 0,1,0,0,1,1 1,1,0,0,0,0 ``` 2. Then it will become this with bottom row of 1s: ``` 0,1,1,0,1,0 0,1,0,0,1,1 1,1,0,0,0,0 1,1,1,1,1,1 ``` 2. Flood-fill the matrix, using only horizontal/vertical moves - done in a similar matter as [@Jonah's J answer for the *To find islands of 1 and 0 in matrix* challenge](https://codegolf.stackexchange.com/a/188893/52210) (`ÐU˜!ƶsgäΔ0δ.ø¬0*šĆ2Fø€ü3}εεÅsyøÅs«à}}X*}`): 1. We first create a matrix of the same size with unique positive integers: ``` 1, 2, 3, 4, 5, 6 7, 8, 9,10,11,12 13,14,15,16,17,18 19,20,21,22,23,24 ``` 2. Then for each cell we get the maximum among itself and its horizontal/vertical neighbors: ``` 7, 8, 9,10,11,12 13,14,15,16,17,18 19,20,21,22,23,24 20,21,22,23,24,24 ``` 3. Which we multiply by the matrix of 0s/1s we started with (the one from step 2.1.2): ``` 0, 8, 9, 0,11, 0 0,14, 0, 0,17,18 14,15, 0, 0, 0, 0 20,21,22,23,24,24 ``` 4. And we continue steps 2.2.2 and 2.2.3 until the result no longer changes: ``` 0,24,24, 0,18, 0 0,24, 0, 0,18,18 24,24, 0, 0, 0, 0 24,24,24,24,24,24 ``` 3. Check if there is just a single island after the flood-fill (`˜0KÙg`) As for the actual code: ``` œ # Get all permutations of rows of the (implicit) input-matrix ʒ # Filter this list of matrices by: ¬!ª # Append a row of 1s: ¬ # Push the first row (without popping the matrix) ! # Convert all 0s/1s to 1s with the faculty ª # Append this row of 1s to the matrix Ð # Triplicate the matrix U # Pop and store a copy in variable `X` ˜!ƶsgä # Pop and push a matrix of the same size with values [1,length] ˜ # Flatten the matrix ! # Convert everything to 1s with the faculty ƶ # Multiply every 1 by its 1-based index s # Swap so the last copy is at the top g # Pop and push its amount of rows ä # Pop and split the list into that many equal-sized parts Δ # Loop until the result no longer changes # (which will be used to flood-fill the matrix): 0δ.ø¬0*šĆ # Surround the matrix with a border of 0s: δ # Map over each row: 0 .ø # Surround it with a leading/trailing 0 ¬ # Push the first row (without popping) 0* # Convert all 0s/1s to 0s by multiplying by 0 š # Prepend this row of 0s to the matrix Ć # Enclose; append its own head 2Fø€ü3} # Get all 3x3 blocks of this matrix: 2F # Loop 2 times: ø # Zip/transpose; swapping rows/columns € # Map over each row: ü3 # Get all overlapping triplets of this row } # Close the loop # Looking at horizontal/vertical neighbors only, get the maximum # of each 3x3 block: εε # Nested map over each 3x3 block: Ås # Push its middle row yøÅs # Push its middle column « # Merge the two triplets together à # Pop and push the maximum }} # Close the nested maps X* # Then multiply each maximum by matrix `X`, # so all cells that contained 0s become 0 again } # Close the flood-fill loop ˜ # Flatten the matrix to a list 0K # Remove all 0s Ù # Uniquify the remaining values g # Pop and push the length (only 1 is truthy in 05AB1E) }gĀ # After the filter: check if any permutations remain (length>=1) # (which is output implicitly as result) ``` [There are a bunch of 5-bytes alternatives for `˜0KÙg`](https://tio.run/##yy9OTMpM/f//9BwD78Mz0xV0uE7PifKODwAzgALGjxp2QgQDFUGCIApI//8fHW1koqMAwgZwFKujEG2ALAhRgiQMlQJTIGGYGCqOjQUA), but I haven't been able to find a 4-byter. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~129~~ 112 bytes ``` WS⊞υ⌕Aι1≔⟦⟦⟧⟧θFυ«≔⟦⟧ηFθF⊕Lκ⊞η⁺⁺✂κ⁰λ¹⟦ι⟧✂κλLκ≔ηθ»Fθ«≔⟦⟧ηFLιF§ικ⊞η⟦κλ⟧≔E⊟ι⟦Lικ⟧ιWΦ⁻ηιΦ⁴№ιEλ⁺π∧⁼ρ﹪ν²⊖⁻νρFκ⊞ιλP↔¬⁻ηι ``` [Try it online!](https://tio.run/##dVHBasMwDD0vXyF6ksGDZuy2U9hWKKyj0GPIIUu82kSz08TeBqPfnslp0uUyG2SjZ733JFe67CpX0jB8aUMKcGvb4A@@M/aIQsA@9BqDhI2xdUaERsIqXQnxkGR9b44W87woJJw48e46wCDgJ7mZMUY0IzcjdBIwnltbdepDWa9qfFH26DU2YpbSEvYUehzDgUylsJGwlkASUiEhNwXHK8DZBUWUmqT1xdM5maX/czWVGzG5y/zW1uo7NtosTOVRrFgI7MoW967lQgavJFwU/Zn4cBroxpBXHe6M5Y50xOI0x9y9hEcXrI9ikY@m5lsJma3x@RRK6rFj0NWBHFoJd4LLn9TfBC@8jHRiXpdGmsk8c1O0swvkTcv/6jF76x0Fr/DV@aWxcYLnYVinvJMY0mSdpnwfbj/pFw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of `0`s and `1`s and outputs a Charcoal boolean i.e. `-` if a stable stack exists, nothing if not. Explanation: ``` WS⊞υ⌕Aι1 ``` Input the matrix and save the positions of the `1`s in each row. ``` ≔⟦⟦⟧⟧θ ``` Start building up the permutations of the rows. ``` Fυ« ``` Loop through the rows. ``` ≔⟦⟧η ``` Start building up the permutations that include this row. ``` Fθ ``` Loop through the permutations of the previous rows. ``` F⊕Lκ ``` Loop through the possible insertion points. ``` ⊞η⁺⁺✂κ⁰λ¹⟦ι⟧✂κλLκ ``` Insert this row at that point and save it to the list of permutations. ``` ≔ηθ ``` Save the list of permutations. ``` »Fθ« ``` Loop through all of the permutations. ``` ≔⟦⟧ηFLιF§ικ⊞η⟦κλ⟧ ``` List the coordinates of all the `1`s. ``` ≔E⊟ι⟦Lικ⟧ι ``` List the coordinates of the `1`s on the bottom row, which are stable by definition. ``` WΦ⁻ηιΦ⁴№ιEλ⁺π∧⁼ρ﹪ν²⊖⁻νρ ``` While there are unknown coordinates adjacent to at least one stable coordinate, ... ``` Fκ⊞ιλ ``` ... save all the newly discovered stable coordinates. ``` P↔¬⁻ηι ``` Overwrite the output with `-` if all the coordinates were stable. ]
[Question] [ Imagine we get a slice of some mountainous region, this would result in a shape similar to this: ``` 4 _ 3 _ _ __/ \ 2 / \__/ \ _/ \_ / 1 / \ / \_/ 0 \/ 12322223210012233343221112 ``` As we can see, we can represent this (to a certain degree) with a sequence of integers. For the purpose of this challenge we define a valley as a contiguous subsequence where the values initially are decreasing and from some point on they are increasing. More formally for a sequence \$(a\_i)\_{i=1}^n\$ a valley will be indices \$1 \leq s < r < t \leq n\$ for which the following holds: * the valley's start and endpoint are the same: \$a\_s = a\_t\$ * the valley starts and ends once the region gets lower: \$a\_s > a\_{s+1} \land a\_{t-1} < a\_t\$ * the valley is not flat: \$a\_s \neq a\_r \land a\_r \neq a\_t\$ * the valley initially decreases: \$\forall i \in [s,r): a\_i \geq a\_{i+1}\$ * the valley will at some point increase: \$\forall j \in [r,t): a\_j \leq a\_{j+1}\$ Now we define the width of such a valley as the size of the indices \$[s,t]\$, ie. \$t-s+1\$. ## Challenge Given a height-profile (sequence of non-negative integers), your task is to determine the width of the widest valley. ## Example Given the height-profile `[1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2]`, we can visualize it as before: ``` 4 _ 3 _ _ __/ \ 2 / \__/ \ _/ \_ / 1 / \ / \_/ 0 \/ 12322223210012233343221112 aaaaaa ccccc bbbbbbbbb ``` Note how the second valley `[3,2,1,0,0,1,2,2,3]` does not extend further to the right because the left-most point is \$3\$ and not \$4\$. Furthermore we don't add the remaining two \$3\$s because we require that the endpoint is higher up than the second-last point. Therefore the width of the widest valley is \$9\$. # Rules * Input will be a sequence of non-negative (sorry Dutch people) integers + you can assume that there is always at least one valley * Output will be the size of the widest valley as defined above # Testcases ``` [4,0,4] -> 3 [1,0,1,0,1] -> 3 [1,0,2,0,1,2] -> 4 [13,13,13,2,2,1,0,1,14,2,13,14] -> 4 [1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2] -> 9 [3,2,0,1,0,0,1,3] -> 4 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẆµIṠḟ0ṢƑaMIḢ)Ṁ‘ ``` **[Try it online!](https://tio.run/##y0rNyan8///hrrZDWz0f7lzwcMd8g4c7Fx2bmOjr@XDHIs2HOxseNcz4//9/tLGOkY6BjiEQg0jjWAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8///hrrZDWz0f7lzwcMd8g4c7Fx2bmOjr@XDHIs2HOxseNcz4f3TP4fZHTWuOTnq4cwaQBiL3//@jo010DHRMYrl0og2BDDCGcYzAAkZgrrEOBBkBIUShoQmICRSEajbSgcgaQVkgVWD9YD4ImujA9BvCzDWGWgJRagwRMgZzQerBRpuANUKEgCpiAQ "Jelly – Try It Online") (added two more test cases which I previously failed to fulfil). ### How? ``` ẆµIṠḟ0ṢƑaMIḢ)Ṁ‘ - Link: list of integers Ẇ - all contiguous substrings µ ) - for each substring, X: I - deltas Ṡ - sign (-ve:-1, 0:0, +ve:1) ḟ0 - filter out zeros Ƒ - is invariant under: Ṣ - sort M - get maximal indices of X a - (vectorising) logical AND I - deltas Ḣ - head Ṁ - maximum ‘ - increment ``` [Answer] # JavaScript (ES6), ~~111~~ ~~108~~ ~~99~~ 97 bytes ``` a=>a.map(o=(p,x)=>a.some(P=q=>(~x?x<0?i?q<P:q>P&&i++:i=0:q>=p)||(o=o<--x|q==P|q-p?o:x,P=q,0)))|-o ``` [Try it online!](https://tio.run/##fY7LbsIwEEX3fEVWyBY2eXlDlEl@IXvEwqIBBQFjk6rywuqvp34EVFGlGlua8Zx7ry/yS47Hx6A@@R0/@ukEk4RGbm9SEQSimKF@HPHWkw40NOTbtKbO2qHVdVfppluvh82mGiBzAyhqrdNhzbmxGqCzmqsWK8OcmGWUUstxOuJ9xGu/veKZnMhesIyJA6VJmibl6m2Zu2W4/wFFgIoZEX@QksVTuIqGufCtexSLIgdERTF3XhlywuxLsKdn/it/925Vzh@M8nIp0Tt6xPsufkuE0Ii9nKYf "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(o = // initialize the output o to a non-numeric value (p, x) => // for each value p at position x in a[]: a.some(P = // initialize P to a non-numeric value q => // for each value q in a[]: ( // exit if something goes wrong: ~x ? // if x is not equal to -1: x < 0 ? // if x is negative: i ? // if we're in the increasing part: q < P // exit if q is less than P : // else: q > P && i++ // increment i if q is greater than P : // else: i = 0 // initialize i to 0 (decreasing part) : // else: q >= p // exit if q is greater than or equal to p ) || ( // if we didn't exit: o = // update the output o: o < --x | // decrement x; if o is less than x q == P | // or the last value is equal to the previous one q - p ? // or the last value is not equal to the first one o // leave o unchanged : // else: x, // update o to x P = q, // update the previous value P to q 0 // force this iteration to succeed ) // ) // end of some() ) | -o // end of map(); return -o ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ ~~115~~ ~~89~~ ~~87~~ ~~86~~ ~~152~~ 149 bytes ``` lambda a:max(r-l+1for l,v in e(a)for r,w in e(a)if max(a[l+1:r]+[0])<v==w*any(s(a[l:i])[::-1]+s(a[i:r])==a[l:r]for i,_ in e(a)));e=enumerate;s=sorted ``` [Try it online!](https://tio.run/##bU7dDoIgFL7vKbiUpE2QmyiexFijhYtNsaFlPb1xIKu5Bmzn@z1cn8Olc2yq5WFqdHs6a6RFqx@Z3zQ5rTuPGnJH1iGTaQzQk3GGtkbg1FVwCq/yqlB4f5dyXGv3zHoQhFW4EmJDVQ7YBhuWEgSvoM2S49yG8c5I426t8Xowu172nR/Mebp66wZUZxUnBeEKE1SuPhwNXHx/eBY1Bgr/UUqSLgsnxSmHMZB86Q18MrL3BIHYGjEcTuYqOm/bfhvK9y9Sqlz0Qx4UaFnu5rE5qSk3vQA "Python 2 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 77 bytes ``` \d+ $* M&!`\b(1+),((?!\1)(?!1+\2)1*,)+((?!\1)1*(?(3)\3|\2))*\1\b 1 O^` \G,|$ ``` [Try it online!](https://tio.run/##NUwxDsIwDNz9i0oFOYkH7GTv2AnxAQuFCgYWBsTYv6eJE2T7dPbd@fv6vT@PcsI1F30GmD1cz1PWDTk4QlwmZVeRg4pjTy6MG3tcMDqNexWcV9YNGOB2z6Ar7XMpiS6UgCvaGBPbBDhSb6nVLZwarceWEeqSDNYslrS9VaJ/mO1jHL@7Lx4 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` M&!` ``` List, rather than counting, overlapping matches. ``` \b(1+), ``` The valley's start is captured into `\1`. This must then not match again until the end. Since we don't capture the comma, this also prevents higher values from matching. ``` ((?!\1)(?!1+\2)1*,)+ ``` Match the decreasing values. The `(?!1+\2)` prevents the any pass through the loop from being greater than the previous. (The first time through `\2` isn't set so it fails to match trivially.) The capture includes the trailing comma as that's golfier. ``` ((?!\1)1*(?(3)\3|\2))* ``` Match the increasing values. This time `((?3)\3|\2)` means that each match is required to be at least as long as the previous value, or the last decreasing capture the first time through the loop. ``` \1\b ``` Finally the end of the valley must be the same height as the start. ``` 1 ``` Delete the heights, leaving the commas. (This is slightly easier than counting the heights as some of them might be zero.) ``` O^` ``` Sort in reverse order i.e. most commas first. ``` \G,|$ ``` Count the number of commas on the first line, plus one. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` →▲mΓ€fȯΛEtġ≤Q ``` [Try it online!](https://tio.run/##yygtzv6fq1H8qKmxSPPQtv@P2iY9mrYp99zkR01r0k6sPzfbteTIwkedSwL///8fbaJjoGMSyxVtCKTBGMo2AvONQDxjHQgyAkKIMkMTEBMoCNFppAORNIKyQIrAusF8EDTRgWk3hJpqDLUBotI4FgA "Husk – Try It Online") ## Explanation I use a similar algorithm as [Jonathan Allan](https://codegolf.stackexchange.com/a/175345/32014). ``` →▲mΓ€fȯΛEtġ≤Q Input is a list, say [3,1,0,1,1,0,2,3] Q Nonempty slices: [[3],[1],[3,1],[0],...,[3,1,0,1,1,0,2,3]] f Keep those that satisfy this: Argument is a slice, say [3,1,0,1,1,0,2] ġ≤ Cut into non-increasing pieces: [[3,1,0],[1,1,0],[2]] t Drop first piece: [[1,1,0],[2]] ȯΛ Each remaining piece E has all elements equal: false, [1,1,0] has different elements m Map over remaining slices: Argument is a slice, say [1,0,1,1] Γ Break into head 1 and tail [0,1,1] € Index of first occurrence of head in tail: 2 ▲ Maximum: 2 → Increment: 3 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 31 bytes ``` ¡ãYÄÃrc k_ò< Åd_äa x}îbZvÃrÔ+2 ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=oeNZxMNyYyBrX/I8IMVkX+RhIHh9w65iWnbDctQrMg==&input=W1s0LDAsNF0sClsxLDAsMSwwLDFdLApbMSwwLDIsMCwxLDJdLApbMTMsMTMsMTMsMiwyLDEsMCwxLDE0LDIsMTMsMTRdLApbMSwyLDMsMiwyLDIsMiwzLDIsMSwwLDAsMSwyLDIsMywzLDMsNCwzLDIsMiwxLDEsMSwyXSwKWzMsMiwwLDEsMCwwLDEsM11dCi1RbQ==) Saved a 10 bytes by taking inspiration from Zgarb's Husk answer. I still think this can be improved, but I haven't found it yet. Explanation: ``` ¡ãYÄÃrc Get all segments k_ à Remove ones where: ò< A non-increasing sub-segment Å Other than the first one d_äa x} Has different heights ® à For each remaining segment: bZv Get the second index of the first character rÔ Maximum +2 Increase by 2 ``` ]
[Question] [ This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge based around defining languages and proving they are Turing complete. This is the cops' thread. [The robbers' thread is here](https://codegolf.stackexchange.com/questions/162291/escape-from-the-tarpit-robbers). # Cops As a cop, you will prepare two things: * A formal specification of a programming language, or other computational system. (Computational systems are defined below.) * A proof that your system is Turing complete, according to the somewhat strict definition below. You will post your specification of your language, and the robbers will try to "crack" it by proving its Turing completeness. If your submission is not cracked within one week you can mark it as safe and post your proof. (Your answer can be invalidated if someone finds a flaw in your proof, unless you can fix it.) This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the winner will be the answer that has the most votes, and which is not cracked or invalidated. The challenge is open-ended - I won't be accepting an answer. For the sake of this challenge, a computational system will be defined as four things: * A "program set" `P`. This will be a countably infinite set, e.g. strings, integers, binary trees, configurations of pixels on a grid, etc. (But see the technical restriction below.) * An "input set" `I`, which will also be a countably infinite set, and need not be the same set as `P` (although it can be). * An "output set" `O`, which similarly will be a countably infinite set, and may or may not be the same as `P` or `I` * A deterministic, mechanistic procedure for producing an output `o` from program `p` and input `i`, where `p`, `i` and `o` are members of `P`, `I` and `O` respectively. This procedure should be such that it could, in principle, be implemented on a Turing machine or other abstract model of computation. The procedure may, of course, fail to halt, depending on the program and its input. The sets `P`, `I` and `O` must be such that you can express them as strings in a computable manner. (For most sensible choices this will not matter; this rule exists to prevent you from choosing strange sets, such as the set of Turing machines that don't halt.) Turing completeness will be defined as the following: * For any computable partial function `f` from `I` to `O`, there exists a program `p` in `P` such that given `p` and input `i`, the output is `f(i)` if `f(i)` has a value. (Otherwise the program doesn't halt.) The word "computable" in the above definition means "can be computed using a Turing machine". Note that neither [rule 110](https://en.wikipedia.org/wiki/Rule_110) nor [bitwise cyclic tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) are Turing-complete by this definition, because they don't have the required input-output structure. Lambda calculus is Turing complete, as long as we define `I` and `O` to be the [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals). (It is not Turing-complete if we take `I` and `O` to be lambda expressions in general.) Note that you don't have to provide an implementation of your language, but you are welcome to include one in your answer if you like. However, you shouldn't rely on the implementation to define the language in any way - the spec should be complete in itself, and if there is a contradiction between the spec and the implementation this should be treated as a bug in the implementation. [Answer] # Blindfolded Arithmetic Possibly a fairly easy language to start off with, relatively speaking. (There are limits on how difficult a language I can make because I have to prove it Turing-complete myself!) For this language, the program set is the set of Blindfolded Arithmetic programs as given in the section "program" below, the input set is the set of positive integers, and the output set is the set of integers (the entire set, not just the positive integers). This language is fairly interesting – maybe even practically useful – because it has a more or less total lack of control flow, being entirely based on computations on numbers you can't see. That makes it potentially useful as a language for implementing programs inside [homomorphic encryption](https://en.wikipedia.org/wiki/Homomorphic_encryption) systems. # Specification Blindfolded Arithmetic is an esoteric programming language with the following specifications: ## Data storage A state of a running Blindfolded Arithmetic program consists of six variables, each of which can store an integer. (There are no limits on how large or small these integers can get; in particular, they can go negative.) The variables are called `a`, `b`, `c`, `d`, `e`, and `i`. At the start of the program, `a` to `e` inclusive are each initialised to 0, and `i` is initialised to a positive integer taken from user input. (If no input is available, `i` is initialised to 1.) If the program ceases execution (this can only occur due to division by zero), the value of `i` immediately before the division was attempted is used as the program's output. ## Program A Blindfolded Arithmetic program is a list of commands, each of which has one of the following forms (where *v* can be replaced by any variable name, potentially a different name each time it's used): * *v* `=` *v* `+` *v* * *v* `=` *v* `-` *v* * *v* `=` *v* `*` *v* * *v* `=` *v* `/` *v* Note that each operand of the commands *must* be a variable; this language does not allow the use of literal integers. Execution of the program is performed by running each of the commands in sequence, and then looping back to the start and continuing to run the commands in sequence again, ad infinitum (or until there's an attempt to divide by zero, which ends the program). Each command has the same semantics as you'd expect from the notation, which is no different from that used by most practical programming languages: the values of the second and third variables metioned in the command are taken, an arithmetic operation (add/subtract/multiply/divide respectively for the four forms of command) is applied to them, and the resulting value stored into the first variable. Division here is integer division, rounding towards 0. There is no control flow of any kind, other than program exit; the commands always cycle in sequence, up until a division by zero (if any) occurs and ends the program. In particular, there's no way to directly read variables, only to use them as a source of calculations whose results impact the values assigned to other variables. ]
[Question] [ Your task is to write a RoboZZle interpreter. If you're not familiar with the game, please watch the [video at robozzle.com](http://www.robozzle.com/) or read my description below. A robot lives on a rectangular grid of squares coloured red, green, blue, or black. Black squares are inaccessible. The others are accessible and some of them contain a star. The goal is to collect all the stars without stepping on the black squares or falling off the map. The robot occupies one square and faces a particular direction - left, right, up, or down. It follows assembly-like instructions grouped into subroutines F1,F2,...,F5. An instruction is a pair of a predicate ("none", "if on red", "if on green", "if on blue") and an action ("go forward", "turn left", "turn right", "paint the current square red", "paint it green", "paint it blue", "do nothing", "call F1", ..., "call F5"). Calls to subroutines use a stack and can be recursive. Just like in conventional programming, after the last instruction of a subroutine is completed, execution carries on from the point where the subroutine was called. Execution begins from the first instruction of F1 and continues until either the robot has visited all squares with stars, or when the robot steps on a black square or outside the map, or 1000 instructions have been executed (failed predicates and "do nothing" actions don't count), or there are no more instructions to execute (stack underflow). Inputs: * `a` - a 12x16 character matrix (as usually represented in your language, e.g. array of strings) that encodes a map - `'#'` for inaccessible (black) squares, `'*'` for squares with a star, `'.'` for the rest * `c` - a 12x16 character matrix describing the colours of accessible squares - `'R'`(red), `'G'`(green), or `'B'`(blue). Inaccessible squares will be represented by an arbitrary letter from the three. * `y` and `x` - the robot's 0-based row and column; `a[y][x]` is guaranteed to be `'.'` * `d` - the direction the robot is facing: `0 1 2 3` for right, down, left, up, i.e. towards `(y,x+1)`,`(y+1,x)`,`(y,x-1)`,`(y-1,x)` * `f` - a single string, the concatenated implementations of F1...F5. Each implementation is a (possibly empty) sequence of predicate-action pairs (at most 10 pairs per subroutine), terminated with a `'|'`. + predicates: `'_'` none, `'r'` red, `'g'` green, `'b'` blue + actions: `'F'` go forward, `'L'` turn left, `'R'` turn right, `'r'` paint red, `'g'` paint green, `'b'` paint blue, `'1'` call F1, ..., `'5'` call F5, `'_'` do nothing You don't have to name you inputs like the above, but their values must be as specified. Output: `1` (or `true`) if the robot collects all stars according to the rules, `0` (`false`) otherwise. [Example](http://www.robozzle.com/beta/index.html?puzzle=9744&program=OfjjdeGISAWaaaa): ``` a=["################","################","##*....*...*#.##","##.####.#####.##","##.####.#####.##","##.####*...*#.##","##.########.####","##*........*#.##","################","################","################","################"] c=["RRRRRRRRRRRRRRRR","RRRRRRRRRRRRRRRR","RRRBBBBRGGGGRRRR","RRBRRRRGRRRRRRRR","RRBRRRRGRRRRRRRR","RRBRRRRRGGGBRRRR","RRBRRRRRRRRGRRRR","RRRBBBBGGGGBRBRR","RRRRRRRRRRRRRRRR","RRRRRRRRRRRRRRRR","RRRRRRRRRRRRRRRR","RRRRRRRRRRRRRRRR"] y=2; x=6; d=2 // and then depending on "f": f="_FrLg2_1|_FbLrR_2||||" // result:1 f="_FrRg2_1|_FbLrR_2||||" // result:0 (stepped on a black square) f="_FrLrL_1|_FbLrR_2||||" // result:0 (1000-step limit exceeded) f="_FrLg2__|________||||" // result:0 (stack underflow) ``` Another [example](http://www.robozzle.com/beta/index.html?puzzle=328&program=OemmgekXzms1IBgI9IqyaWadIga), involving "paint" instructions: ``` a=["#***************","#*###*###*###*##","#*###*###*###*##","***#***#***#***#","***#***#***#***#","*###*###*###*###","***#***#***#***#","***#***#***#***#","***#***#***#***#","*###*###*###*###","*.*#***#***#***#","***#***#***#***#"] c=["RGGGGGGGGGGGGGGG","RBRRRGRRRGRRRGRR","RBRRRGRRRGRRRGRR","RBRRGGGRGGGRGGGR","BRRRGGGRGGGRGGGR","BRRRGRRRGRRRGRRR","BRRRGGGRGGGRGGGR","RBRRGGGRGGGRGGGR","BRRRGGGRGGGRGGGR","BRRRGRRRGRRRGRRR","BGRRGGGRGGGRGGGR","RBRRGGGRGGGRGGGR"] y=10; x=1; d=0 f="_2_R_R_1|_FgRgFgFg3rRr4b2_Fgb|_F_F_R|_2_L_r||" // result:1 ``` To generate your own test, go to a puzzle from [the list at robozzle.com](http://www.robozzle.com/beta/index.html), try to solve it (or not solve it), press F12 in your browser, type in the JS console: ``` r=robozzle;s=JSON.stringify;with(r.level)console.log('a='+s(Items)+'\nc='+s(Colors)+'\ny='+RobotRow+'\nx='+RobotCol+'\nd='+RobotDir+'\nf='+s(r.encodeSolution())) ``` and reformat the result for your language. Shortest wins. No loopholes. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 574 bytes ``` Z*A:-findall(X^Y-D,(nth0(Y,Z,O),nth0(X,O,C),plus(32,C,D)),L),list_to_assoc(L,A). N^C^G^[P,I|R]^F^X^Y^D:-map_assoc(\=(74),G);N<1e3,get_assoc(X^Y,G,J),J>67,put_assoc(X^Y,G,78,H),T=N+1,((I\=95,(P=95;get_assoc(X^Y,C,P)))->(between(49,53,I),plus(48,M,I),nth1(M,F,Q),append(Q,R,S),T^C^H^S^F^X^Y^D;member(I,`RL`),E is(D-I//3)mod 4,T^C^H^R^F^X^Y^E;I=70,(D=0,U is X+1;D=1,V is Y+1;D=2,U is X-1;D=3,V is Y-1),(U=X;V=Y),T^C^H^R^F^U^V^D;I>97,put_assoc(X^Y,C,I,W),T^W^H^R^F^X^Y^D);N^C^H^R^F^X^Y^D). A+C+F+L:-A*G,C*B,split_string(F,"|","",P),maplist(string_codes,P,[M|N]),0^B^G^M^[M|N]^L. ``` [Try it online!](https://tio.run/##nVFhc5pAEP3ur3D0y508DKipUYszCoGQQWMu1WiMhxqpdQaVATL5wn@3p6Wtdsyk7e0sw759@25vNwi3/nYpR2@r3e6p0KrLX1ebxcz3yZCPZANkE39TyAhPuKM4/A9xB50i8F8jUi5Bh0EpHAp/FcVuvHVnUbR9IQ5atJjpcp1bfNyDnbAJN7nQ5EZdXs@ClPaskWqFwqKN7mfVK2PpxWlGUGHhluK2@amK4PUUr17hhuKL1pVUEGI/a7VLkJ74Nk4VdPQopXKTzL34zfM2pFLDZRl22n/lCp19IB6mkg5M3FPMgsDbLMg9GB7EFeIFN/zhZ@@NtbeeeyGxMWXOlOI6u4qIIdsXF2W63i6ylbSApQXXDVurKiCGpqAvuNmhpDYMTcVgH4wOQSnNyPugnGZklYL0tWFjoI3okWifD0QXdrP250x02HjcMx@PrjfEXE/6McRSWpIumZJTl1sFC3qhjSjwV7EbxeFqsyQmckkOuZwYHMSe9lslP1Luy3bhRehh3Em6EwqFt8VyO/wQcqe4242n@cLpmUJA@fyxn4cEN3/s70Cndf9Q@HdaxY8LJ9J4yqzTI3iszRizfvv7kOD/cgEdSGegIz/P@n8t62OtiZRzSy4TpiauuWRLU1g5ZGFlXhLxXIDCWCJIjhsmSU5SuapwpZjJfAc "Prolog (SWI) – Try It Online") This defines a predicate that when called succeeds if the all the stars are successfully collected and fails otherwise. The predicate takes the arguments as such: `a+c+f+x^y^d.`. `a` and `c` must be lists of backtick quoted strings, while `f` must be a double quoted string. ## Explanation This program contains three predicates, `*/2`, `^/2`, and `+/2`. The `*/2` predicates which is defined on the first line is responsible for part of the input processing. The `^/2` predicate recursively calculates how the robot moves step by step and succeeds if the robot legally collects all the stars and fails otherwise. The `+/2` predicate is the main predicate of the program and prepares the input for the `^/2` predicate with some help from the `*/2` predicate. Note that each of these predicates technically takes only two arguments but using operators and pattern matching they can behave as if they had more arguments (I discuss this phenomenon more in depth [here](https://codegolf.stackexchange.com/a/153160/20059)). ### `*/2` ``` Z*A:-findall(X^Y-D,(nth0(Y,Z,O),nth0(X,O,C),plus(32,C,D)),L),list_to_assoc(L,A). ``` This predicate takes two arguments. The first is a list of lists of character codes (this is how Prolog parses backtick quoted strings). The second is a associative map from points in the 12x16 map (represented as `X^Y`) to 32 plus the character code stored at that point in the list of lists of character codes. The 32 is added to each of the character codes so that for the color matrix it will turn the uppercase color characters into lowercase color characters. The way it does this is generates a list of pairs of points and the character codes at that point using [`findall/3`](http://www.swi-prolog.org/pldoc/doc_for?object=findall/3). It then uses [`list_to_assoc/2`](http://www.swi-prolog.org/pldoc/doc_for?object=list_to_assoc/2) to create the corresponding associative map from points to the character code at that point. The [`findall/3`](http://www.swi-prolog.org/pldoc/doc_for?object=findall/3) predicate is a builtin takes a "template" as its first argument, a goal as its second argument and a list as its third argument. The predicate fills the list with all the possible values of the template that cause the goal to succeed. Due to operator precedence, the template that is passed to `findall/3` in `*/2` is parsed as `(X^Y)-D`. The `-` operator represents a pair of two values in Prolog so the template represents the point's location (`X^Y`) paired with 32 plus the point's character code (`D`). Note that the `^` used in representing the point is in no way connected to the `^/2` predicate. Let us consider the goal that is passed to the `findall/3` predicate. ``` nth0(Y,Z,O),nth0(X,O,C),plus(32,C,D) % Note that the O (oh) is not a 0 (zero) ``` The goal contains three predicates each of which need to succeed for the goal to succeed. The [`nth0/3`](http://www.swi-prolog.org/pldoc/doc_for?object=nth0/3) predicate which is used twice is used to get the value at a particular index of the list (the `0` in its name indicates it is zero indexed). The first call to it stores the `Y`th row of the character matrix in `O` while the second call stores the `X`th character in that row in `C`. The final predicate [`plus/3`](http://www.swi-prolog.org/pldoc/doc_for?object=plus/3) succeeds if its first two arguments sum to its third argument. This is used to make the character code in the pair is 32 greater than the character code in the character matrix which as stated above will turn all uppercase letters into lowercase letters. Finally `findall/3` stores all of the `X^Y-D` combinations that cause its goal to succeed in the list `L` which the associative map is built from. ### More Coming Soon... [Answer] # JavaScript (ES6), ~~298~~ ~~276~~ 264 bytes *Saved 8 bytes thanks to @ngn* Takes input as `(a,c,x,y,d,f)`, where `a` and `c` are arrays of arrays of characters. Returns `0` or `1`. ``` (a,c,x,y,d,f,k=1e3)=>(g=(F,p=0,s=f.split`|`[F],r=a[y])=>!k|!r|x&16||r[x]<'$'?2:/\*/.test(a)?(r[x]=o=0,(I=s[p+1],P=s[p])&&(P<'b'|P==c[y][x].toLowerCase()&&I!='_'&&k--?+I?o=g(I-1):I=='L'?d--:I=='R'?d++:I<'b'?y+=(d&=3,x-=~-d%2,2-d)%2:c[y][x]=I:0,o||g(F,p+2))):1)(0)&1 ``` ### Test cases ``` let f = (a,c,x,y,d,f,k=1e3)=>(g=(F,p=0,s=f.split`|`[F],r=a[y])=>!k|!r|x&16||r[x]<'$'?2:/\*/.test(a)?(r[x]=o=0,(I=s[p+1],P=s[p])&&(P<'b'|P==c[y][x].toLowerCase()&&I!='_'&&k--?+I?o=g(I-1):I=='L'?d--:I=='R'?d++:I<'b'?y+=(d&=3,x-=~-d%2,2-d)%2:c[y][x]=I:0,o||g(F,p+2))):1)(0)&1 getA = _ => [ "################", "################", "##*....*...*#.##", "##.####.#####.##", "##.####.#####.##", "##.####*...*#.##", "##.########.####", "##*........*#.##", "################", "################", "################", "################" ].map(s => [...s]); getC = _ => [ "RRRRRRRRRRRRRRRR", "RRRRRRRRRRRRRRRR", "RRRBBBBRGGGGRRRR", "RRBRRRRGRRRRRRRR", "RRBRRRRGRRRRRRRR", "RRBRRRRRGGGBRRRR", "RRBRRRRRRRRGRRRR", "RRRBBBBGGGGBRBRR", "RRRRRRRRRRRRRRRR", "RRRRRRRRRRRRRRRR", "RRRRRRRRRRRRRRRR", "RRRRRRRRRRRRRRRR" ].map(s => [...s]); y=2; x=6; d=2; [ "_FrLg2_1|_FbLrR_2||||", // result:1 "_FrRg2_1|_FbLrR_2||||", // result:0 (stepped on a black square) "_FrLrL_1|_FbLrR_2||||", // result:0 (1000-step limit exceeded) "_FrLg2__|________||||" // result:0 (stack underflow) ] .forEach(code => console.log('Example #1', code, '-->', f(getA(), getC(), x, y, d, code))); getA = _ => [ "#***************", "#*###*###*###*##", "#*###*###*###*##", "***#***#***#***#", "***#***#***#***#", "*###*###*###*###", "***#***#***#***#", "***#***#***#***#", "***#***#***#***#", "*###*###*###*###", "*.*#***#***#***#", "***#***#***#***#" ].map(s => [...s]); getC = _ => [ "RGGGGGGGGGGGGGGG", "RBRRRGRRRGRRRGRR", "RBRRRGRRRGRRRGRR", "RBRRGGGRGGGRGGGR", "BRRRGGGRGGGRGGGR", "BRRRGRRRGRRRGRRR", "BRRRGGGRGGGRGGGR", "RBRRGGGRGGGRGGGR", "BRRRGGGRGGGRGGGR", "BRRRGRRRGRRRGRRR", "BGRRGGGRGGGRGGGR", "RBRRGGGRGGGRGGGR" ].map(s => [...s]); y=10; x=1; d=0; [ "_2_R_R_1|_FgRgFgFg3rRr4b2_Fgb|_F_F_R|_2_L_r||" // result:1 ] .forEach(code => console.log('Example #2', code, '-->', f(getA(), getC(), x, y, d, code))); ``` ### Commented ``` ( // main function taking: a, c, x, y, d, f, // - input variables k = 1e3 // - k = instruction counter ) => ( // g = ( // g = recursive execution function, taking: F, // - F = subroutine id p = 0, // - p = instruction pointer s = f.split`|`[F], // - s = instruction string r = a[y] // - r = current row in a[] ) => // !k | // if we've executed 1000 instructions !r | x & 16 || // or we've felt out of the map r[x] < '$' ? // or we've reached a black square: 2 // exit with error code 2 : // else: /\*/.test(a) ? ( // if there are still some stars: r[x] = o = 0, // mark the current cell as visited (I = s[p + 1], P = s[p]) && // I = instruction, P = predicate ( // if P is defined: P < 'b' | // if the predicate is '_' P == c[y][x].toLowerCase() // or it matches the color of the cell && I != '_' // and the instruction is not '_', && k-- ? // then decrement k and: +I ? // if I is '1' ... '5': o = g(I - 1) // process call to subroutine : // else: I == 'L' ? // if I is 'L': d-- // turn left : // else: I == 'R' ? // if I is 'R': d++ // turn right : // else: I < 'b' ? ( // if I is not a color: y += ( // I must be 'F', d &= 3, // so make the bot advance x -= ~-d % 2, // by updating x 2 - d // and y ) % 2 // ) : // else: c[y][x] = I // paint the current cell : // else: 0, // do nothing o || // provided that o is equal to 0, g(F, p + 2) // go on with the next instruction ) // end of instruction execution ) : // else: 1 // success: return 1 )(0) & 1 // initial call to the subroutine F1 ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~236~~ 233 bytes -3 thanks to Erik the Outgolfer Now that I've given away the bonus, I'm posting a sample solution to my own challenge. There's room for improvement here - feel free to copy and golf further. ``` a c r d f←⎕⋄c←819⌶c⋄F←0,('|'=¯1⌽f)/⍳≢f⋄t←n←0 {~(⊂r)∊⍳⍴a:0⋄'#'=r⌷a:0⋄p q←2↑f↓⍨⊃⌽t⋄(_←p≡'|')∧×≢t:0⋄_:∇t↓←¯1⋄(⊃⌽t)+←2⋄~p∊'_',r⌷c:∇0⋄n+←1⋄n>999:0⋄(r⌷a)←'.'⋄~'*'∊a:1⋄r+←(q≡'F')×11 9○0j1*d⋄d+←4|'.R.L'⍳q⋄q∊'rgb':∇(r⌷c)←q⋄q∊⎕d:∇t,←F[⍎q]⋄∇0}0 ``` [Try it online!](https://tio.run/##1ZQ9b9NQFIZ3/4orZbh2SIwdIYRzVaQkkrNk8oqQ5dhOFDD@uHEFlNChVKHNR9WqqjIxwAIbAwgmFvpP7h8J59w2DEkcIcHCGfxx3/c577nXkr00qgYvvSjpV/3IGw4H/lKcXQ0SMT43FHHylifd5OAgCpnHfMZZwHrMZjmLWcqypUd8wklAeuAGSkyPfXh6YFpi9s2HNxu7VFQ6ons/P5ti9qOn3RXzL@L0Qw/UHNRY5rw6VMXkiGviZILy/KtXN8BAS3SPi9n3m7eUZGCuifEFxF2K@ScxeQMtc5BUF5RUnL6HJGjy8XoBEbmk3DpsIkdgfI4zgPmW0@7IdtPjwxRyqUsrmOWjH8EYZfTHDy3Lkr1UOYwG61SnCNIyBdSro42jX81wCJtq1wvTJJZYTI0nZjkAOUD53ojqjt6hsMkM1jLM5f0uxUzZ3MfmKwlONJDTV2DRfiTmZ9ljkHC@18YSbssGwYOfHNHSWlECRtJayc5aUaVR2U1W/oQs61B4KZf0bWQTymlDbZA6RsnLVrKJQHtr5l@SxdNKEqdtbid/5xaQq9zNE9J3n1BbZjb/2Vf5H0hUxhcNslmSvJFbirL6@ygN0lJr5L5Wo67NO/2aa45cu9vhjlsbQUHi/B0xiwCnADCIOszDNA0DksTEI93I85@SYbbv8VArTOedomamYRhV7EiiwbNBTsIXfhgGYaDt2ok7cm9rbTCcZT8OQt6LkufaLw "APL (Dyalog Classic) – Try It Online") Same as the above, expanded with comments: ``` ⎕io←0 ⍝ 0-based indices (not counted in the score) a c r d f←⎕ ⍝ decompose eval'ed input (⎕) into variables c←819⌶c ⍝ make c lowercase F←0,('|'=¯1⌽f)/⍳≢f ⍝ split f at the '|'-s t←n←0 ⍝ t:stack, n:step counter { ⍝ lambda ~(⊂r)∊⍳⍴a:0 ⍝ if the robot is off the map, return 0 '#'=r⌷a:0 ⍝ if the robot is on a wall, return 0 p q←2↑f↓⍨⊃⌽t ⍝ current instruction - p:predicate, q:action (_←p≡'|')∧1≥≢t:0 ⍝ if at end of func and stack is empty, return 0 _:∇t↓←¯1 ⍝ if at end of func, pop from stack and recurse (⊃⌽t)+←2 ⍝ increment program counter (top of stack) ~p∊'_',r⌷c:∇0 ⍝ if predicate doesn't match cell colour, recurse n+←1⋄n>999:0 ⍝ if too meany steps, return 0 (r⌷a)←'.' ⍝ consume star ~'*'∊a:1 ⍝ if no more stars left, return 1 r+←(q≡'F')×11 9○0j1*d ⍝ if action is F, move forward d+←4|'.R.L'⍳q ⍝ if action is L or R, turn left or right q∊'rgb':∇(r⌷c)←q ⍝ if action is paint (r,g,b), do it q∊⎕d:∇t,←F[⍎q] ⍝ if action is F1...F5, push on stack and recurse ∇0 ⍝ action is nop (_), recurse }0 ⍝ call the lambda (argument will be ignored) ``` ]
[Question] [ Imagine enumerating the elements of rhombi which grow `[1],[1,3,1],[1,3,5,3,1],…` (only odd numbers such that they align nicely). This would look like as follows, note that you always begin enumerating with `1`: ``` 01 1 02 03 04 1 2 3 4 05 06 07 08 09 … 5 10 11 12 13 (1) (1,3,1) (1,3,5,3,1) (1,3,5,7,5,3,1) … ``` Now if you start summing the columns (`[1],[2],[1,3,5],[4],[5],[2,6,10],…`) you get the *rhombus sequence*. These are the first 100 elements of said sequence: ``` 1,2,9,4,5,18,35,24,9,10,33,60,91,70,45,16,17,54,95,140,189,154,115,72,25,26,81,140,203,270,341,288,231,170,105,36,37,114,195,280,369,462,559,484,405,322,235,144,49,50,153,260,371,486,605,728,855,754,649,540,427,310,189,64,65,198,335,476,621,770,923,1080,1241,1110,975,836,693,546,395,240,81,82,249,420,595,774,957,1144,1335,1530,1729,1564,1395,1222,1045,864,679,490,297,100 ``` ## IO You are free to choose one of these three input/output methods (you won't need to handle invalid inputs): * Given an integer *n* output the *n*th element in that sequence (0- or 1-indexed, your choice) * Given an integer *n* output first *n* elements of that sequence * Print/return the sequence indefinetely ## Testcases Please refer to the first 100 terms above, here are some larger examples (1-indexed): ``` 101 -> 101 443 -> 1329 1000 -> 49000 1984 -> 164672 2017 -> 34289 2018 -> 30270 3000 -> 153000 ``` [Answer] ## [Snowman](https://github.com/KeyboardFire/snowman-lang), 72 bytes ``` ((}1vn2nD#`nPnCdU!*2nM1`nR:#nSNaB#`nS2nMNdE;aM|#NdE2nP+#`nSNdE`|aA#nM*)) ``` This is a subroutine that takes 1-indexed input and returns the corresponding output via the permavar `+`. [Try it online!](https://tio.run/##NY69DoIwGEV3nuKzbcKPESijBhP/RgiRuFNpDR38aoToIPjqtQze5dyc4eZeRd/Z1kiV@zYIJv7CDI@0wQoP8rKIMix4g@c1xboUe@drZ0p52ohipI4ZVsvZutqMYkexiMLQ@t7NPEGDRvjwOOZpOnnSeOCi2s4AYRryLbAgMY8h6dG87wL/hJUC8mU6Ajb/AjrUfUVC4hZQ2R8 "Bash – Try It Online") ``` (( // begin subroutine } // we'll only need 3 variables - b, e, g 1vn2nD // b = 0.5 #` // retrieve input and swap, now b = input and e = 0.5 nP // power, resulting in b=sqrt(input) nC // ceiling - this gives the index i of the rhombus we want dU!* // keep a copy of i in the permavar ! for later use 2nM1`nR // generate the range [1, 2i) : // map the following block over the range... #nS // subtract i, resulting in e.g. [-3 -2 -1 0 1 2 3] for i=4 NaB // absolute value - [3 2 1 0 1 2 3] #`nS // subtract from i, giving [1 2 3 4 3 2 1] 2nMNdE // double and decrement, [1 3 5 7 5 3 1] ;aM // map | // shove the rhombus columns into g #NdE2nP // b = (i-2)^2 +#` // move b into e and replace it with the original input nSNdE // subtract the two and decrement, giving input-(i-2)^2-1 `|aA // this is the index into the rhombus columns that we want #nM* // multiply by the original input and return )) ``` This uses basically the same algorithm as [Mr. Xcoder's answer](https://codegolf.stackexchange.com/a/152086/3808)—the only difference is that here we only generate the columns of the rhombus we need, which is the ceil(sqrt(n))th one. To illustrate why this works, here are the inputs that correspond to each rhombus: ``` rhombus # inputs 1 1 2 2 3 4 3 5 6 7 8 9 4 10 11 12 13 14 15 16 ... ``` Note that the left column corresponds exactly to the ceiling of the square root of each element in the right column. To get the 1-based index from here, we simply subtract the square of the index of the previous rhombus. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḥ€€’ŒBFị@× ``` [Try it online!](https://tio.run/##y0rNyan8///hjiWPmtaAUMPMo5Oc3B7u7nY4PP2/oYFBkM7hdhWghPt/AA "Jelly – Try It Online") A full program / monadic link returning the **N**th term (1-indexed). > > I noticed that each sum is the index of that column in the overall list of columns (the input itself) multiplied by the index of that column in the corresponding Rhombus, so no need to actually generate the rows. > > > ## How? ``` Ḥ€€’ŒBFị@× ~ Full program. I'll call the input N. € ~ For each integer X in the range [1, N]. Ḥ€ ~ Double each integer in the range [1, X]. ’ ~ Decrement (subtract 1). ŒB ~ Bounce (element-wise). Palindromize each. F ~ Flatten. ị@ ~ Get the element at the index N in our list. × ~ Multiply by N. ``` [Answer] # JavaScript (ES7), ~~42~~ 41 bytes *Saved 1 byte thanks to @ovs* 0-indexed. A closed-form expression derived from [A004737](https://oeis.org/A004737). ``` n=>((k=n**.5|0)-Math.abs(n+k*~k))*2*++n+n ``` ### Test cases ``` let f = n=>((k=n**.5|0)-Math.abs(n+k*~k))*2*++n+n console.log(f(101-1)) // 101 console.log(f(443-1)) // 1329 console.log(f(1000-1)) // 49000 console.log(f(1984-1)) // 164672 console.log(f(2017-1)) // 34289 console.log(f(2018-1)) // 30270 console.log(f(3000-1)) // 153000 ``` [Answer] # Befunge, ~~62~~ 60 bytes ``` &:1>:00p:*`| 00:-\*:g00:<>2-\-0v!`\g *.@v+1<g00:<^*2g00_2*1+ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjoxPjowMHA6KmB8CjAwOi1cKjpnMDA6PD4yLVwtMHYhYFxnCiouQHYrMTxnMDA6PF4qMmcwMF8yKjEr&input=MTk4NA) **Explanation** ![Source code with execution paths highlighted](https://i.stack.imgur.com/1UT4Q.png) ![*](https://i.stack.imgur.com/jmV4j.png) We start by reading the one-based element number, *n*, from stdin, and saving a duplicate. ![*](https://i.stack.imgur.com/z4eIY.png) Then we determine which rhombus we're in, by counting up an integer, *r*, until `r*r >= n`. ![*](https://i.stack.imgur.com/RFUim.png) The column offset from the right hand side of the rhombus, *c*, is `r*r - n`. ![*](https://i.stack.imgur.com/BX1CZ.png) To get that offset reflected around the centre axis, we check if `c >= r`. ![*](https://i.stack.imgur.com/aZli8.png) And if it is, then the reflected *c* becomes `r*2 - 2 - c`. ![*](https://i.stack.imgur.com/SetfX.png) Once we have the reflected *c*, the sum of the column is simply `(c*2 + 1) * n`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes ``` {⍵×2×⌊/|⍵-.5+×⍨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bD083Ojz9UU@Xfg2Qo6tnqg3k9a541LsZyK0FKjsEYhsaAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` _.ạ²€ṂḤ× ``` [Try it online!](https://tio.run/##y0rNyan8/z9e7@GuhYc2PWpa83Bn08MdSw5P/390z@F2IN/9//9oraLEvPRUDUMdBUNzTSBhAGSZmBiDWAYGQNLSwkRHwcjA0BxMWugoGAPFYwE "Jelly – Try It Online") ### How it works ``` _.ạ²€ṂḤ× Main link. Argument: n _. Subtract 0.5; yield (n - 0.5). ²€ Square each; yield [1², 2², ..., n²]. ạ Take the absolute differences of (n - 0.5) and each of the squares. Ṃ Take the minimum. Ḥ Unhalve; double the minimum. × Multiply the result by n. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` *¹D▼mo≠-.¹m□ḣ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxf@1Du10eTRtT27@o84FunqHduY@mrYQJP7/v5EBAA "Husk – Try It Online") Similar to the existing Jelly and APL answers. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Ñ*UDza½nUÃrm ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0SpVx7JhvW5Vw3Jt&input=MzAwMA) ``` Ñ*UDza½nUÃrm :Implicit input of integer U Ñ :Multiply by 2 * :Multiply by UÇ : Map the range [0,U) ² : Square a : Absolute difference with ½ : 0.5 nU : Subtracted from U à : End map r : Reduce by m : Minimum ``` ]
[Question] [ This has no practical purpose but it could be fun to golf. # Challenge Given a number *n*, 1. Count the amount of each digit in *n* and add 1 to each count 2. Take the prime factorization of *n* 3. Count the amount of each digit in the prime factorization of *n*, without including duplicate primes 4. Create a new list by multiplying together the respective elements of the lists from steps 1 and 3 5. Return the sum of that list For example, 121 has two `1`s and a `2`, so you would get the following list from step 1: ``` 0 1 2 3 4 5 6 7 8 9 1 3 2 1 1 1 1 1 1 1 ``` The prime factorization of 121 is 112, which gives the following list for step 3: ``` 0 1 2 3 4 5 6 7 8 9 0 2 0 0 0 0 0 0 0 0 ``` Note how we did not count the exponent. These multiply together to get: ``` 0 1 2 3 4 5 6 7 8 9 0 6 0 0 0 0 0 0 0 0 ``` And the sum of this list is 6. # Test cases ``` 1 -> 0 2 -> 2 3 -> 2 4 -> 1 5 -> 2 10 -> 2 13 -> 4 121 -> 6 ``` # Notes * [Standard loopholes](//codegolf.meta.stackexchange.com/q/1061/75524) are forbidden. * Input and output can be in any reasonable format. * You should leave ones (or zeros for step 3) in the list for digits that did not appear in the number. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) & [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) (avoid pairing the two vectors) ``` DF‘ċЀ⁵ ÆfQÇæ.Ç‘$ ``` A monadic link taking a positive integer and returning a non-negative integer. **[Try it online!](https://tio.run/##y0rNyan8/9/F7VHDjCPdhyc8alrzqHEr1@G2tMDD7YeX6R1uB0qo/P//39DIEAAA "Jelly – Try It Online")** ### How? ``` DF‘ċЀ⁵ - Link 1, digitalCount: number(s) e.g. [13,17] D - to decimal list (vectorises) [[1,3],[1,7]] F - flatten [1,3,1,7] ‘ - increment (vectorises) [2,4,2,8] ⁵ - literal ten 10 Ѐ - map across (implicit range [1,2,3,4,5,6,7,8,9,10]) ċ - count [0,2,0,1,0,0,0,1,0,0] ÆfQÇæ.Ç‘$ - Main link: positive integer, n e.g. 11999 $ - last two links as a monad: Ç - call the last link (1) as a monad [0,2,0,0,0,0,0,0,0,3] ‘ - increment (vectorises) [1,3,1,1,1,1,1,1,1,4] Æf - prime factorisation [13,13,71] Q - deduplicate [13,17] Ç - call the last link (1) as a monad [0,2,0,1,0,0,0,1,0,0] æ. - dot product 8 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ṾċЀØD ÆfQÇ×Ç‘$S ``` [Try it online!](https://tio.run/##ATMAzP9qZWxsef//4bm@xIvDkOKCrMOYRArDhmZRw4fDl8OH4oCYJFP/UsW8w4figqxH//8xMjE "Jelly – Try It Online") Developed independently from and not exactly the same as [the other Jelly solution](https://codegolf.stackexchange.com/a/151631/75553). **Explanation** I'm gong to use `242` as an example input. ``` ṾċЀØD Helper link Ṿ Uneval. In this case, turns it's argument into a string. 242Ṿ → ['2','4','2']. [2,11] → ['2', ',', '1', '1']. The ',' won't end up doing anything. ØD Digits: ['0','1',...,'9'] ċЀ Count the occurrence of €ach digit in the result of Ṿ ÆfQÇ×Ç‘$S Main link. Argument 242 Æf Prime factors that multiply to 242 → [2,11,11] Q Unique elements → [2,11] Ç Apply helper link to this list → [0,2,1,0,0,0,0,0,0,0] Ç‘$ Apply helper link to 242 then add 1 to each element → [1,1,3,1,2,1,1,1,1,1] × Multiply the two lists element-wise → [0,2,3,0,0,0,0,0,0,0] S Sum of the product → 5 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~43~~ 41 bytes ``` ⎕CY'dfns' +/×/+/¨⎕D∘.=⍕¨(⎕D,r)(∪3pco r←⎕) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepc2vqHp@tr6x9aARR0edQxQ8/2Ue/UQys0QFydIk2NRx2rjAuS8xWKHrVNAIppgkz5DzaGy5CLC8IwgjGMYQwTGMMUxjA0gLPgqgyNDAE "APL (Dyalog Unicode) – Try It Online") **How?** `r←⎕` - input into `r` `3pco` - prime factors `∪` - unique `⎕D,r` - `r` prepended with `0-9` `⍕¨` - format the factors and the prepended range `⎕D∘.=` - cartesian comparison with every element of the string `0123456789` `+/¨` - sum each row of the two tables formed `×/` - multiply the two vectors left `+/` - sum the last vector formed [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes ``` fS¢>O ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/LfjQIjv////NzMwB "05AB1E (legacy) – Try It Online") ``` f list of prime factors (without duplicates) of the implicit input S characters, all of the digits ¢ count each of the characters in the implicit input > increase each of the counts O sum (implicit output) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 44 bytes ``` Y_N_.aM,tT++o>aTa%o{a/:olPBo}$+y*Y_N JUQlM,t ``` Takes input from command-line argument. [Try it online!](https://tio.run/##K8gs@P8/Mt4vXi/RV6ckRFs73y4xJFE1vzpR3yo/J8Apv1ZFu1ILqEDBKzQwB6jk////ugX/jYyNzC2NTM0MAA "Pip – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~136~~ 127 bytes ``` lambda a:sum(''.join(u(a)).count(`i`)*-~`a`.count(`i`)for i in range(10)) u=lambda a:[`j`for j in range(2,a)if a%j<1>len(u(j))] ``` [Try it online!](https://tio.run/##TY0xDsIwDAB3XuEF1UZQkYyI8hFAsoEWErVOG5KBha8HdQHW0@lufKVHUFum5lR6GS43Adk984BVVfvgFDMKUX0NWROyY1pt3iz8B7oQwYFTiKL3Fs2WaJGbb@vInmfF/xS7FnIdyNLvzaFv54cnOpcxOk0wobGGygc "Python 2 – Try It Online") # Credits * Reduced from 136 bytes to 127 by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ]
[Question] [ Given a string, return a table where the first column has the unique letters of the string in order of occurrence and subsequent columns list the indices of that letter in the string, using zero or one-based indexing. Horizontal whitespace does not matter, as long as the left-most column is vertically aligned. Indices must be in ascending order from left to right. ### Examples Using zero-based indexing and given "abracadabra", return ``` a 0 3 5 7 10 b 1 8 r 2 9 c 4 d 6 ``` Using one-based indexing and given "3141592653589793238462643383279503", return: ``` 3 1 10 16 18 25 26 28 34 1 2 4 4 3 20 24 5 5 9 11 32 9 6 13 15 31 2 7 17 22 29 6 8 21 23 8 12 19 27 7 14 30 0 33 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes ``` ,‚å∏ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR2wSdRz07gCwFdWNDE0NTSyMzU2NTC0tzS2MjYwsTMyMzE2NjC2Mjc0tTA2N1AA "APL (Dyalog Unicode) ‚Äì Try It Online") (`‚å∏` is 3 bytes) Uses 1-based indexing. `‚å∏` is the key operator. Here it behaves as a monadic operator. It applies the function `,`, concatenate the left argument with the right argument, to each unique element in its right argument and the indices of that unique element in the original argument. [Answer] # [Haskell](https://www.haskell.org/), 86 bytes ``` import Data.List f s=unlines[x:concat[' ':show i|i<-[0..length s-1],s!!i==x]|x<-nub s] ``` Defines a function, `f`, which returns a String containing this output. [Try it online!](https://tio.run/##TY4xb4MwFIT3/IoXL0kVQAEDAQSRKnXIkK1DB9eqHOIUK85zgo3CwH@nVE3V3nK6@264Rtiz1Hoc1eVqWgcvwolgr6ybncBWHWqF0rK@qA3WwrEFLArbmDuoQZU@WweBlvjpGrB@yD07n6uq6vnQlz52B7B8vAiFUIGVt05iLT9m8BCDa@deXbtHWPawWgEpyNMv3W7/0RP88Hf8G8AwlaUPjOym98aDN9PqI/GAPB9aUYujmOw70jAOkzxKE5pk@SanEc3iNEpjSjMabfJkTQnn4xc "Haskell ‚Äì Try It Online") How? ``` import Data.List -- Imports Data.List. This contains the nub method which is necessary f s = -- Define a function, f, which takes one argument, s [ |x<-nub s] -- Loop through nub s with the variable x. Nub removes duplicates from a list, in this case the input. [ |i<-[0..length s-1] ] -- Go thourgh the list [0,1,2...] until the length of the input - 1. Basically a indexed for-loop ,s!!i==x -- Filter out everything where the char at this index isn't x ' ':show i -- i as a string with a space before it concat -- Flatten the whole list x: -- Append x before it unlines -- Insert newlines between every element in the list and flatten it, effectively putting every element on it's own line ``` [Answer] # [kdb+/q](https://en.wikipedia.org/wiki/Kdb%2B), 5 bytes ``` group ``` Builtins are fab ``` q)group"abracadabra" a| 0 3 5 7 10 b| 1 8 r| 2 9 c| ,4 d| ,6 ``` I usually golf in [k](http://en.wikipedia.org/wiki/K_(programming_language)), but the 2-byte k version (`=:`) doesn't format the output nicely ``` k)=:"abracadabra" "abrcd"!(0 3 5 7 10;1 8;2 9;,4;,6) ``` The results are exactly the same, but the formatting is lost. To format, and to remove the return object, we actually pick up more bytes than the q version ``` k)f:{[[email protected]](/cdn-cgi/l/email-protection) x;} //11 bytes! k)f"abracadabra" a| 0 3 5 7 10 b| 1 8 r| 2 9 c| ,4 d| ,6 ``` [Answer] # Python, 96 bytes ``` def f(s,r=[]): for c in s: if c not in r:print(c,*(i for i,l in enumerate(s) if l==c));r+=[c] ``` [try it online!](https://repl.it/Itpc/0) [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` u"@0hG@=fVh ``` Output indices are 1-based. [Try it online!](https://tio.run/##y00syfn/v1TJwSDD3cE2LSzj/391Y0MTQ1NLIzNTY1MLS3NLYyNjCxMzIzMTY2MLYyNzS1MDY3UA "MATL ‚Äì Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` jmj;+dxCdCMQ{ ``` [Try it online!](http://pyth.herokuapp.com/?code=jmj%3B%2BdxCdCMQ%7B&input=%22missisippi%22&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Q;"ƒ†·π¢$G ``` [Try it online!](https://tio.run/##y0rNyan8/z/QWunIgoc7F6m4////PzezuDizOLOgIBMA "Jelly ‚Äì Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` √ôvSyQ∆∂0Ky¬∏√¨√∞√Ω, ``` [Try it online!](https://tio.run/##AUAAv/8wNWFiMWX//8OZdlN5Uca2MEt5wrjDrMOww70s//8zMTQxNTkyNjUzNTg5NzkzMjM4NDYyNjQzMzgzMjc5NTAz "05AB1E ‚Äì Try It Online") **Explanation** ``` √ôv # for each unique char y in input S # split input into a list of chars yQ # compare each to y for equality ∆∂ # multiply each by its 1-based index 0K # remove zeroes y¬∏√¨ # prepend y to the list of indices √∞√Ω, # join by spaces and print ``` [Answer] # Mathematica, 85 bytes using one-based indexing ``` (t=#;j=First/@t~StringPosition~#&/@(s=First/@Tally@Characters@t);Row[Column/@{s,j}])& ``` [Answer] ## JavaScript (ES Draft), 77 bytes ``` s=>s.replace(/./g,(c,i)=>a[c]=(a[c]||c)+` `+i,a={})&&Object.values(a).join` ` ``` 88 bytes in older browsers: ``` f= s=>s.replace(/./g,(c,i)=>a[c]=(a[c]||c)+` `+i,a={})&&Object.keys(a).map(c=>a[c]).join` ` ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [PHP](https://php.net/), 82 bytes ``` for(;~$c=$argn[$i];)$r[$c].=str_pad(++$i,5," ",0);foreach($r as$k=>$v)echo"$k$v "; ``` [Try it online!](https://tio.run/##HcxBDoIwEEDRPacgk1lAIAY6FGhq9SCEmLGgJSTSFMPSqyO6@qv/vPP7@eqdj5DD82WAyqqUStSSZKsaRYLaqhZ1RdSSaJQsCDTwPbDl4RfQ@2MJif6gNX@iw6nXKYYObX8y6zvcPA9JluGUyxxiyItUH8fI1iUYYl5xNhfc0tG6BXDGLTrI/Qs "PHP ‚Äì Try It Online") [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 95 bytes ``` dim X(126)[_l;||i=asc(_sA,a,1|)‚îòX(i)=X(i)+@ `+!a$][_lA||_SA,b,1|i=asc(C)~X(i)<>D|?C,X(i)‚îòX(i)=@ ``` ## Explanation This copies significant parts of [my answer on this challenge](https://codegolf.stackexchange.com/questions/127261/unique-is-cheap/127310#127310): ``` dim x(126) Create an array of 126 elements (one for each ASCII element) [_l;|| Read cmd line input, loop over its length i=asc(_sA,a,1|) Read the next char's ascii value ‚îò (Syntactic linebreak) X(i)= Set the value for this ascii-codepoint to X(i) everything we've put in before +@ ` and a literal space +!a$ and the current (1-based) index cast as string ] close the FOR loop [_lA|| Loop over the original string again (to preserve order of appearance) _SA,b,1| Read 1 char, assign to C$ (note the capital S in the function call, this auto-creates C$ abd assigns it the value of the substring-call) i=asc(C) Get the index in our storage array from C$'s ascii value ~X(i)<>D IF the storage array holds data for i (<> D$, which we'll set to "" in a second), |?C,X(i) THEN PRINT the character, followed by the indices saved for this char ‚îò (Syntactic linebreak) X(i)=@ Clear out the data stored for C$ @ declares a string lit, ` would close it and that gets auto-added at EOF, creating the literal @`, which gets assigned to D$ ``` ## Sample run: ``` Command line: abracadabra a 1 4 6 8 11 b 2 9 r 3 10 c 5 d 7 ``` [Answer] # [C (clang)](http://clang.llvm.org/), 176 bytes ``` G(S,V,c,g,i,H,L)char*S,*V;{for(V=malloc(8),H=strlen(S),c=g=-1;++g<H;){if(strchr(V,L=S[g]))continue;printf("%c ",V[c++]=L);for(i=-1;++i<H;printf(S[i]==L?"%d ":"",i));puts("");}} ``` *Of course* this is the longest answer here... [Try it online!](https://tio.run/##XY2xboMwFEXn5iuQq0h2MFWDgUAdt2MysCGxIAb6APMkYkeEdIny2Z2pq3aoup5777kQwNgYvTyigfHadt7@Mrdon4bX1V80odH/WTviu2PLgRa85MA1R37kOYOhmTYF35Ty1tuJlurUjKMFmjJ@VE41doYWjIPSKthK39f7o2Q37KnLYHADnqui0jVjYM2M5trJs/ufe0rW4BFeVuD7tcqZ/NbjjwSd5LdVVFgrlb@RdeuRF0I4MibP1/lCCWHyfl9cyzs1aOiHxZZ5t9XDgRKxjbZxFiaxiNNsl4lQpFESJpEQqQh3Wfws3Hh1Xz6NDaCBofsC "C (clang) ‚Äì Try It Online") [Answer] # Python 3, ~~111~~ 106 bytes ``` def q(f): d={a:[]for a in f} for a,b in enumerate(f):d[b]+=[a] [print(p,*d.pop(p))for p in f if p in d] ``` [repl.it](https://repl.it/Iue8/6) [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/csharp), 138 bytes ``` using System.Linq;s=>Console.Write(string.Join("\n",s.Distinct().Select(c=>c+string.Join("",s.Select((d,i)=>d==c?i:-1).Where(i=>i>-1))))); ``` [Answer] # [F#](http://fsharp.org/), 120 bytes ``` let f s=s|>Seq.indexed|>Seq.groupBy(fun(a,b)->b)|>Seq.iter(fun(a,b)-> printf"\n%c"a Seq.iter(fun(c,_)->printf"%i"c)b) ``` A more readable version: ``` let f s = s |> Seq.indexed |> Seq.groupBy (fun (idx, char) -> char) |> Seq.iter (fun (char, charIdxSeq) -> printf "\n%c" char Seq.iter (fun (idx, _) -> printf "%i" idx) charIdxSeq) ``` `Seq.indexed` creates a new sequence containing tuples which are composed of the original element and it's 0 based index in the original sequence. The rest is fairly self explanatory which is never a good thing for golf! [Answer] # [R](https://www.r-project.org/), ~~80~~ 77 bytes ``` function(s)for(i in (z=unique(s<-strsplit(s,'')[[1]])))cat(i,which(s==i)," ") ``` [Try it online!](https://tio.run/##FcixCoAgEADQva8Ql@7Ahvb8EnEwSzwILU8J@nmr6cErPegeWvKVcgLGkAuQoCTg0S3R1XbgZeJa@DyoAqtxRGNmaxHRuwqk7kg@AmtNqOQgsQeQbi3Ou@3nixc "R ‚Äì Try It Online") an anonymous function; prints the result 1-indexed with a trailing newline. [Answer] # [J](http://jsoftware.com/), 11 bytes ``` ~.,.":@I.@= ``` [Try it online!](https://tio.run/##y/r/P81WT6FOT0dPycrBU8/B9n9qcka@QpqCemJSUWJyYgqIUv8PAA "J ‚Äì Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ¬ßm»Ø¬ß:;ms¬•u ``` [Try it online!](https://tio.run/##yygtzv7//9Dy3BPrDy23ss4tPrS09P///0rGhiaGppZGZqbGphaW5pbGRsYWJmZGZibGxhbGRuaWpgbGSgA "Husk ‚Äì Try It Online") Note: Husk (or at least the command `¬•`) is newer than this challenge. ## Explanation ``` ¬ßm»Ø¬ß:;ms¬•u Implicit input, say S = "ababbc". u Remove duplicates: "abc" ¬ßm Map over this string: Argument is a character, say 'b'. ¬• 1-based indices in S: [2,4,5] ms Convert each to string: ["2","4","5"] ; Wrap argument in a string: "b" »Ø¬ß: Prepend to list of index strings: ["b","2","4","5"] Result is a list of lists of strings [["a","1","3"],["b","2","4","5"],["c","6"]] Implicitly print, separating strings by spaces and lists by newlines. ``` ]
[Question] [ This is a pretty run of the mill question. I will define a sequence and you golf some code to output a entry given a index. * The first item in the sequence is 2. * The nth item in the sequence is the smallest positive integer other than n and 1 sharing at least one factor with n (other than 1) that has not already appeared in the list. # Test cases Here are the first 25 items in the sequence: ``` 1 2 2 4 3 6 4 8 5 10 6 3 7 14 8 12 9 15 10 5 11 22 12 9 13 26 14 7 15 18 16 20 17 34 18 16 19 38 20 24 21 27 22 11 23 46 24 21 25 30 ``` [Related (offset by one) OEIS](http://oeis.org/A077127) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` R»2ɓ²Rg⁸>1Tḟ⁸ḟḢṭµ/Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8/z/o0G6jk5MPbQpKf9S4w84w5OGO@UAGkHy4Y9HDnWsPbdV/uHPVfyPToENbj@453P6oaY37fwA "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 118 117 bytes -1 byte thanks to [Cameron Aavik](https://codegolf.stackexchange.com/users/48436/cameron-aavik)! ``` import math def f(n,i=3): if n<2:return 2 while 1: if math.gcd(n,i)>1>(i in map(f,range(n)))<i!=n:return i i+=1 ``` [Try it online!](https://tio.run/##NYzBCoMwEETvfsU2pyyKEL2J@iVepCa6pW5CuqX069OkpadhZngvvOXw3KdEZ/BR4FzlqDbrwGluaOpxqIAc8NgN0cozMnQVvA66WzD5Kl9B2v26FQBnM2sC4rwG7Zq48m41I@JIl4n/DipkPZkUIrFotbBqb55YPyRqQqhBLaJylO7yguB8hK/4pzQNGJO16QM "Python 3 – Try It Online") The code is pretty inefficient (it brute-forces a value that doesn't exist in the previous results, and calculates the previous results again on every new value), so it works properly but I wouldn't recommend running it on large numbers. [Answer] # [Haskell](https://www.haskell.org/), ~~60~~ 59 bytes EDIT: * -1 byte: @xnor pointed out `all(/=x)` was shorter than `x`notElem``. `f` takes an integer and returns an integer. ``` f n=[x|x<-[2..],gcd x n>1||n<2,all(/=x)$n:map f[1..n-1]]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZ5ubWOAbr1FQlJlXopemGW2op2dkGPs/TSHPNrqipsJGN9pITy9WJz05RaFCIc/OsKYmz8ZIJzEnR0PftkJTJc8KqF8hDaQtT9cwNlZR0eD/fwA "Haskell – Try It Online") This is very exponential time, so TIO times out after 21, while my interpreted GHCi got up to 22 before I stopped it just now. The following 9 bytes longer version memorizing into a list easily goes up into the thousands: ``` f n=[x|x<-[2..],gcd x n>1||n<2,all(/=x)$n:take(n-1)l]!!0 l=f<$>[1..] ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZ5ubWOAbr1FQlJlXopemGW2op2doYGAQ@z9NIc82uqKmwkY32khPL1YnPTlFoUIhz86wpibPxkgnMSdHQ9@2QlMlz6okMTtVI0/XUDMnVlHRgCvHNs1GxQ5kUOz//wA "Haskell – Try It Online") * `f n` uses a list comprehension to generate candidates `x`, taking the first passing one with `!!0`. * `gcd x n>1` checks that `x` and `n` have common factors. * `||n<2` exempts `n==1` from the factor requirement. * `all(/=x)$n:map f[1..n-1]` checks that `x` is neither `n` nor a preceding sequence element. [Answer] No built-in for GCD in C#, so... # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 197 196 194 bytes ``` n=>{if(n<2)return 2;var p=new int[n-1];int i=0,a,b;for(;i<n-1;)p[i]=f(++i);for(i=2;;i++)if(n!=i){for(a=n,b=i;a*b>0;)if(a>b)a%=b;else b%=a;if(b!=1&a!=1&!System.Array.Exists(p,e=>e==i))return i;}} ``` [Try it online!](https://tio.run/##VVDBasMwDL3vK9RCh72kpc3VUWCM9bSNQRk7lB7s1NkEqVNsp2sp@fbMDtu66iDLT9LjPZVuWjZW9xCirKVz8GqbDyt3NxE5DzmG89JTCYeGtvAsyTD@17oMxVidnNe72bI1ZU7GpxBSARUgmLauxdVsRHuDxZkqZvKMW@1bayATB2lhj0Z/xe21mS42IhRAOE9lqkTVWCYoD7jg@zVtsGJJQnzACTMhKEl45Bwh8XNEJZpUIQl5p4q5iD1ZKC4nqISunQY1QSkCqka4uJUxjX6M3FsrT7PHIznv2D7VWGgMrL9aSXRdL26ubTUW2KA3@FuI8OQI2TwUQdbV5L@DPTTGNbWevVvy@omMZuMXffRvpnV6u/qUVm@XsvTByxiSQJnAmAf6@KlY0HO5bDdUXf8N "C# (.NET Core) – Try It Online") Once again, refrain from using this code to calculate numbers in the sequence for `n>30`... * -1 byte by changing the GCD `while` loop for a `for` loop. * -2 bytes thanks to Kevin Cruijssen! Nice one! [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 46 bytes ``` {⍺←2⋄1=⍵:2⋄(~∨/⍺∊∇¨⍳⍵-1)∧(1<⍺∨⍵)∧⍺≠⍵:⍺⋄⍵∇⍨1+⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR727gJTRo@4WQ9tHvVutQCyNukcdK/RBMh1djzraD6141LsZKKdrqPmoY7mGoQ1YBii4FcQHcToXgLSCWN0tQBZQz6PeFYbaQIFaoDVg/RYA "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ ## Goal Given an string with a train of hashes, calculate its total length and divide by the distance from start to finish. ## Simulation **What are we simulating?** According to [this paper](http://science.sciencemag.org/content/271/5256/1710.abstract), the ratio of the length of a river to the distance between start and end is approximately Pi! (This may have been disproved empirically, but I could find the data and for this challenge we'll assume it is true). **How are we simulating this?** * Take a string input of whitespace and hashes * Each hash will have two others adjacent to it + With the exception of the first and last hash which will have only 1 * Each character lies on a lattice point `(x, y)` * `x` is the character's index in its line + eg `c` is the 4th character in `0123c567` * `y` is the character's line number + eg `c` is on the 3rd line: ``` 0line 1line 2line 3c... ``` * Sum the distances between adjacent hashes, call it `S` * Take the distance between the first and last hashes, call it `D` * Return `S/D` [![enter image description here](https://i.stack.imgur.com/oPtqT.jpg)](https://i.stack.imgur.com/oPtqT.jpg) ## Specification * **Input** + Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary) * **Output** + Flexible, give output in any of the standard ways (eg return, print) + White space, trailing and leading white space is acceptable + Accuracy, please provide at least 4 decimal places of accuracy (ie `3.1416`) * **Scoring** + Shortest code wins! ## Test Cases These are my approximations of the rivers. My approximations might be poor or these my be poor sample of the river population. Also, I did this calculations by hand; I could have miss calculated. [Yellow River](https://en.wikipedia.org/wiki/Yellow_River#/media/File:Yellowrivermap.jpg) ``` ### #### # # # # # # # # # # # # # # # ## # # ##### ## # # ## ``` ``` 1.6519 ``` [Nile River](https://en.wikipedia.org/wiki/Nile#/media/File:River_Nile_map.svg) ``` # # # # # # # # # # # # # # # # ## # # # # # # # # # # # ## # # # # # # # # # # # ``` ``` 1.5498 ``` [Mississippi River](https://en.wikipedia.org/wiki/Mississippi_River#/media/File:Mississippiriver-new-01.png) ``` ### # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # ## # # ## ## ## # # # # # # # # # # # # # # # # # #### # # ``` ``` 1.5257 ``` ### TL;DR These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't [waste ammo](https://medium.com/the-physics-arxiv-blog/how-mathematicians-used-a-pump-action-shotgun-to-estimate-pi-c1eb776193ef#.eld2u7w76)! There are [nine challenges](http://meta.codegolf.stackexchange.com/a/10035/43214) total. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~48~~ ~~44~~ ~~42~~ ~~37~~ 33 bytes *Quite a few bytes saved thanks to [rahnema1's idea (Octave answer)](https://codegolf.stackexchange.com/a/104702/36398) of collapsing two convolutions into one* ``` t5BQ4B&vX^Z+*ssGt3Y6Z+1=*&fdwdYy/ ``` This takes the input as a binary matrix, with `;` as row separator. `1` corresponds to hash and `0` to space. [Try it online!](https://tio.run/nexus/matl#@19i6hRo4qRWFhEXpa1VXOxeYhxpFqVtaKullpZSnhJZqf//f7SBAio0BEMYbahggA1ao@tBpQ2w68OhC68eBUMydBmSYZchhgtxmIzJszbEEgLo6gzRQ9QaFtr49eEKQ5xxgw3GAgA) Or [verify all test cases](https://tio.run/nexus/matl#zVa7DsIwDNz5ik4MdCAnHovFgtg6ITHwUBED4gdAIL6@SJWKaBrbaZpIKENVXRzH57Ody76oHov1dr4eP/fnYz6534vH7LA85lhNxrfr63p4T6vNrjqZrL1Qr@aLzLgW2Tbtr3HbMVaiTYYAKwT4QueGzMndP4KDAXsfbEapYVu24zhkc@Na5egknk59UWPFweIBKAJvBUFrps0zuTPkUkHHmjiWIUSEQJ6HxutVeclRRuP0WxuGRfkOJKNG7V5al8IAlIvXp7JNXL919UPqGCT3L8V7Dxwh@dKyHQnX9RSDHz1/snJ8qnA4rnUXnwmhzQgI8UPwP5Q/JNNvetxPX@n1Y3lh8y@/Ar57SH6/QMShnK/O7Oj67Tmd/w5PVz/x@l/3Ld0/v98d5Qc). [Here's](https://tio.run/nexus/matl#tZVBDoMgEEX3nmKSn5R9t249QnetSe9/CRsQlRm@CJiaGM0bGD9/Bly@w/PzmKbhtSxvJ/EC4G/IcblRtjDiLTgNmyiKYRRnI02eTtofPgyYLwb9OKT5dxW3ytVqk4XNw@FLnObGEhFkJMosElxmhhACS7A6pvLAfj0jwOW66vRoArlP0sIFgrRWkahOpUSQEd3ALmuMM2L0sDFVmZM8ocv0jvPDwHWX0xMNxALiUwtiDtdKZVbkntLWqESkN@lWJXvVjtqL0qgeXRXqR9zofle3ucav/CQL0KJw5huUj6LnUnOFCifRn1BftRv6fv91XZizWjj/AA) a format converter that takes inputs as 2D char arrays (again, with `;` as separator) and produces string representations of the corresponding binary matrices. ### Explanation This was fun! The code uses ~~three~~ two 2D-convolutions, each for a different purpose: 1. To detect vertical and horizontal neighbours, which contribute a distance of `1`, the required mask would be ``` 0 1 0 1 0 1 0 1 0 ``` But we only want each *pair* of neighbours to be detected once. So we take half the mask (and the last row of zeros can be removed): ``` 0 1 0 1 0 0 ``` Similarly, to detect diagonal neighbours, which contribute a distance of `sqrt(2)`, the mask would be ``` 1 0 1 0 0 0 1 0 1 ``` but by the same reasoning as above it becomes ``` 1 0 1 0 0 0 ``` If this mask is multiplied by `sqrt(2)` and added to the first, the two convolutions can be replaced by one convolution with the combined mask ``` sqrt(2) 1 sqrt(2) 1 0 0 ``` 2. Start and end points are, by definition, the points with only one neighbour. To detect them we convolve with ``` 1 1 1 1 0 1 1 1 1 ``` and see which points give `1` as result. To produce the combined mask of item 1 it's shorter to generate its square and then take the square root. The mask in item 2 is a predefined literal. ``` t % Take input matrix implicitly. Duplicate 5B % 5 in binary: [1 0 1] Q % Add 1; [2 1 2] 4B % 4 in binary: [1 0 0] &v % Concatenate vertically X^ % Square root of each entry Z+ % 2D convolution, maintaining size * % Multiply, to only keep results corresponding to 1 in the input ss % Sum of all matrix entries. This gives total distance Gt % Push input again. Duplicate 3Y6 % Predefined literal. This gives third mask Z+ % 2D convolution, maintaining size 1= % Values different than 1 are set to 0 * % Multiply, to only keep results corresponding to 1 in the input &f % Push array of row indices and array of column indices of nonzeros d % Difference. This is the horizontal difference between start and end wd % Swap, difference. This is the vertical difference between start and end Yy % Hypothenuse. This gives total distance in straight line / % Divide. Display implicitly ``` [Answer] # Octave, 99 bytes ``` @(a)sum((c=conv2(a,[s=[q=2^.5 1 q];1 0 1;s],'same').*a)(:))/2/{[x y]=find(c<2&c>0),pdist([x y])}{2} ``` nearly same method as [MATL answer](https://codegolf.stackexchange.com/posts/104685/edit) but here kernel of convolutions is ``` 1.41 , 1 , 1.41 1 , 0 , 1 1.41 , 1 , 1.41 ``` that `sqrt(2) =1.41` is for diagonal neighbors and `1` is for direct neighbors so when we sum values of the result over the river we get twice the real distance. **ungolfed version**: ``` a=logical([... 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 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 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0 0 0 1 1 0 0 1 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 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]); sq = sqrt(2); kernel = [... sq , 1 , sq 1 , 0 , 1 sq , 1 , sq]; %2D convolution c=conv2(a,kernel,'same').*a; #river length river_length = sum(c (:))/2; #find start and end points [x y]=find(c<2&c>0); # distance between start and end points dis = pdist([x y]); result = river_length/ dis ``` Try (paste) it on [Octave Online](https://octave-online.net) [Answer] # JavaScript (ES6), 178 Input as a string with newlines *in rectangular form* : each line padded with spaces to the same length (as in the examples) ``` r=>r.replace(/#/g,(c,i)=>([d=r.search` `,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d)) ``` *Less golfed* ``` r=>( r.replace(/#/g, // exec the following for each '#' in the string (c,i) => // c: current char (=#), i: current position ( // check in 8 directions // note: d starts as the offset to next row, prev x position // and is incremented up to offset to next row, succ x position // note 2: there are 2 diagonal offsets, then 2 orthogonal offsets // then other 2 diagonal, then 2 more orthogonal [d=r.search`\n`,-d, ++d,-d, ++d,-d, 1,-1].map( // for each offset (d,j) => // d: current offset, j: array position (0 to 7) r[i+d] == c && // if find a '#' at current offset ... ( --n, // decrement n to check for 2 neighbors or just 1 s += j & 2 ? 1 : Math.SQRT2 // add the right distance to s ), n = 1), // n starts at 1, will be -1 if 2 neighbors found, else 0 // if n==0 we have found a start or end position, record it in v and w n || (v=w, w=i) ), w=s=0), // init s and w, no need to init v // at the end // d is the length of a line + 1 // s is twice the total length of the river // v and w can be used to find the x,y position of start and end s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d)) ) ``` **Test** ``` F= r=>r.replace(/#/g,(c,i)=>([d=r.search`\n`,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d)) Yellow=` ### #### # # # # # # # # # # # # # # # ## # # ##### ## # # ## ` Nile=` # # # # # # # # # # # # # # # # ## # # # # # # # # # # # ## # # # # # # # # # # # ` Missi=` ### # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # ## # # ## ## ## # # # # # # # # # # # # # # # # # #### # # ` console.log('Yellow River',F(Yellow)) console.log('Nile River',F(Nile)) console.log('Mississippi River',F(Missi)) ``` ]
[Question] [ You must write a program or function. The input is a 'map' of numbers. You can choose to take the map as either a string with new line characters (`\n`) or a 2D array of strings. All maps are 5 characters by 5 characters, and the characters are always either digits greater than 0 or spaces. Here is an example of a map: ``` 12 45 11233 233 1 2 899 ``` Your task is to find the connected components in the map. A valid component is a series of at least three horizontally and/or vertically (*not diagonally*) connected identical digits (*not spaces*). You will then need to replace the characters of the valid connected components with `x`s and print or return that result. So, the output for the above example would be: ``` x2 45 xx2xx 2xx 1 2 899 ``` Here's another test case (thanks to Martin Ender): ``` Input: 2 3 4 1 5 111 6 11 7 Output: 2 3 4 x 5 xxx 6 xx 7 ``` This is code golf so shortest code in bytes wins! [Answer] # Python 3, ~~238~~ ~~237~~ ~~200~~ ~~199~~ ~~192~~ 181 bytes ``` def f(a,i=0):F=lambda i,n,c:29>i>=0!=" "!=a[i]==c!=n and(a.__setitem__(i,n)or-~sum(F(i+j,n,c)for j in[-1,1,-6,6]));j=i+i//5;F(j,[a[j],"x"][2<F(j,1,a[j])],1);i>23or f(a,i+1);return a ``` Defines a function `f(a)` that takes the input as an array of characters and returns the same array modified. ([Arrays of characters are acceptable as strings by default.](http://meta.codegolf.stackexchange.com/questions/2214/whats-a-string)) ### Ungolfed with explanation The modified code is recursive, but works the same. ``` # The main function; fills all continuous nonempty areas of size >= 3 in array # with x's. Both modifies and returns array. def findpaths(array): # Fills a continuous area of curr_char in array with new_char, starting # from index. Returns the number of cells affected. def floodfill(index, new_char, curr_char): if (0 <= index < 29 # Check that the position is in bounds and (index + 1) % 6 != 0 # Don't fill newlines and array[index] != " " # Don't fill empty cells and array[index] == curr_char # Don't fill over other characters and curr_char != new_char): # Don't fill already filled-in cells array[index] = new_char # Fill current position return (1 # Add neighboring cells' results, plus 1 for this cell + floodfill(index + 1, new_char, curr_char) # Next char + floodfill(index - 1, new_char, curr_char) # Previous char + floodfill(index + 6, new_char, curr_char) # Next line + floodfill(index - 6, new_char, curr_char)) # Previous line return 0 # Nothing was filled. The golfed solution returns False here, # but that's coerced to 0 when adding. for i in range(25): # Loop through the 25 cells i += i // 5 # Accommodate for newlines in input curr_char = array[i] # Get the cell's contents # Fill the area from the cell with dummies area_size = floodfill(i, 1, curr_char) # Convert dummies to "x" if area was large enough, back to original otherwise fill_char = "x" if 2 < area_size else curr_char floodfill(i, fill_char, 1) return array ``` [Answer] # Ruby, 304 bytes ``` def b(s,i) @v=[] b2(s,i,s[i]) end def b2(s,i,c) if(0...s.size)===i&&s[i]==c&&!@v[i] @v[i]=s[i]='x' [1,-1,6,-6].each{|j|b2(s,i+j,c)} end s end def f(s) z = s.dup ps = ->(i){b(z.dup,i).scan('x').size} (0...s.size).each{|i|b(s, i)if ![' ',"\n"].include?(s[i])&&ps.call(i)>2} s end ``` example usage: ``` puts f(File.read("map.txt")) ``` the code reuses the 'blot' method to calculate the path length. variables/methods: * f(s): function to convert map string, returns new map with 'x's * ps(i): path size from map index i (where x = i % 6, y = i / 6) * s: input string, map lines separated by "\n" * z: copy of input string * b(s,i): 'blot' function: writes 'x' from map index i over paths * @v: 'visited' array ## Attempt at more detailed explanation: make a copy of the input string, which we use for finding the length of the path from any given point in the map. ``` z = s.dup ``` define a 'ps' (path length) anonymous function (lambda) which takes the map index i as an argument. it returns the length of the path from that point. it does this by calling the 'b' (blot) method to insert x's on a copy of the original map and then counting the number of x's in the returned string. ``` ps = ->(i){b(z.dup,i).scan('x').size} ``` the following part iterates over each character in the map (index i, character s[i]). it calls the 'b' (blot) function on map position i if the path length from position i is greater than 2, and if it's not a space or newline character. ``` (0...s.size).each { |i| b(s, i) if ![' ',"\n"].include?(s[i]) && ps.call(i) > 2 } ``` the b (blot) function takes the map string and an index as argument. it initialises @v (visited array) and calls the b2 helper function. ``` def b(s,i) @v=[] b2(s,i,s[i]) end ``` the b2 function takes the map string, a map position (i), and a character in the current path (c). it calls itself recursively to replace connected sections of digits with the 'x' character. it returns the input string (this is so the ps function can call scan() on the return value). this if statement is checking that the map position (i) given is within the bounds of the string (0...s.size) and that the character at s[i] is the same as the starting character. also @v[i] is checked to avoid infinite recursion. ``` if(0...s.size) === i && s[i] == c && !@v[i] ``` this is the bit that replaces the character at index (i) with the 'x' character. it also marks that index as visited. ``` @v[i] = s[i] = 'x' ``` this is where b2 calls itself recursively searching for the path. i+1 is one character to the right, i-1 is one character to the left, i+6 is one row down (5 digits + 1 newline = 6 characters), i-6 is one row up. ``` [1,-1,6,-6].each { |j| b2(s, i+j, c) } ``` [Answer] # JavaScript (ES6), ~~171~~ ~~161~~ ~~139~~ ~~137~~ ~~136~~ ~~133~~ 132 bytes ``` f=(a,i=0)=>(F=i=>" "<c&&a[i]===c&&(a[i]=n,1+F(i-1)+F(i+1)+F(i-6)+F(i+6)),n=1,c=a[i],n=F(i)>2?"x":c,c=1,F(i),i>28?a:f(a,++i+(i%6>4))) ``` ``` <!-- this HTML included just for testing --><textarea rows=5 cols=6 oninput="document.querySelector`pre`.innerHTML=this.value.length==29?f([...this.value]).join``:'invalid input'">12 45&#10;11233&#10; 233&#10; 1&#10;2 899</textarea><br/><pre></pre> ``` This is a translation of my Python answer. I/O as character arrays. Too bad there's no efficient way of doing `sum`... [Answer] # C(Ansi), ~~243~~ ~~233~~ ~~179~~ 188 Bytes ## Golfed: ``` #define O o[1][l] x,n,l,L;r(o,l)char**o;{if(!(l>L|l<0|O<47|O!=x))n++,O++,r(o,l-1),r(o,l+6),r(o,l-6),r(o,l+1),n>2?O='x':O--;}main(g,o)char**o;{for(;(L=30)>l;l++)n=0,x=O,r(o,l);puts(o[1]);} ``` ## With Annotations: ``` #define O o[1][l] x,n,l,L; /*-------------------------- Globals*/ r(o,l)char**o;{ /*------------------------ Recursive Function*/ if(!(l>L|l<0|O<47|O!=x)) /*----------- if this cell is valid(in range, is a number, is the same as the parent number*/ n++, /*--------------------------- Increment count*/ O++, /*--------------------------- Increment character to mark*/ r(o,l-1), /*------------------------- Recurse left*/ r(o,l+6), /*------------------------- Recurse down*/ r(o,l-6), /*------------------------- Recurse down*/ r(o,l+1), /*------------------------- Recurse right*/ n>2?O='x':O--; /*---------------------If greater than 3, replace with x, else decrement character*/ } /*----------------------------- Return*/ main(g,o)char**o;{ /*--------------------- Main*/ for(;l<(L=30);l++){ /*---------------- For entire string and set L*/ n=0; x=O; /*-------------------- set counter to 0*/ r(o,l); /*------------------------ Recurse*/ } /*---------------------------------- End While*/ puts(o[1]); /*------------------------ Print*/ ``` } ## Input: Expects a newline at the beginning and end of the string. ### Example Input: ``` ./findPaths " 12 45 11233 233 1 2 899 " ``` ### Example Output: ``` x2 45 xx2xx 2xx 1 2 899 ``` ## Update Making the grid fixed allowed me to shave off nearly 60 bytes. [Answer] ## Mathematica, 180 bytes ``` (f=Flatten@#;p=Partition)[If[Tr[1^VertexComponent[r~Graph~Cases[##&@@p[#,2,1]&/@Join[g=p[r,5],g],{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b],#]]<3,f[[#]],"x"]&/@(r=Range@25),5]& ``` Explanation: ``` (f=Flatten@#;p=Partition)[ If[ Tr[1^VertexComponent[ r~Graph~Cases[ ##&@@p[#,2,1]&/@Join[g=p[r,5],g], {a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b ], # ]]<3, f[[#]], "x" ]&/@(r=Range@25), 5 ]& ``` Pure function which accepts a `5x5` array. `` is the 3-byte private-use character `U+F3C7` representing the postfix transpose operator [`\[Transpose]`](http://reference.wolfram.com/language/ref/character/Transpose.html). `(f=Flatten@#;p=Partition)`: Flattens the input list and stores it in `f`. Sets `p = Partition` and returns it. `g=p[r,5]`: The array `{{1,2,3,4,5}, ..., {21,22,23,24,25}}` (this is because `r` gets set to `Range@25`). `Join[g=p[r,5],g]`: the list of rows and columns of `g`. `p[#,2,1]&`: Pure function which partitions the list `#` into sublists of length `2` with overlap `1`; i.e., the list of adjacent pairs in `#`. `##&@@p[#,2,1]&`: Same as above except it returns a `Sequence`. `##&@@p[#,2,1]&/@Join[g=p[r,5],g]`: Maps the previous function of the rows and columns of `g` to obtain a list of all of the adjacent entries in `g`. My gut says there is a shorter way to do this. `r~Graph~Cases[...]`: Graph whose vertices are the integers `1, ..., 25` and whose edges are the edges between adjacent entries in `g` which have the same corresponding entries in the input array (other than `" "`) `{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" "`: Pattern which matches `{a,b}` such that `f[[a]] == f[[b]]` (same value in the input array) and which are not equal to `" "`. Set `A = f[[a]]` to save `1` byte. `...:>a<->b`: Replace every match with an undirected edge from a to b. `VertexComponent`: Returns the connected component of the second argument (a vertex) in the first argument (a graph). `Tr[1^VertexComponent[...]]`: The size of the connected component. Saves `1` byte from `Length@VertexComponent[...]`. `If[Tr[...]<3,f[[#]],"x"]&`: Pure function which takes an entry `#` in `g`. If the size of its connected component is less than `3`, replace it with the corresponding entry in the input. Otherwise, replace it with `"x"`. `(f=Flatten@#;p=Partition)[...,5]`: And finally reshape the result to be a `5x5` array. [Answer] ## Clojure, 188 bytes This is quite overwhelming :D ``` #(apply str(map-indexed(fn[i v](if((set(flatten(for[m(range 30)](let[n(for[p[-1 -6 1 6]:when(=(get %(+ m p)0)((set"123456789")(% m)))](+ m p))](if(< 1(count n))(conj n m)[])))))i)\x v))%)) ``` Called like this (it takes a 1D vector of characters): ``` (def f #(apply str(...)) (print (str "\n" (f (vec (str "12 45\n" "11233\n" " 233\n" " 1\n" "2 899\n"))))) (print (str "\n" (f (vec (str "2 3\n" " 4\n" " 1 5\n" "111 6\n" "11 7\n"))))) ``` Too lazy to ungolf it but basically `for[m(range 30)]` visits each index and for each index the inner `let[n(for[p[-1 -6 1 6]...(+ m p))]` makes a list of 0 to 4 elements which lists locations which had the same value (1 - 9) as the middle location. If more than 1 neighbour matches the mid piece it means that all these form a cluster, so those locations are added to the set used at `(if((set(flatten(...)))i)`. If index `i` is found from the set then `\x` is emitted and the original value otherwise. That `:when( ... )` is quite interesting... [Answer] # [Julia](https://julialang.org) ## 256 bytes too long... readable version: ``` ~A=( B=hcat(collect.(split(A,"\n"))...);C=copy(B); s\T=( L=[s]; C[s...]='_'; [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T)); L ); keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x'; join(eachcol(B).|>join,"\n") ) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZLPSsNAEMb1uk8x5JDuYhK6adoqYYNtTkKpl3hKg4Q0baOhLW4qGxBfxEsvPpS-hW_g7KZQ3cM3sPP75s-yH59Ph7rKj18_y7zJRUosyyLch2BIOPcHAwLQKQAnPlzf3CAgIoMpgynlK6Uxo38xA_l41fkDAhxA1-UwQgUYn2v9w5TGlFKIoRjsNBfOMgjIaDQcBgGCY3OMbQxwroYg2pUBdQRljgGVAYFkn4dm5V5_X168TwSdik2RN7TY1XVZNB6V-7pq6MSxFluLMc_zWBiLYrdv6ZSFcpEIOhOpzMI4lZjMRO-xF6bU5U6fObTTvuNyEzjLvLeodaN12dDYab0r6SDPhEhsG-u86s4zh-oEWySMhTMWPpetpDFDo3KjSi6rNc4Tpypjtl2X23WzoWhNDvu6pIotdAZtLPJte9Z1m6ZtN5rqhU-7akvLvNjggrgBAvrmtF33EF90tXsBejd37h8SJvR3wPe6zaUsXxp4v5sLgQlSbpcdfzx28Rc) * classical floodfill * converts the input to char matrix (`B`), copy it (`C`, it is used for admin the visitedness), then performs floodfill from each (current) digits of `C`. `\` returns the vector of connected component `L` and if it fulfills the reqs then modify `B`. At the end it builds a string from `B`. * works for arbitrary, "rectangular" strings ## 194 bytes input as char matrix (split+join are outsourced): ``` ~B=( C=copy(B); s\T=( L=[s]; C[s...]='_'; [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T)); L ); keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x'; B ) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZHBauMwEIbveorBB0eitqkcJ2kxMotzWgjtxXtyTDGOm7jrTULlLGMofZFecumL9C36GPsGHUmFdoX4B6Tv_2eEXl4fTn1Xn9__beqhViXzPI_JGJIZkzKeThmAUwDJYri6viZAZRZDiyHGiAaz-h2zUExHzp8wkAAmV8KcFGDxlfUfhgZDRMJILPY5F80yTdh8PpslCYELu6xtAfCVRiDZ0YKmAtplQbQgsOr1NNyHV-9vz7niS9UcjiPPRarXheIrVeoqXZY6iqJKTe4maclDGVyKgDu9DEJpixRV9JSNYbZtB74MxuhCB8QLpQrfp5y_TT3wVcDNhVgXQqQrkf5uR82XgowYZp3edNuOzCVWwvf7dr8ddpysxenYtxzF2tyQTWSx769ct7wc3Wg4SXPx-RK8PzwC_3kT3P4qhDL_SQ_O1c6M0Bz6vm2GiOtjT80I8tZ7TwhKEUT9IYt6OHR73tbNjmD-nJv5zJEjCaL9o9a6fRwcr0hYu98w1_98dvUD) ]
[Question] [ What general tips are these for golfing in Lisp (any dialect)? Please post one tip per answer, and only answers that are specific to a dialect of Lisp (e.g. "remove comments" is not an answer). Please post the dialect of Lisp your tip applies to with your tip. [Answer] # Order function parameters to minimize whitespace Instead of ``` (defun f(a b)(...)) ... (f x(1+ y)) ``` try something like ``` (defun f(b a)(...)) ... (f(1+ y)x) ``` [Answer] # Conditional Output *GNU Common Lisp* ### `~v^` The *up-and-out* directive `~^` is most commonly used in a list formatting operation to terminate after the last list item. However, it can also be used with a `v` modifier to consume an argument, in which case it terminates if that argument is zero. This is particularly useful for dealing with the zero produced by `dotimes`. ``` (loop as n from 1 to 10 do(format t"~d~%"n)) (dotimes(n 11)(if(> n 0)(format t"~d~%"n))) (dotimes(n 11)(format t"~v^~d~%"n n)) ``` --- ### `format(condition)` The first argument to `format` can be one of `t`, `nil` a.k.a. `()`, or a stream. If passed `t`, it will output to `stdout`, if `nil` it will return the formatted output as a string. This can be used conditionally output. The above example could be written equally as short as: ``` (dotimes(n 11)(format(> n 0)"~d~%"n)) ``` If a value was output, the return value will be `nil`. Because of this, it can also be used as the terminating condition for a `do` loop: ``` (do((n 11))((<(decf n)1))(format t"~d~%"n)) (do((n 11))((format(>(decf n)0)"~d~%"n))) ``` --- ### `~[...~]` The conditional formatter consumes an argument, and selects a formatting string from a list by index. A common use case is with the default formatter `~:;` to select between zero and not zero. ``` (dotimes(n 11)(format t"~v^~[~r~:;~d~]~%"n(mod n 3)n)) ``` Conditional formatters can also be nested, in which case each will consume an argument in turn. --- ### `~&` In each of the examples above, `~%` is used to emit a newline. In most cases, this could be replaced by a literal newline. Another option is to use `~&`, which will emit a newline if and only if the output cursor is not at the start of a line, a.k.a. a `fresh-line`. Both `~%` and `~&` can also take an argument, with a `v` modifier or as a constant, and will produce as many newlines. They will also both happily accept a negative argument, in which case they emit nothing. --- ### External References *Practical Common Lisp* [18. A Few FORMAT Recipes](http://www.gigamonkeys.com/book/a-few-format-recipes.html) *Common Lisp the Language, 2nd Edition* [22.3.3. Formatted Output to Character Streams](https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html) [Answer] Use `loop` and `format`, which is like `printf` on steroids. `format` includes iteration and conditions, as well as roman numerals, English numbers and English plurals. It is very, very ugly, and very compact. [Answer] # Print strings consisting of capital letters via printing atoms The `princ` function in Common Lisp is short, and will print objects without escape characers. If you print Common Lisp symbols, which have the synax `'symbol-name`, this saves you from needing quotes around what you want to print, and can also save on whitespace. Note that when printing symbols, they will be capitalized. Also, it does not add a newline or a space, so you don't need concatenation. For example, ``` (princ'hai) ``` will print `HAI`. And ``` (princ'hai)(princ(read)) ``` will print `HAI`, ask for input, and print it back out, e.g. if you type hello, the result is ``` HAIhellohello ``` [Answer] # Use `1+` and `1-` for increment and decrement Instead of `(+ a 1)` or `(- b 1)` try `(1+ a)` or `(1- b)`. ]
[Question] [ This is a pretty simple challenge, but (I hope) a fun one. # Task If right now either the month is `4` and the day is `20`, the hour (on a 12 hour clock) is `4` and the minute is `20`, or the minute is `4` and the second is `20`, print this ascii art: ``` . .:. :|: .:|:. ::|:: :. ::|:: .: :|:. .::|::. .:|: ::|:. :::|::: .:|:; `::|:. :::|::: .:|::' ::|::. :::|::: .::|:; `::|::. :::|::: .::|::' :::|::. :::|::: .::|::; `:::|::. :::|::: .::|::;' `::. `:::|::. :::|::: .::|::;' .:;' `:::.. `;::|::. :::|::: .::|::: ::::; `:::::. ':|::. :::|::: .::|:' ,::::;' `:::::. ':|:::::|:::::|:' :::::;' `:::::.:::::|::::|::::|::::.,:::;' ':::::::::|:::|:::|:::::::;:' ':::::::|::|::|:::::::'' `::::::::::;' .:;'' ::: ``::. :':': ; ``` You can have trailing spaces. Otherwise, print the number of minutes and seconds left until the next such occasion in the format: `%d minutes and %d seconds left until your next hit.` with the time being minimized. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! *P.S. If this challenge is too inappropriate for this site, tell me and I'll change it.* [Answer] # Python 2, 371 bytes This source contains non-printable bytes, so it is presented as a hexdump that can be decoded with `xxd -r`. ``` 00000000: efbb bf66 726f 6d20 7469 6d65 2069 6d70 ...from time imp 00000010: 6f72 742a 0a74 3d74 696d 6528 290a 693d ort*.t=time().i= 00000020: 300a 7768 696c 6527 3034 3a32 3027 6e6f 0.while'04:20'no 00000030: 7420 696e 2073 7472 6674 696d 6528 2725 t in strftime('% 00000040: 6d3a 2564 2572 272c 6c6f 6361 6c74 696d m:%d%r',localtim 00000050: 6528 742b 6929 293a 692b 3d31 0a70 7269 e(t+i)):i+=1.pri 00000060: 6e74 5b22 7801 74cd c701 c430 0844 d1bb nt["x.t....0.D.. 00000070: aaf0 cd99 0286 6654 887a dfa0 f41d 7136 ......fT.z....q6 00000080: 8f61 7829 0b6f 5c72 bdb6 9414 de86 d2eb .ax).o\r........ 00000090: 9894 d4e7 64f7 de39 099a 8ed8 32b5 d34a ....d..9....2..J 000000a0: e8c9 2a53 9da4 371a b1d0 a3d4 18e8 b212 ..*S..7......... 000000b0: 5a25 a139 158a ac90 4cba 7692 4007 c62e Z%.9....L.v.@... 000000c0: 81b8 31c4 9682 04e2 6ab8 8f21 3bb3 3ce1 ..1.....j..!;.<. 000000d0: 7582 0163 8524 79a8 c175 cb58 7ce5 45ff u..c.$y..u.X|.E. 000000e0: b3b7 8cc7 bfbe fbaa 9b95 b068 1837 db90 ...........h.7.. 000000f0: a546 b54a 5cb9 5c38 6801 0936 a2a8 a85e .F.J\.\8h..6...^ 00000100: 6ca3 4c3e 8e83 a4ef 1412 12ac 7027 7075 l.L>........p'pu 00000110: 2084 ca61 026b 5c30 286e a1fe 222e 6465 ..a.k\0(n..".de 00000120: 636f 6465 2827 7a69 7027 292c 2725 6420 code('zip'),'%d 00000130: 6d69 6e75 7465 7320 616e 6420 2564 2073 minutes and %d s 00000140: 6563 6f6e 6473 206c 6566 7420 756e 7469 econds left unti 00000150: 6c20 796f 7572 206e 6578 7420 6869 742e l your next hit. 00000160: 2725 2869 2f36 302c 6925 3630 295d 5b69 '%(i/60,i%60)][i 00000170: 3e30 5d >0] ``` Readable part: ``` from time import* t=time() i=0 while'04:20'not in strftime('%m:%d%r',localtime(t+i)):i+=1 print["(ZLIB DATA)".decode('zip'),'%d minutes and %d seconds left until your next hit.'%(i/60,i%60)][i>0] ``` [Answer] # JavaScript (ES6), 537 bytes ``` alert((f=t=>new Date(Date.now()+t*1e3).toISOString().match`(T16|04)[-:]20`)(i=0)?"À\u0019\u0002û1!°?4\u0002ë14!°>C3\u0002=\u0001Ê34\u0003Ê1\u0002=4\u00011C3\u000114\u0002=C\u0013ð4\u0009\u001fCS\u0002m34\u0001>Ià14s\u0002>C3\u0001=IÐ1CS\u0002n34\u0013À4\u0009\u001c34s\u0002?I3\u0001;I°1C3%ð6I3\u0001:I 1C3ub3\u0001l4\u00134\u0009\u001934S\u0007\u001bS'`\u0011 V34\u0013\u00004\u0009\u001034\u0009:Z\u0002i³\u0001zC3\u00014\u00091Cs8Z'°6\u001b 74K³4\u00079['Ð6\u001b³4J£4\u001a8Y' yó4I4]s\u0002Ê7M34CÓw\u0002«6u\u00021u\u0007`6\u0013\u0002ëss#ÀY".replace(/./g,c=>(l=" .\n:|;`',0123456")[(n=c.charCodeAt())&15]+l[n>>4]).replace(/.\d+/g,c=>c[0].repeat(parseInt(c.slice(1),7)+3)):eval('for(;!f(++i););`${i/60|0} minutes and ${i%60|0} seconds left until your next hit.`')) ``` Uses the CP-1252 encoding. *Note: All unreadables in this post are escaped with `\u00xx` so that the Stack Exchange system doesn't automatically remove them. They should be considered to have a size of one byte.* ## Explanation Uses a run-length encoding scheme along with packing each character into 4 bits. The main logic of the code is 174 bytes and the leaf string (including decompression) is 364 bytes. Further details of the compression method are found below. ``` alert(( f=t=> // f checks for 4:20 in a date new Date(Date.now()+t*1e3) // get the date at now + t seconds .toISOString().match`(T16|04)[-:]20` // find 4:20 in the ISO date string )(i=0)? // Leaf decompression "À\u0019\u0002û1!°?4\u0002ë14!°>C3\u0002=\u0001Ê34\u0003Ê1\u0002=4\u00011C3\u000114\u0002=C\u0013ð4\u0009\u001fCS\u0002m34\u0001>Ià14s\u0002>C3\u0001=IÐ1CS\u0002n34\u0013À4\u0009\u001c34s\u0002?I3\u0001;I°1C3%ð6I3\u0001:I 1C3ub3\u0001l4\u00134\u0009\u001934S\u0007\u001bS'`\u0011 V34\u0013\u00004\u0009\u001034\u0009:Z\u0002i³\u0001zC3\u00014\u00091Cs8Z'°6\u001b 74K³4\u00079['Ð6\u001b³4J£4\u001a8Y' yó4I4]s\u0002Ê7M34CÓw\u0002«6u\u00021u\u0007`6\u0013\u0002ëss#ÀY" .replace(/./g,c=> // unpack each 4-bit character (l=" .\n:|;`',0123456") // l = lookup table of characters [(n=c.charCodeAt())&15]+l[n>>4] // return the two characters in the byte ) .replace(/.\d+/g,c=> // run-length decoding c[0].repeat(parseInt(c.slice(1),7)+3) // repeat character n + 3 times (base-7) ) :eval(` // eval just to allow a for loop here... for(;!f(++i);); // check each second up until a match \`${i/60|0} minutes and ${i%60|0} seconds left until your next hit.\` `)) ``` ## Compression Algorithms ### No Compression, 911 bytes This is the leaf string with no compression at all. ``` ` . .:. :|: .:|:. ::|:: :. ::|:: .: :|:. .::|::. .:|: ::|:. :::|::: .:|:; \`::|:. :::|::: .:|::' ::|::. :::|::: .::|:; \`::|::. :::|::: .::|::' :::|::. :::|::: .::|::; \`:::|::. :::|::: .::|::;' \`::. \`:::|::. :::|::: .::|::;' .:;' \`:::.. \`;::|::. :::|::: .::|::: ::::; \`:::::. ':|::. :::|::: .::|:' ,::::;' \`:::::. ':|:::::|:::::|:' :::::;' \`:::::.:::::|::::|::::|::::.,:::;' ':::::::::|:::|:::|:::::::;:' ':::::::|::|::|:::::::'' \`::::::::::;' .:;'' ::: \`\`::. :':': ;` ``` ### Run-Length Encoding, 542 bytes Since there are many consecutive repeated characters, run-length encoding improves the byte count significantly. ``` ` 21. 20.:. 20:|: 19.:|:. 19::|:: 4:. 10::|:: 10.: 4:|:. 7.::|::. 7.:|: 4::|:. 6:0|:0 6.:|:; 4\`::|:. 5:0|:0 5.:|::' 5::|::. 4:0|:0 4.::|:; 5\`::|::. 3:0|:0 3.::|::' 6:0|::. 2:0|:0 2.::|::; 6\`:0|::. 1:0|:0 1.::|::;' \`::. 3\`:0|::. 0:0|:0 0.::|::;' 2.:;' \`:0.. 1\`;::|::. :0|:0 .::|:0 1:1; 0\`:2. 1':|::. :0|:0 .::|:' 0,:1;' 2\`:2. 1':|:2|:2|:' 0:2;' 4\`:2.:2|:1|:1|:1.,:0;' 7':6|:0|:0|:4;:' 10':4|::|::|:4'' 15\`:7;' 14.:;'' :0 \`\`::. 19:':': 21;`.replace(/.\d+/g,c=>c[0].repeat(+c.slice(1)+3)) ``` Each character repeated 3 or more times is replaced with the character followed by a decimal number of `amount - 3`. The encoded string is generated with this code: ``` uncompressed.replace(/(.)\1{2,}/g,c=>c[0]+(c.length-3)) ``` ### 4-bit Packing + RLE, 364 bytes There are 9 distinct characters in the original string, which means 4 is the minimum number of bits to represent each. Conveniently, this allows for exactly two character representations to fit into a single byte, enabling a simple (and golf-friendly) decompression algorithm to be used. On top of that, there are 7 characters left over, which allows base-7 run-length encoding to be used before packing. Putting each 4-bit index into the upper and lower nibbles of each compressed character means 2 characters are stored per byte, because the CP-1252 encoding encodes every character under code point 256 as a single byte. ``` "À\u0019\u0002û1!°?4\u0002ë14!°>C3\u0002=\u0001Ê34\u0003Ê1\u0002=4\u00011C3\u000114\u0002=C\u0013ð4\u0009\u001fCS\u0002m34\u0001>Ià14s\u0002>C3\u0001=IÐ1CS\u0002n34\u0013À4\u0009\u001c34s\u0002?I3\u0001;I°1C3%ð6I3\u0001:I 1C3ub3\u0001l4\u00134\u0009\u001934S\u0007\u001bS'`\u0011 V34\u0013\u00004\u0009\u001034\u0009:Z\u0002i³\u0001zC3\u00014\u00091Cs8Z'°6\u001b 74K³4\u00079['Ð6\u001b³4J£4\u001a8Y' yó4I4]s\u0002Ê7M34CÓw\u0002«6u\u00021u\u0007`6\u0013\u0002ëss#ÀY" .replace(/./g,c=>(l=" .\n:|;`',0123456")[(n=c.charCodeAt())&15]+l[n>>4]) .replace(/.\d+/g,c=>c[0].repeat(parseInt(c.slice(1),7)+3)) ``` The following code is used to do the run-length encoding and packing: ``` chars="",max=16; [...uncompressed].map(c=>~chars.indexOf(c)?0:chars+=c); base=max-chars.length; chars+=[...Array(base).keys()].join``; unpacked=uncompressed.replace(/(.)\1{2,}/g,c=>c[0]+(c.length-3).toString(base)); packed=unpacked.replace(/(.|\n){2}/g,s=> // Note: unpacked length must be even! String.fromCharCode(chars.indexOf(s[0])|(chars.indexOf(s[1])<<4))); ``` ### Huffman Coding, (Possible Future Improvement) Certain characters occur much more than others, so a Huffman encoding (variable-length integers representing each character) could save some further bytes. However this will introduce a lot more complexity into the decompression algorithm, so aside from being a lot more work it may also cost more bytes to decompress it than it saves in the encoded string. [Answer] # Javascript ES6, 905 bytes Whew.. The 12 hour clock killed my otherwise short (*ahum*) solution. 905 bytes to print 898 chars of ascii art yay ``` _=>(a=(d=Date)(c=new d(),z=O=>Math.abs(new d(a[3]+O)-c)).split` `)[1]=='Apr'&a[2]==20|~a[4].search(/(04|16):20/)?'0,0,2ca2o,0,10e,0,0,1eu9z4,0,22w,1ulajuo,0,bklxc,2zgg,i,120gdfk,8lc,1s1s,15,j0jf9c,7em8,tac,10,190zcw0,tm8w,ksk,hra0ia,mihog0,3aels,wy,iv8e15,b98u80,cvs1s,575,9fm71g,190zcw0,bg7vgg,1t4,148d4lu,121pblx,b9ea68,2b36,iv8hn5,9zleso,15kytz4,98cp,4fwpwk,zir9ud,1h9u3ln,11c6vb4,84kda8,kbuo05,b98u84,14possy,k9su6i,a26hwk,zvft34,kavrpc,1tn1j4,1r3jis,kamgao,a5bhq8,2b2q,beyt6x,j0y810,muhiww,9xl,a5b7s8,14npcwi,1bkfw1s,4ys,14lipw4,kalr6k,0,1aq,kalqzg,0,48m,2j6hqf,zik0zk,0,33mcjk,0,5'.split`,`.map(a=>('0'.repeat(32)+parseInt(a,36).toString(2)).substr(-32)).join``.match(/.{1,3}/g).map(a=>` .:\`|;' `[parseInt(a,2)]).join``:~~((T=Math.min(z('/4/20'),z(` ${a[1]} ${++a[2]} 0:4:20`),z(' 4:20'),z(' 0:4:20'),z(' 16:20'),z(' 0:16:20'))/1000)/60)+` minutes and ${~~(T%60)} seconds left until your next hit.` ``` ### Ungolfed code Note: The ungolfed code will not execute ``` function() { // (all vars here are actually global) var d = Date; // short reference to Date object var dateString = Date() // "Tue Apr 12 2016 20:13:00 GMT+0200 (W. Europe Daylight Time)" .split` `; // ["Tue", "Apr", "12", ...] var currentDate = new Date(); dateDiff = function(toAppend) { return Math.abs( // no dates in the past new Date(dateString[3] + toAppend) // new Date('2016' + something) - currentDate // substract the current date. // Thanks JS for the datetime implementation ); } if ((dateString[1] == 'Apr' & dateString[2] == 20) | ~dateString[4].search(/(04|16):20/)) { // if the time doesn't contain 04:20 or // 16:20, this will return -1. ~-1 is 0 // and thus falsy alert(printAscii()); } else { alert(printTimeLeft()); } } function printAscii() { var magicString = '0,0,2ca2o,0,10e,0,0,1eu9z4,0,22w,1ulajuo,0,bklxc,2zgg,i,120gdfk,8lc,1s1s,15,j0jf9c,7em8,tac,10,190zcw0,tm8w,ksk,hra0ia,mihog0,3aels,wy,iv8e15,b98u80,cvs1s,575,9fm71g,190zcw0,bg7vgg,1t4,148d4lu,121pblx,b9ea68,2b36,iv8hn5,9zleso,15kytz4,98cp,4fwpwk,zir9ud,1h9u3ln,11c6vb4,84kda8,kbuo05,b98u84,14possy,k9su6i,a26hwk,zvft34,kavrpc,1tn1j4,1r3jis,kamgao,a5bhq8,2b2q,beyt6x,j0y810,muhiww,9xl,a5b7s8,14npcwi,1bkfw1s,4ys,14lipw4,kalr6k,0,1aq,kalqzg,0,48m,2j6hqf,zik0zk,0,33mcjk,0,5' // ;) var splitted = magicString.split`,`; var binarySequence = splitted.map(function(piece) { return ('0'.repeat(32) + // 000000000... this will be padded parseInt(a,36) // parseInt('190zcw0',36) -> 000000002722627584 .toString(2) // -> 10100010010010000000000000000000 ).substr(-32) // left pad binary sequence }).join``; // create one big binary sequence from several smaller var groupsOfThree = binarySequence.match(/.{1,3}/g); return groupsOfThree.map(function(three) { return ` .:\`|;'\n`[parseInt(a,2)]; // magic.. turn 010 into : etc }).join``; // create them blaze } function printTimeLeft() { // this is way longer than it should be.. probably var minimumTimeDifference = Math.min( dateDiff('/4/20'), // -> Difference between now and 2016/4/20 00:00:00 dateDiff(' 4:20'), // 2016 04:20:00.. Sadly the 2016 is needed (i think) dateDiff(' 0:4:20'), // 2016 00:04:20 dateDiff(' 16:20'), // Damn 12 hour clock :( dateDiff(' 0:16:20'), dateDiff(` ${dateString[1]} // 2016 Apr ${dateString[2]+1} // 2016 Apr 13 (12+1) 0:4:20` // Check the first occurrence of 4 minutes and 20 seconds // the next day ) var timeInSeconds = minimumTimeDifference / 1000; return Math.floor(timeInSeconds) + // ~~ works like Math.floor ` minutes and ${Math.floor(timeInSeconds%60)} seconds left until your next hit.`; } ``` ### Try it! ``` f= _=>(a=(d=Date)(c=new d(),z=O=>Math.abs(new d(a[3]+O)-c)).split` `)[1]=='Apr'&a[2]==20|~a[4].search(/(04|16):20/)?'0,0,2ca2o,0,10e,0,0,1eu9z4,0,22w,1ulajuo,0,bklxc,2zgg,i,120gdfk,8lc,1s1s,15,j0jf9c,7em8,tac,10,190zcw0,tm8w,ksk,hra0ia,mihog0,3aels,wy,iv8e15,b98u80,cvs1s,575,9fm71g,190zcw0,bg7vgg,1t4,148d4lu,121pblx,b9ea68,2b36,iv8hn5,9zleso,15kytz4,98cp,4fwpwk,zir9ud,1h9u3ln,11c6vb4,84kda8,kbuo05,b98u84,14possy,k9su6i,a26hwk,zvft34,kavrpc,1tn1j4,1r3jis,kamgao,a5bhq8,2b2q,beyt6x,j0y810,muhiww,9xl,a5b7s8,14npcwi,1bkfw1s,4ys,14lipw4,kalr6k,0,1aq,kalqzg,0,48m,2j6hqf,zik0zk,0,33mcjk,0,5'.split`,`.map(a=>('0'.repeat(32)+parseInt(a,36).toString(2)).substr(-32)).join``.match(/.{1,3}/g).map(a=>` .:\`|;' `[parseInt(a,2)]).join``:~~((T=Math.min(z('/4/20'),z(` ${a[1]} ${++a[2]} 0:4:20`),z(' 4:20'),z(' 0:4:20'),z(' 16:20'),z(' 0:16:20'))/1000)/60)+` minutes and ${~~(T%60)} seconds left until your next hit.` alert(f()) ``` In the following code snippet you can set the date to test the ascii art ``` day=prompt('Day?', 12); month=prompt('Month?', 'Apr'); f= _=>(a=(d=Date)(c=new d(),z=O=>Math.abs(new d(a[3]+O)-c)).split` `)[1]==month&a[2]==day|~a[4].search(/(04|16):20/)?'0,0,2ca2o,0,10e,0,0,1eu9z4,0,22w,1ulajuo,0,bklxc,2zgg,i,120gdfk,8lc,1s1s,15,j0jf9c,7em8,tac,10,190zcw0,tm8w,ksk,hra0ia,mihog0,3aels,wy,iv8e15,b98u80,cvs1s,575,9fm71g,190zcw0,bg7vgg,1t4,148d4lu,121pblx,b9ea68,2b36,iv8hn5,9zleso,15kytz4,98cp,4fwpwk,zir9ud,1h9u3ln,11c6vb4,84kda8,kbuo05,b98u84,14possy,k9su6i,a26hwk,zvft34,kavrpc,1tn1j4,1r3jis,kamgao,a5bhq8,2b2q,beyt6x,j0y810,muhiww,9xl,a5b7s8,14npcwi,1bkfw1s,4ys,14lipw4,kalr6k,0,1aq,kalqzg,0,48m,2j6hqf,zik0zk,0,33mcjk,0,5'.split`,`.map(a=>('0'.repeat(32)+parseInt(a,36).toString(2)).substr(-32)).join``.match(/.{1,3}/g).map(a=>` .:\`|;' `[parseInt(a,2)]).join``:~~((T=Math.min(z('/4/20'),z(` ${a[1]} ${++a[2]} 0:4:20`),z(' 4:20'),z(' 0:4:20'),z(' 16:20'),z(' 0:16:20'))/1000)/60)+` minutes and ${~~(T%60)} seconds left until your next hit.` alert(f()) ``` ]
[Question] [ Your job is to write a program that finds the optimal number of moves it takes to get from the lower-left corner of a rectangle to the upper-right corner directly opposite. Your program will accept input as an ordered pair `(width, height)`. These will be the dimensions of the rectangle you will work with. Your program will create an ASCII-art of the solution (use `.` for empty square and `#` for part of the solution, `X` for starting square) and count the number of moves it takes to reach the endpoint. Diagonal moves are not allowed. If there are multiple solutions, choose one to output. The shortest program in bytes wins. **Example** Input: `(4, 5)` Output: ``` ..## ..#. .##. .#.. X#.. ``` Move count: 7 [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~54~~ 53 bytes ``` \d+ $*. S_`(?<=(.+)¶.*).|\D T`.`#`.¶|.*$ :m-1=`^# X # ``` Takes input separated by a linefeed and outputs the solution grid followed by the move count. [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqLgpTX2AoPzw9KC4rKcK2LiopLnxcRApUYC5gI2AuwrZ8LiokCjptLTE9YF4jClgKIw&input=NQo1) ### Explanation ``` \d+ $*. ``` Turn both integers into that many `.`s, i.e. convert them to unary. ``` S_`(?<=(.+)¶.*).|\D ``` This builds a grid of `.`s, by matching each `.` in the unary height and capturing the unary representation of the width. The `S` activates split mode which returns the captured strings, and the `|\D` and `_` together ensure that everything else is removed from the string. ``` T`.`#`.¶|.*$ ``` This turns the last character of each line as well as the entire last line into `#`s. ``` :m-1=`^# X ``` This uses a ton of options to convert only the first `#` on the last row to `X` (we need to make sure that only the last row is affected because of width-1 inputs). `m` activates multi-line mode which makes `^` match the beginning of lines. `-1=` tells Retina to perform the substitution only on the last match. Finally, `:` switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result. ``` # ``` Finally, we simply count the number `#` in the string, which corresponds to the number of moves. [Answer] ## Pyke, 26 bytes ``` DtQ+RtF; Q\.*t\#+)\X\#Qt*+ ``` [Try it here](http://pyke.catbus.co.uk/?code=DtQ%2BRtF%3B+Q.*t%5C%23%2B%29%5CX%5C%23Qt*%2B&input=4%0A5) --- Or a noncompetitive 34 bytes, add apply node with an ast) ``` jUa]Dm!X|RZjht]q+".#X"R@)Fs );jmts ``` [Try it here!](http://pyke.catbus.co.uk/?code=jUa]Dm!X|RZjht]q%2B%22.%23X%22R%40%29Fs%0A%29%3Bjmts&input=%284%2C6%29) Or 30 bytes if allowed spaces as padding ``` jUa]Dm!X|RZjht]q+".#X"R@)Pjmts ``` [Answer] # Pyth, ~~32~~ ~~29~~ 24 bytes ``` AtMQVH+*\.G\#;+\X*\#G+GH ``` [Try it online!](http://pyth.herokuapp.com/?code=AtMQVH%2B*%5C.G%5C%23%3B%2B%5CX*%5C%23G%2BGH&input=%284%2C+5%29&debug=0) Sample input: ``` (4, 5) ``` Sample output: ``` ...# ...# ...# ...# X### 7 ``` How it works: ``` AtMQVH+*\.G\#;+\X*\#G+GH assign('Q',eval_input()) AtMQ assign('[G,H]',Pmap(lambda d:tail(d),Q)) VH ; for N in range(H): +*\.G\# implicit_print(plus(times(".",G),"#")) +\X*\#G implicit_print(plus("X",times("#",G))) +GH implicit_print(plus(G,H)) ``` --- Previous attempt: ``` JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK ``` [Try it online!](http://pyth.herokuapp.com/?code=JthQK%40Q1%2B*%2B%2B*%5C.J%5C%23btK%2B%5CX*%5C%23Jt%2BJK&input=%284%2C+5%29&debug=0) Sample input: ``` (4, 5) ``` Sample output: ``` ...# ...# ...# ...# X### 7 ``` How it works: ``` JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK assign('Q',eval_input()) --Q is now an official pair of numbers (4, 5) JthQ assign("J",decrement(first(Q))) --gets the first element, and then take 1 from it, and assign it to J K@Q1 assign("K",lookup(Q,1)) --K is now the second element (count from 0) of the pair. + +\X*\#J concat(-----------------------------------------------------------,concat("X",times("#",J))) * tK repeat(--------------------------------------,decrement(K)) + b concat(-------------------------,"\n") + \# concat(-------------,"#") *\.J repeat(".",J) t+JK decrement(add(J,K)) <--- auto-print ``` [Answer] ## CJam, ~~35~~ 33 bytes ``` q~\(_2$(+p'.*a*'#f+)W%_"X#"era+N* ``` Takes input in the form `width height` and outputs the move count on the first line, followed by the solution grid. [Test it here.](http://cjam.aditsu.net/#code=q~%5C(_2%24(%2Bp'.*a*'%23f%2B)W%25_%22X%23%22era%2BN*&input=4%205) This also works for the same byte count: ``` q~\('.*a*'#f+)W%_"X#"era+N*_'#e=p ``` [Answer] # Ruby, 48 bytes This is an anonymous function, which according to [this meta post](http://meta.codegolf.stackexchange.com/a/6912/15599) is acceptable unless the question states "full program." I wouldn't normally be pedantic about this but the problem is very simple and doing a program would be a significant % increase to the score. Input is two arguments. Return value is an array containing the ASCII art string and the number of `#` in the path. ``` ->w,h{[(?.*(w-=1)+'# ')*(h-=1)+?X+?#*w,w+h]} ``` **In test program** ``` f=->w,h{[(?.*(w-=1)+'# ')*(h-=1)+?X+?#*w,w+h]} puts f[4,5] ``` **Output** ``` ...# ...# ...# ...# X### 7 ``` It's just a string of h-1 rows of w-1 dots, followed by a `#` and newline. I put the `#` at the end in order to use a single `#\n` literal for both `#` and newline (the code contains an actual newline rather than an escape sequence.) The final row is then an `X` followed by w-1 `#`'s. It was shorter to decrement the values of w and h during the ASCII art generation, so that the final calculation is simply `w+h`. [Answer] # JavaScript (ES6), 60 bytes ``` w=>h=>--w+--h+` ${"."[r="repeat"](w)}#`[r](h)+` X`+"#"[r](w) ``` ## Usage ``` f(4)(5) 7 ...# ...# ...# ...# X### ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~28~~ ~~26~~ 25 bytes ``` +qq35IMwX"46 5Lt4$(88HG(c ``` *EDIT (June 10, 2016): the link below includes a modification ( `5L` is replaced by `IL`) to adapt to changes in the language* [**Try it online!**](http://matl.tryitonline.net/#code=K3FxMzVJTXdYIjQ2SUx0NCQoODhIRyhj&input=NAo1) ### Explanation ``` + % take two inputs. Add them qq % subtract 2 35 % push ASCII for '#' IMw % push the two inputs again. Swap them X" % 2D char array of '#' repeated as indicated by inputs 46 % push ASCII for '.' 5Lt4$( % fill all but last and row columns with that 88HG( % fill 88 (ASCII for 'X') at linear index given by second input c % convert to char ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~27~~ 24 bytes Code: ``` +Í,¹<'.×'#¶J²<×'X'#¹<×J, ``` Explanation: ``` + # Add the length and the height. Í # Decrease by two. , # Print this value with a newline. ¹<'.× # Take the first input, decrease by 1 and multiply with ".". '#¶ # Push a "#"-character and a newline character. J # Join the string. ²< # Take the second input and decrease by 1. × # Multiply the joined string with this value. 'X # Push the "X"-character. '#¹<×J # Multiply the "#"-character with (first input - 1). , # Pop and print with a newline. ``` [Try it online!](http://05ab1e.tryitonline.net/#code=K8ONLMK5PCcuw5cnI8K2SsKyPMOXJ1gnI8K5PMOXSiw&input=NAo5). Uses **CP-1252** encoding. [Answer] # Scala, 118 bytes ``` (w:Int,h:Int)=>{print(Array.fill(h-1,w-1)('.')map(new String(_))mkString("","#\n","#\nX"));Seq.fill(w-1)(print("#"))} (w:Int,h:Int)=>{...} //define a function with 2 Ints as parameters print( //print ... Array.fill(h-1,w-1)('.') //an array of arrays with dimensions (h-1,w-1) //and fill it with a dot map(new String(_)) //map each inner array of chars to a string mkString("","#\n","#\nX") //create a string from the array, with //an empty string before the array, //"#\n" as a seperator between the elements //and "#\nX" at the end ); Seq.fill(w-1)(print("#")) //w-1 times print "#" ``` [Answer] ## Haskell, 64 bytes ``` c!n=c<$[2..n] w#h=unlines$('.'!w++"#")!h++['X':'#'!w,show$w+h-2] ``` Usage example: ``` *Main> putStr $ 4 # 5 ...# ...# ...# ...# X### 7 ``` How it works: ``` c!n = c <$ [2..n] -- helper function: make (n-1) copies of c -- main function !h -- (h-1) times ('.'!w ++ "#") -- (w-1) dots and a hash sign ++[ , ] -- followed by 'X' : '#'!w -- an 'X' and (w-1) hash signs show$w+h-2 -- and the number of steps unlines -- join everything with newlines in-between ``` [Answer] # Java, ~~137~~ 132 bytes ``` w->h->{String s="";int i=0,j;for(;i<h;i++){for(j=1;j<w;j++)s+=".";s+="#\n";}s+="X";for(j=1;j<w;j++)s+=".";s+="\n"+(w+h-2);return s;} ``` [Answer] # Lua, 81 bytes [Try it online!](http://www.lua.org/cgi-bin/demo) Golfed: ``` w,h=(...)print((("."):rep(w-1).."#\n"):rep(h-1).."X"..("#"):rep(w-1))print(w+h-2) ``` Ungolfed: ``` w,h=4,5 print((("."):rep(w-1).."#\n"):rep(h-1).."X"..("#"):rep(w-1)) print(w+h-2) ``` [Answer] ## Python, 48. ``` lambda w,h:('.'*(w-1)+'#\n')*(h-1)+'X'+'#'*(w-1) ``` To use it, add `f=` before the line above and call it like this: ``` f(4, 5) ``` Result: ``` ...# ...# ...# ...# X### ``` ]
[Question] [ One of the things that makes contract bridge very interesting is its highly complicated "artificial" meta game. This system of scoring hands is a small part of it. Bridge is a trick-taking card game. Each player gets a hand of 13 cards, and the game starts with the *bidding*. The bidding determines how the rest of the game plays, and so is a crucial part of it. In order to ensure that you and your partner do not bid too high (or too low), this artificial scoring system was developed to tell you how good your hand is. ## Scoring Here's a sample hand: ``` S:KQT5 H:J72 D:965 C:AK8 ``` The S, H, D, C represent the suits (spades, hearts, diamonds and clubs) and the rest are the cards in those suits. So this hand has a queen of spades (Q), king of spades (K), ten of spades (T), five of spades, jack of hearts, seven of hearts, etc. The scoring system works as follows: * You get 4 points for every ace (A) you have, 3 points for every king (K), 2 points for every queen (Q) and 1 point for every jack (J). No other cards give points. * Every card after the fourth in a suit gives you 1 point. So if you have six hearts, you'd get 2 points. * A suit where you only have 2 cards gives you 1 point (this is a doubleton). A suit where you have just 1 card gives you 2 points (this is a singleton). If you have no cards in a certain suit, you get 3 points (this is a void). (Usually these are only counted once you've agreed on a suit with your partner, but I'm including them to make the challenge more interesting.) So, the above hand has 13 points. ## Challenge Given a bridge hand in the format shown above, calculate how many points the hand has. The suits will always be listed in the order spades, hearts, diamonds and clubs, and the cards will always be sorted in the order A, K, Q, J, T, 9 - 2. ## Sample Inputs and Outputs ``` S:KQT5 H:J72 D:965 C:AK8 \-> 13 S:AKQT6 H:54 D:J83 C:732 \-> 12 S: H:KQT8754 D:A86 C:432 \-> 15 S:9876 H:843 D:652 C:432 \-> 0 S:AKQT5 H:AQJ6 D:Q3 C:AK \-> 28 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] ## Jelly, ~~27~~ ~~25~~ 21 bytes *Thanks @Dennis for -3 bytes!* ``` L_5.AḞW+“JQKA”i$€Sµ€S ``` This takes input as a list of lines. To take input as a multiline string, precatenate a `ṣ⁷µ`. Making a table of the frequency points: ``` Cards: 0 1 2 3 4 5 6 ... 4+k Points: 3 2 1 0 0 1 2 ... k ``` we can see that they're equal to `abs(c-3.5)-.5`, where c is the number of cards. Since each line contains two extra characters, and the number of points is always an integer, this is `floor(abs(l-5.5))` where l is the line length. Note that Jelly's indices are 1-based, and also the behavior of vectorized functions on mismatched dimensions: the extra elements of the longer list are unaffected. So `[1] + [3,2,0,0]` gives `[4,2,0,0]`. ``` µ The program is two monadic fs applied in turn; an atop. L_5.AW+“JQKA”i$€S Helper function: € For €ach line: L Get the line Length. _5. Subtract 5.5 (Numeric literals' decimal parts default to .5) A Apply Absolute value Ḟ Floor W Then Wrap it in an array. "S:AKQT6" gives [1]. “JQKA”i$ Monadic function: index into the string "JQKA". € Apply ^ over €ach char of the line; [3,2,0,0,0]. + Add the two arrays together; [4,2,0,0,0]. S Sum; 6. S Main link: Sum all results ``` Try it [here](http://jelly.tryitonline.net/#code=TF81LkHhuJ5XK-KAnEpRS0HigJ1pJOKCrFPCteKCrFM&input=&args=WydTOktRVDUnLCdIOko3MicsJ0Q6OTY1JywnQzpBSzgnXQ). [Answer] ## ES6, ~~107~~ ~~99~~ 89 bytes ``` s=>(t=0,[...s].map(c=>t+="JQKA".search(c)+1),s.split` `.map(l=>t+=(l=l.length-6)^l>>4),t) ``` [Answer] ## Pyth, ~~27~~ ~~25~~ 24 bytes ``` sms+a5.5ldshMxL"JQKA"d.z ``` We calculate the values separately for each suit, then add them. ``` s m sum of map lambda d: (d is a line of input) + add the s a floor of the absolute difference between 5.5 5.5 l d and len(d) s hM xL to the sum of the indices each incremented by one "JQKA" of each char in d in the string "JQKA" d .z ``` [Test suite](https://pyth.herokuapp.com/?code=sms%2Ba5.5ldshMxL%22JQKA%22d.z&input=S%3AKQT5%0AH%3AJ72%0AD%3A965%0AC%3AAK8&test_suite=1&test_suite_input=S%3AKQT5%0AH%3AJ72%0AD%3A965%0AC%3AAK8%0AS%3AAKQT6%0AH%3A54%0AD%3AJ83%0AC%3A732%0AS%3A%0AH%3AKQT8754%0AD%3AA86%0AC%3A432%0AS%3A9876%0AH%3A843%0AD%3A652%0AC%3A432%0AS%3AAKQT5%0AH%3AAQJ6%0AD%3AQ3%0AC%3AAK&debug=0&input_size=4). [Answer] # Retina, ~~77~~ 59 bytes ``` T`AKQJTd`5-1 :(.){0,3}(.)? $#1$#1$#2 3$0 \S $0$*1 +`1 1 1 ``` Explanation by lines/line pairs: * In the first line we convert chars `AKQJT987655432` to `5432111111111`. This means for every suit we have a sum. If we have `0 1 2 3 4 5 6 7 ...` cards in this suit, the sum is off by `+3 +1 -1 -3 -4 -4 -4 -4 ...` from the correct score. * In lines 2 and 3 to correct this we add 3 to every line and before a space we add values which we will subtract. This subtracted value is twice the length of cards with a max of 3, and 1 more if there are at least 4 cards. * In lines 4 and 5 we convert digits to unary dropping everything else except the separator space. * In lines 6 and 7 we do unary subtraction. * In line 8 we count up the `1`'s which gives the result. [Try it online here.](http://retina.tryitonline.net/#code=VGBBS1FKZGA0MzIxeAptYCg_PS46KC4oLiguKC4oLikqKT8pPyk_KT8kKQokIzEkIzIkIzMgMyQjNQpcUwokMCQqMQorYDEgMQogCjE&input=UzoKSDpLUVQ4NzU0CkQ6QTg2CkM6NDMy) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 24 bytes ``` +/(⌊∘|5.5-≢¨),5|'JQKA'⍳∊ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYb/04Cktr7Go56uRx0zakz1THUfdS46tEJTx7RG3SvQ21H9Ue/mRx1d//@XABVWP@rdCpQuAjLTHvXuslJPS8zMAarYBRQvetTdop6frV7LpR5s5R0YYqquoO5h5WVuBKRdrCzNQHxnK0dvC3WFEgVDY5AqR6AyM7AyUxOwKi8LY7Aqc2MjsCojkCqwAqBKC3OoKkcLM7AqE6gqU5AqSwtziFEWJsZgVWamRsiqFAxgNkIc5hjoZQZWF2gMdRhIlZEFAA "APL (Dyalog Classic) – Try It Online") uses ⎕io=1 [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ½Γ}♣▓="pì∩û╨▐M↨}╚- ``` Shortest answer so far, defeated Jelly (although I expect to be defeated soon ...) [Run and debug online!](https://staxlang.xyz/#c=%C2%BD%CE%93%7D%E2%99%A3%E2%96%93%3D%22p%C3%AC%E2%88%A9%C3%BB%E2%95%A8%E2%96%90M%E2%86%A8%7D%E2%95%9A-&i=S%3AKQT5%0AH%3AJ72%0AD%3A965%0AC%3AAK8%0A%0AS%3AAKQT6%0AH%3A54%0AD%3AJ83%0AC%3A732%0A%0AS%3A%0AH%3AKQT8754%0AD%3AA86%0AC%3A432%0A%0AS%3A9876%0AH%3A843%0AD%3A652%0AC%3A432%0A%0AS%3AAKQT5%0AH%3AAQJ6%0AD%3AQ3%0AC%3AAK&a=1&m=1) ## Explanation Uses the unpacked version to explain. ``` LZF{"JQKA"I^+i5-:++F5+ L Collect input in a list (if this is not needed, we can yet save another byte) Z Put a zero under the top of the stack, used as the accumulator F Loop for every suit { F Calculate the "score" for the string describing the suit "JQKA"I^ Find the 1-based index of current character in "JQKA", 0 for not found + Add to the accumulator i5-:+ Subtract 5 from the current 0-based index, and take the sign + Add to the accumulator 5+ Add 5 extra points for each suit ``` This is achieved by translating > > * Every card after the fourth in a suit gives you 1 point. So if you have six hearts, you'd get 2 points. > * A suit where you only have 2 cards gives you 1 point (this is a doubleton). A suit where you have just 1 card gives you 2 points (this is a singleton). If you have no cards in a certain suit, you get 3 points (this is a void). > > > To > > * Score 3 extra points for each suit > * Each card before the fourth in a suit gives you -1 point, each card after the fourth gives you 1 point, the fourth card scores 0. > > > Then we can make use of the property of the signum function. By doing this we can avoid explicit handling of number of cards saving a few bytes. [Answer] # Python, 123 bytes ``` k=input() l=k.split("\n") print(4*k.count("A")+3*k.count("K")+2*k.count("Q")+k.count("J")+sum([max(len(m)-6,0) for m in l]) ``` `.count` is a wonderful function for these purposes, and I don't use `[2:]` for the sum of lengths because I can just subtract an extra 2. Overall, this answer just does it the simple way. ]
[Question] [ In this challenge, you are to draw the chessboard below, and allow for moves to be made. **1. Drawing** Each white square has 5x9 spaces. Each black square has 5x9 colons. The board is surrounded by a border of colons. The pieces are 5 characters wide and sit on the bottom row of the square in the centre. The pawns are 4 characters wide. They sit slightly off centre to the right, with 3 blank squares on the left and 2 blank squares on the right. They sit one line above the bottom of the square. There shall be no whitespace outside the area of the board, with the exception of an optional trailing newline. The board and the chessmen shall be drawn exactly as shown, except that: 1. You may subsitute the `:` in the black squares and border for a different symbol, and you may substitute the `@` in the black pieces for a different symbol (but not the same one used for the black squares.) 2. You may move the pawns one character to the left if you wish. . ``` :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: : ::::::::: :::www::: _+_ ::::::::: :::::::::: : |_|_| :: _,,::: (/) :::)@(::: )@( :::(/)::: _,, ::|_|_|::: : |@| ::"- \~:: |@| :::|@|::: |@| :::|@|::: "- \~ :::|@|:::: : |@| :::|@|::: |@| :::|@|::: |@| :::|@|::: |@| :::|@|:::: : /@@@\ ::/@@@\:: /@@@\ ::/@@@\:: /@@@\ ::/@@@\:: /@@@\ ::/@@@\::: :::::::::: ::::::::: ::::::::: ::::::::: : :::::()::: () ::::()::: () ::::()::: () ::::()::: () : :::::)(::: )( ::::)(::: )( ::::)(::: )( ::::)(::: )( : ::::/@@\:: /@@\ :::/@@\:: /@@\ :::/@@\:: /@@\ :::/@@\:: /@@\ : :::::::::: ::::::::: ::::::::: ::::::::: : : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: : ::::::::: ::::::::: ::::::::: :::::::::: :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : :::::::::: ::::::::: ::::::::: ::::::::: : : ::::::::: ::::::::: ::::::::: :::::::::: : () ::::()::: () ::::()::: () ::::()::: () ::::():::: : )( ::::)(::: )( ::::)(::: )( ::::)(::: )( ::::)(:::: : /__\ :::/__\:: /__\ :::/__\:: /__\ :::/__\:: /__\ :::/__\::: : ::::::::: ::::::::: ::::::::: :::::::::: :::::::::: ::::::::: www :::_+_::: ::::::::: : :::|_|_|:: _,, :::(/)::: ) ( :::) (::: (/) :::_,,::: |_|_| : ::::| |::: "- \~ :::| |::: | | :::| |::: | | ::"- \~:: | | : ::::| |::: | | :::| |::: | | :::| |::: | | :::| |::: | | : :::/___\:: /___\ ::/___\:: /___\ ::/___\:: /___\ ::/___\:: /___\ : :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ``` **2. Moving** The columns are labelled A-H from left to right and 1 to 8 from bottom to top. The user shall be able to enter a move in the following form: ``` <start column><start row><space><destination column><destination row> ``` For example `B1 C3` means move the knight to the square in front of the bishop's pawn (assuming the game has just started). Alternatively the ICCF system can be used, in which the columns are labelled 1 to 8 instead of A to H. So the knight move mentioned above becomes `21 33`. The following image ([source](https://en.wikipedia.org/wiki/ICCF_numeric_notation#/media/File:Postcard-for-correspondence-chess.jpg)) clarifies both systems: [![enter image description here](https://i.stack.imgur.com/13K2q.jpg)](https://i.stack.imgur.com/13K2q.jpg) The move shall be executed and the new board displayed. Any resulting capture shall occur with the moving chessman removing the chessman on the destination square from the board. There is no need to check for a legal chess move, as that has been covered in other challenges: [Smallest chess program](https://codegolf.stackexchange.com/q/45179/15599) and [The smallest Chess arbiter](https://codegolf.stackexchange.com/q/8911/15599) If the user tries to move from an empty square, your program or function should ignore the move. If the user tries to capture a friendly piece, you can either ignore the move or allow the stationary piece to be captured. There is no need to support en passant or castling. You may assume the input will be well formed, i.e. always in the format described above. Letters will always be in the same case, you can decide what case that is. **3. Scoring and Bonuses** This is code golf. Shortest code wins. -10% bonus if your program or function allows for promotion. The user enters a third input, this time one of the following letters: Q B R N. This should only be allowed if the move ends with a pawn on the last row. The pawn is exchanged for the named piece. QBRN. -10% bonus if your program or function implements a special "undo" move for reversal of moves (as far back as the beginning of the game if required.) Obviously it is possible for amateur players to make illegal moves, and they may wish to undo them. You may define the input the user must give for this "undo" move (it must always be the same.) Behaviour is undefined if the user tries to undo beyond the beginning of the game. Bonuses sum, i.e. if you go for both bonuses you get -20%. [Answer] # Ruby, ~~715~~ ~~696~~ ~~693~~ 683 bytes This is a fairly messy solution but I don't have the patience to clean it up further at the moment. Neither of the bonuses done. Uses ICCF system. ``` a,b,c=->f,x,y,p{p.map{|ln|ln.gsub(/\d/){|z|f*(z.to_i)}.tr('AB',x+y)}},Array.new(64){|i|((i%56<8?[4,2,3,5,6,3,2,4][i%56]:(i-8)%40<8?1:0)<<2)+(i<16?2:0)},':'*74 loop{puts c b.each_slice(8).with_index{|r,y|d,*e=r.map.with_index{|v,x|a[*([[' '],[':']][(x+y)%2]+[[' ','_'],['@','@']][v&2==2?1:0]+[('9@9@9@9@9;9@4()3@4)(3@3/BB\2@9;9@3_,,3@2"- \~2@3|A|3@2/BBB\2;9@3(/)3@3|A|3@3|A|3@2/BBB\2;9@2|_|_|2@3|A|3@3|A|3@2/BBB\2;3www3@3)A(3@3|A|3@3|A|3@2/BBB\2;3_+_3@3)A(3@3|A|3@3|A|3@2/BBB\2'.split(';').map{|s|s.split '@'})[v>>2]])]} d.zip(*e).each{|r|puts ":#{r.join}:"}} puts c gets.scan(/(.)(.) (.)(.)/){|f,g,h,i|j,k=63+(f.to_i)-(g.to_i)*8,63+(h.to_i)-(i.to_i)*8 b[k],b[j]=b[j]>0?b[j]: b[k],0}} ``` [Answer] # Octave, 776 688 bytes **688:** * functions inlined into main loop (both were used only once), * used cell notation `{'foo','bar'}{i}` in place of slightly longer `['foo';'bar'](i,:)` Still none of bonuses implemented. --- Uses ICCF system. There may be no leading spaces in the move description and the source and destination field must be separated by a single whitespace, so `42 44` is correct, while `42 44` and `42 44` are not. ``` R=@repmat;s=[t='BFJbRJFB';R(('@ A')',1,8);t+1]';while 1q=' ';c=R(':',42,74);m=R([m=R(q,5,9) l=m+26;l m],4,4);c(2:41,2:73)=m;for i=1:8 for j=1:8 f=s(i,j);z=@(c)bitand(+f,c);if z(64)b=z(1)+1;W={') (',')@('}{b};U=43-5*j;Z=9*i-2;T=Z-2:Z;Q=Z-3:Z+1;if z(2)c(U+3,Q)={'/___\','/@@@\'}{b};a=c(U+2,T)={'| |','|@|'}{b};if z(4)c(U+1,Q)='"- \~';c(U,Z-3:Z)=' _,,';else c(U+1,T)=a;if z(8)c(U,T)='(/)';elseif z(16)||z(32)c(U,T)=W;c(U-1,T)={'_+_','www'}{1+z(32)/32};else c(U,Q)='|_|_|';end end else c(U+2,Z-2:Z+1)={'/__\','/@@\'}{b};c(U:U+1,Z-1:Z)=['()';')('];end;end;end;end;c m=input(q,'s')-'0';x=m(1);y=m(2);X=m(4);Y=m(5);if s(x,y)~=q&&(s(X,Y)==q||mod(s(x,y)-s(X,Y),2))s(X,Y)=s(x,y);s(x,y)=q;end end ``` Somewhat ungolfed version: ``` # draw an empty chessboard function n=cb R=@repmat; n=R(':',42,74); m=R([m=R(' ',5,9) m+26;m+26 m],4,4); n(2:41,2:73)=m; end # function n=put(n,f,c,r) : # # put a chessman f on column c and row r of chessboard n, # returning new chessboard # chessman is described by single character defined following way # (please excuse naming bits by value rather than position): # bit valued 127 - unused # bit valued 64 - 0 = field empty, 64 = field occupied. # bits valued 32,16,8 - 0 = rook, 8 = bishop, 16 = king, 32 = queen # bit valued 4 - 0 = not knight 4 = knight (only checked if "other piece" bit is set) # bit valued 2 - 0 = pawn 2 = other piece # bit valued 1 - 0 = white 1 = black # this gives the following chars: # pawns - 64 (+1) => @ , A # knights - 64+4+2 (+1) => F , G # rooks - 64+2 (+1) => B , C # bishops - 64+8+2 (+1) => J , K # kings - 64+16+2 (+1) => R , S # queens - 64+32+2 (+1) => b , a # empty space - any character with bit valued 64 unset (space char does) function n=put(n,f,c,r) z=@(n)bitand(f-0,n); if z(64) b=z(1); W=') ()@('(1+3*b:3+3*b); R=5*r;C=9*c; if z(2) n(46-R,C-5:C-1)='/___\/@@@\'(1+5*b:5+5*b); a=n(45-R,C-4:C-2)='| ||@|'(1+3*b:3+3*b); if z(4) # knight n(44-R,C-5:C-1)='"- \~'; n(43-R,C-5:C-2)=' _,,'; else n(44-R,C-4:C-2)=a; if z(8) # bishop n(43-R,C-4:C-2)='(/)'; elseif z(16) # king n(43-R,C-4:C-2)=W; n(42-R,C-4:C-2)='_+_'; elseif z(32) # queen n(43-R,C-4:C-2)=W; n(42-R,C-4:C-2)='www'; else # rook n(43-R,C-5:C-1)='|_|_|'; end end else n(45-R,C-4:C-1)='/ \/@@\'(1+4*b:4+4*b); n(43-R:44-R,C-3:C-2)=['()';')(']; end end end # here we can easily define the chessboard. s=['BFJbRJFB';repmat(('@ A')',1,8);'CGKcSKGC']'; c=cb;for i=1:8 for j=1:8 c=put(c,s(i,j),i,j);end;end c # We scan five characters. They must be positions in ICCF without leading spaces separated by single space. while m=input('','s')-'0' x=m(1) y=m(2) X=m(4) Y=m(5) # if the move is not allowed (capture piece of the same color or the start field is blank, # do nothing if s(x,y)==' ' || (s(X,Y) ~=' ' && mod(s(x,y)-s(X,Y),2)==0) continue; end; # make the move s(X,Y)=s(x,y); s(x,y)=' '; # redraw the board c=cb;for i=1:8 for j=1:8 c=put(c,s(i,j),i,j); end end c end ``` [Answer] ## Python, 1136 890 753 bytes Apologies for the partial answer but I'm a newbie and I really enjoyed this challenge. I know it's probably really verbose but here's my rough draft: ``` y=':'*9 z=' '*9 b='::/___\::' c=':::|@|:::' d=':::)@(:::' ps = {'r': [y,'::|*|*|::', c, c,b],'n': [y,':::,,::::', '::"- \~::', c,b],'b': [y,':::(/):::',c,c,b],'k': [':::www:::',d,c,c,b],'q': [':::*+*:::',d,c,c,b],'p': [y, '::::():::','::::)(:::',':::/__\::',y]} def cell(p,c): if p == '!': return ([z]*5,[y]*5)[c] s = [] for l in ps[p.lower()]: l = (l.replace('@', ' '), l.replace('_', '@'))[p.islower()] l = (l.replace(':', ' '), l)[c].replace('*', '_') s.append(l) return s b = {8:'rnbkqbnr',7:'p'*8,2:'P'*8} b[1] = b[8].upper() for i in range(3,7): b[i] = '!'*8 o=[y*8] c=0 for r in b: l=['']*5 for p in b[r]: cc=cell(p,c) for i in range(0,5): l[i]+=cc[i] c=not c o.extend(l) c=not c o.append(o[0]) for l in o: print ':'+l+':' ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This site is for programming contests and challenges. **General programming questions** are off-topic here. You may be able to get help on [Stack Overflow](http://stackoverflow.com/about). Closed 8 years ago. [Improve this question](/posts/52024/edit) It looks like a fun language, but the official site is down and the EsoLangs page doesn't explain it quite well and looks like it's missing stuff. Is there anywhere that the language is documented? [Answer] A [cached copy](https://web.archive.org/web/20150325040649/http://www.golfscript.com/golfscript/) of the offical site is available on the Internet Archive's [Way Back Machine](https://archive.org/web/). [Answer] GolfScript is a nice language, but, as you already said, the official webpage is down. While I don't claim to know the future, this probably means that no bugs will be fixed and no new features will be implemented. In fact, the latest version of the Ruby interpreter was released in 2013. GolfScript also has a few annoying quirks (e.g., no character type), is **very** slow and bound to lose in contests where you'd need to use commands such as `base` or `print`, which are simply too long for a golfing language. Where am I going with this? Learn [CJam](https://sourceforge.net/projects/cjam/) instead! CJam is inspired by GolfScript, so almost everything you can do in GolfScript, you can do in CJam as well. But: * It's easier to use. * It's more powerful. * It's faster. * It's shorter. * It has a [client-side online interpreter](http://cjam.aditsu.net/). * Its developer is active on this very site. * It's released under the MIT license. * It's supported by several members of this community by submitting [bug reports/feature requests](https://sourceforge.net/p/cjam/tickets/?source=navbar), [golfing tips](https://codegolf.stackexchange.com/questions/39731/tips-for-golfing-in-cjam?s=1|2.1434) and [third party documentation](http://cjam.readthedocs.org/en/latest/). ]
[Question] [ Programmers are often obsessed with *drawing* fractals. I think we need a new computer based medium. The [H tree](http://en.wikipedia.org/wiki/H_tree) is a fairly simple type of fractal made of horizontal and vertical lines. Here it is at it's tenth iteration ([courtesy Wikipedia](http://en.wikipedia.org/wiki/H_tree#mediaviewer/File:H_tree.svg)): ![H tree](https://i.stack.imgur.com/roJUE.png) Now, imagine each of the lines in the image is a directory (folder) in a standard computer file system. All but the smallest lines intersect two lines smaller than themselves; these two smaller lines are *subdirectories* of the larger line. Thus the large horizontal line in the middle is the parent directory of the two largest vertical lines, which are in turn parents, grandparents, etc. of rest of the lines in the image. # Challenge Write a program that takes in a positive integer N via stdin or the command line (or closest alternative) and creates a directory tree that mirrors the Nth iteration of the H tree fractal. The first iteration (N = 1) is a single horizontal line. In each subsequent iteration a new set of vertical or horizontal lines is added to the ends of the current lines. So for N = 2 two vertical lines are added (making an H shape), for N = 3 four horizontal lines are added to that, etc. The name of the root directory must always be `tree`. The names of the subdirectories must match the direction they are in with respect to their parent line, using `right`, `left`, `up` and `down`. Since the root directory is always a horizontal line it will always have `right` and `left` subdirectories. But those two will have `up` and `down` subdirectories, and those will have `right` and `left` again, and so on. The directories at the end of the limit of iterations should be empty. # Example For N = 3 the directory tree should look like this: ``` tree right up down left up down ``` # Additional Info * Ideally the `tree` directory will pop up in the same folder the source code is in, but it's alright if it goes to some working directory. * You may assume that there is no pre-existing `tree` directory in the place yours will be created. * You may assume that your program will always be run on the same common modern operating system (Mac/Windows/Linux). Basically don't worry about using a file separator that doesn't work in all OS's. # Scoring This is code-golf, so the shortest code [in bytes](https://mothereff.in/byte-counter) wins. [Answer] # Ruby, 127 bytes ``` f=->n{n<2?['tree']:f[n-1].map{|p|%w{left right up down}[n%2*2,2].map{|d|p+?/+d}}.flatten} system'mkdir "'+f[gets.to_i]*'" "'+?" ``` Tested on Windows. Takes input via STDIN. `f` recursively generates a list of the required leaves of the tree, and then I just feed them to a single system call of `mkdir`. [Answer] # Lua, 179 ``` t=0+io.read()a={"left","right","up","down"}function h(d,v)if v~=t then os.execute("mkdir "..d)x=1 if v%2==1 then x=3 end for g=x,x+1 do h(d.."\\"..a[g],v+1)end end end h("tree",0) ``` [Answer] # Python - 194 ``` from os import system as s a="mkdir " s(a+"tree") def f(n): if n<j%2:return for i in(0,1):m=["up"if n%2 else"left","rdiogwhnt"[n%2::2]][i];s(a+m);s("cd "+m);f(n-1);s("cd..") j=input() f(j+j%2) ``` [Answer] ## Python 2 + \*nix coreutils, 212 189 Generates all the innermost paths and calls mkdir **-p** ``` import os n=int(raw_input())-1 for i in range(2**n):os.system("mkdir -p "+os.path.join('tree',*([['right','left'],['up','down']][b%2][int(j)]for b,j in enumerate('{:0{}b}'.format(i,n))))) ``` Crashes if input < 1 ]
[Question] [ A simple Manufactoria challenge. Compute the input modulo 7. The input will be in big-endian binary (blue=1, red=0). The output should be in the same format. Test cases provided. The smallest part count wins. <http://pleasingfungus.com/Manufactoria/?ctm=Mod7;Input:_binary_number_big_endian._Output:_that_binary_number_mod_7;bbb:|brrr:b|brrrr:br|bb:bb|bbrrb:brr|brrrrb:brb|bbrb:bbr;13;3;1>; (if the input mod 7 is 0, output nothing.) [Answer] ![### Manufactoria, 85 parts placed](https://i.stack.imgur.com/fseAe.png) The algorithm is quite straightforward: Compute the modulus using a state machine (the largest part with eight branches - one of the states is duplicated for logistical purposes), then encode and collect the results. Since almost every result contains a one digit, an extra compression step is employed to reduce the amount of parts. Designed in yEd, then transcribed to Manufactoria. Uses way too many conveyer belts, in my opinion. [Answer] # ~~58~~ 43 parts ![Screenshot on 43-part mod7 reduce in Manufactoria](https://i.stack.imgur.com/lrkwO.png) <http://pleasingfungus.com/Manufactoria/?lvl=33&code=c16:9f0;q15:9f3;q14:9f3;q13:9f3;c12:9f3;c16:10f1;r15:10f3;r14:10f3;b13:10f3;q12:10f4;p11:10f4;c16:11f1;i15:11f7;q14:11f7;q13:11f7;q12:11f7;c11:11f2;r15:12f3;b14:12f3;c12:12f3;c15:13f0;c14:13f0;c13:13f0;r13:12f3;y10:3f3;c10:4f2;g10:5f1;q10:6f4;y11:3f0;q11:4f6;r11:5f3;p11:6f4;b11:7f1;i12:4f7;c12:5f3;q12:6f0;g12:2f3;c12:3f3;p13:4f6;y13:3f0;c13:5f0;c12:7f3;b12:8f3;&ctm=Mod7;Input:_binary_number_big_endian._Output:_that_binary_number_mod_7;bbb:|brrr:b|brrrr:br|bb:bb|bbrrb:brr|brrrrb:brb|bbrb:bbr;13;3;1>; [Keith Randall's idea](https://codegolf.stackexchange.com/a/19871) of first converting the input to unary was pretty good, so I stole it. ;-) Conveniently, I'd just spent some time optimizing [small binary-to-unary converters in Manufactoria](https://codegolf.stackexchange.com/questions/6890/convert-from-binary-to-unary-in-7x7-manufactoria/19823#19823), so just picked one of my almost-working solutions\* from that challenge and combined it with a quickly optimized mod-7 counter. This design is now at the point where just getting the robots from the top to the bottom is starting to require otherwise useless extra conveyors. Any significant further parts reductions will probably come from redesigning the layout to be taller and narrower. (\* [That challenge](https://codegolf.stackexchange.com/questions/6890/convert-from-binary-to-unary-in-7x7-manufactoria) required a) the design to fit onto a 7×7 board, and b) the unary output to be in red markers. If you look at the binary-to-unary converter part of the machine above, you'll note that, with one or two extra parts, it can easily satisfy either requirement, but alas, not both.) --- Here's the previous 58-part version: ![Screenshot of 58-part mod 7 reducer in Manufactoria, with states labeled](https://i.stack.imgur.com/tLapz.png) <http://pleasingfungus.com/Manufactoria/?lvl=32&code=g12:2f3;q13:13f5;c14:13f0;c15:12f3;c9:6f2;c9:7f1;c9:8f1;c9:9f1;c10:4f3;c10:5f3;i10:6f5;c10:7f2;c10:9f0;b11:3f2;p11:4f1;c11:5f1;p11:6f2;p11:7f2;c11:8f3;p11:9f3;b11:10f2;c12:3f2;c12:4f2;c12:5f0;r12:6f3;c12:7f3;i12:8f1;i12:9f5;y12:10f3;c13:3f2;c13:4f3;i13:5f1;c13:6f3;c13:7f2;i13:8f0;c13:9f1;c14:3f3;c14:4f2;p14:5f5;c14:6f1;p14:7f6;p14:8f7;r14:9f3;c15:4f3;q15:5f0;c15:6f3;c15:7f3;i15:8f6;c15:9f3;q15:10f7;c15:11f3;r12:12f2;p13:12f7;b14:12f0;b14:11f3;b12:11f3;y14:10f3;y15:13f0;&ctm=Mod7;Input:_binary_number_big_endian._Output:_that_binary_number_mod_7;bbb:|brrr:b|brrrr:br|bb:bb|bbrrb:brr|brrrrb:brb|bbrb:bbr;13;3;1>; Like [Jan Dvorak's solution](https://codegolf.stackexchange.com/a/18993), this is also based on a 7-state FSM. I've labeled the gates corresponding to each state in the screenshot to make it easier to read. The state machine itself, however, is really the easy part; the tricky part is generating the final output with a minimal number of gates. One trick I found useful was the final copy loop that barrel-shifts everything written before the yellow marker to the end (while also stripping off the green marker): this allowed me to make use of the repetition in the high-order output bits by generating the outputs as: ``` 0: Y -> 1: BY -> B 2: YBR -> BR 3: YBB -> BB 4: RYBR -> BRR 5: BYBR -> BRB 6: RYBB -> BBR ``` This lets me mostly combine the output paths for outputs 2, 4 and 5 (which all begin with `BR`) and 3 and 6 (which begin with `BB`). [Answer] ## 60 parts My solution is quite a bit different. It converts binary to unary first, then does the mod 7. I can't quite beat Ilmari. ![enter image description here](https://i.stack.imgur.com/fVgCB.png) [Answer] I actually had no idea what I'm doing but it works and I might be the winner (if only the test-cases would be proof enough). :D ![enter image description here](https://i.stack.imgur.com/5FO48.png) EDIT: Optimized it 2 times, a bit smaller now.(Removed rubbish) ]
[Question] [ The [Flesch-Kincaid readability algorithm](https://en.wikipedia.org/wiki/Flesch-Kincaid) depends on the measures of word count and syllable count, neither of which is entirely objective, or easily automatable using a computer. For example, does "code-golf", with the hyphen, count as one word or two? Is the word "million" two or three syllables? In this task, you will need to approximate, as counting exactly will take too much time, space, and most importantly, code. Your task is to build the smallest possible program (i.e. a function) in any language that will take an English reading passage (assumed to be in complete sentences), and calculate the Flesch Reading Ease index to a tolerance of eight points (to account for variations in syllable counting and word counting). It is calculated as follows: ``` FRE = 206.835 - 1.015 * (words per sentence) - 84.6 * (syllables per word) ``` Your program must be aligned to the reference passages below, whose indices were calculated using manual counting: ``` I would not, could not, in the rain. Not in the dark, not on a train. Not in a car, not in a tree. I do not like them, Sam, you see. Not in a house, not in a box. Not with a mouse, not with a fox. I will not eat them here or there. I do not like them anywhere! ``` Index: 111.38 (64 syllables in 62 words in 8 sentences) ``` It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him. ``` Index: 65.09 (74 syllables in 55 words in 2 sentences) ``` When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. ``` Index: 3.70 (110 syllables in 71 words in 1 sentence) If you have any other passages for which you have manually counted the syllables and words and calculated the index, you may show them as verification. [Answer] ## Perl 120 bytes ``` #!perl -pa0 s@\w+|([.!?])@$s+=$#-,lc($&)=~s![aeiou]+\B|([aeiouy]$)!$y+=1-$#-/3!ger@ge} {$_=206.835-1.015*@F/$s-84.6*$y/@F ``` Sample I/O: ``` $ perl flesch-kincaid.pl < input1.dat 110.730040322581 $ perl flesch-kincaid.pl < input2.dat 65.6097727272728 $ perl flesch-kincaid.pl < input2.dat 1.71366197183096 ``` Counting of syllables is done by assuming that each vowel cluster is a single syllable, except for lone vowels at the end of a word, which are only counted two thirds of the time; a heuristic that seems to be fairly accurate. [Answer] ## K&R c -- 188 ~~196~~ ~~199~~ ~~229~~ characters With the spec changed to specify a function I can get of lot of the c overhead out of the count. Also changing to use Strigoides' syllable counting hack which is better than my formula tweak and extended to deal with overcounting of words. After I found a shorter way to do the vowel detection which was sadly based on `stdchr`, I had incentive to squeeze a few more out of the bit-twiddling abomination I've been using so that I didn't have to be boring. ``` d,a,v,s,t,w;float R(char*c){for(;*c;++c){s+=*c=='.';if(isalpha(*c)){ w+=!a++;d=(*c&30)>>1;if(*c&1&(d==7|((!(d&1))&(d<6|d>8)))){t+=!v++;} else v=0;}else v=a=0;}return 206.835-1.*w/s-82.*t/w;} ``` The logic here is a simple state machine. It counts sentences by periods only, words by strings of alphabetic characters, and syllables as strings of vowels (including y). I had to diddle the constants a little to get it to come out with the right figures, but I've borrowed Strigoides' trick of just undercounting the syllables by a fixed fraction. **Un-golfed**, with comments and some debugging tools: ``` #include <stdlib.h> #include <stdio.h> d,a,/*last character was alphabetic */ v,/*lastcharacter was a vowel */ s, /* sentences counted by periods */ t, /* syllables counted by non-consequtive vowels */ w; /* words counted by non-letters after letters */ float R/*eadability*/(char*c){ for(;*c;++c){ s+=*c=='.'; if(isalpha(*c)){ /* a letter might mark the start of a word or a vowel string */ w+=!a++; /* It is only the start of a word if the last character wasn't a letter */ /* Extract the four bits of the character that matter in determining * vowelness because a vowel might mark a syllable */ d=(*c&30)>>1; if( *c&1 & ( d==7 | ( (!(d&1)) & (d<6|d>8) ) ) ) { /* These bits 7 or even and not 6, 8 make for a vowel */ printf("Vowel: '%c' (mangled as %d [0x%x]) counts:%d\n",*c,d,d,!v); t+=!v++; } else v=0; /* Not a vowel so set the vowel flag to zero */ }else v=a=0; /* this input not alphabetic, so set both the alphabet and vowel flags to zero... */ } printf("Syllables: %3i\n",t); printf("Words: %3i (t/w) = %f\n",w,(1.0*t/w)); printf("Sentences: %3i (w/s) = %f\n",s,(1.0*w/s)); /* Constants tweaked here due to bad counting behavior ... * were: 1.015 84.6 */ return 206.835-1. *w/s-82. *t/w; } main(c){ int i=0,n=100; char*buf=malloc(n); /* Suck in the whole input at once, using a dynamic array for staorage */ while((c=getc(stdin))!=-1){ if(i==n-1){ /* Leave room for the termination */ n*=1.4; buf=realloc(buf,n); printf("Reallocated to %d\n",n); } buf[i++]=c; printf("%c %c\n",c,buf[i-1]); } /* Be sure the string is terminated */ buf[i]=0; printf("'%s'\n",buf); printf("%f\n",R/*eadability*/(buf)); } ``` **Output:** (using the scaffold from the long version, but the golfed function.) ``` $ gcc readability_golf.c readability_golf.c:1: warning: data definition has no type or storage class $ ./a.out < readability1.txt 'I would not, could not, in the rain. Not in the dark, not on a train. Not in a car, not in a tree. I do not like them, Sam, you see. Not in a house, not in a box. Not with a mouse, not with a fox. I will not eat them here or there. I do not like them anywhere! ' 104.074631 $ ./a.out < readability2.txt 'It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him. ' 63.044090 $ ./a.out < readability3.txt 'When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. ' -1.831667 ``` **Deficiencies:** * The sentence counting logic is wrong, but I get away with it because only one of the inputs has a `!` or a `?`. * The word counting logic will treat contractions as two words. * The syllable counting logic will treat those same contractions as one syllable. But probably overcounts on average (for instance `there` is counted as two and many words ending in `e` will be counted one too many), so I've applied a constant factor of 96.9% correction. * Assumes a ASCII character set. * I believe the vowel detection will admit `[` and `{`, which clearly isn't right. * Lots of reliance on K&R semantics makes this ugly, but hey, it's code golf. **Things to look at:** * I am (momentarily) ahead of both python solution here, even if I am trailing the perl. * Get a load of the horrible thing I did for detecting vowels. It makes some sense if you write the ASCII representations out in binary and read the comment in the long version. [Answer] ## Python, ~~202~~ ~~194~~ ~~188~~ ~~184~~ ~~171~~ 167 characters ``` import re def R(i):r=re.split;w=len(r(r'[ \n]',i));s=r('\\.',i);y=r('[^aeiou](?i)+',i);return 206.835-1.015*w/(len(s)-s.count('\n'))-84.6*(len(y)-y.count(' ')-2)*.98/w ``` First, get the total number of words by splitting along spaces and newlines: ``` w=len(r(r'[ \n]',i)) ``` Then, the formula. Sentence and syllable counts are only used once, so they are embedded in this expression. Sentences are simply the input split along `.`, with newlines filtered out: ``` s=r('\\.',i);s=len(s)-s.count('\n') ``` Syllables consist of the input split along non-vowels, with spaces removed. This seems to consistently slightly over-estimate the number of syllables, so we need to adjust it down (about .98 seems to do it): ``` y=r('[^aeiou](?i)+',i);y=len(y)-y.count(' ')-2; ``` **202 -> 194:** `len(x)-2` rather than `len(x[1:-1])`. Removed unnecesary brackets. Made syllable regex case-insensitive **194 -> 188:** The file was previously saved as dos rather than unix file format, causing `wc -c` to count newlines as two characters. Whoops. **188 -> 184:** Get rid of those nasty `x for x in ... if x!=...`s by storing the intermediate result and subtracting `x.count(...)` **184 -> 171:** Remove input/output, and convert to function **171 -> 167:** Insert the `len(x)-x.count(...)`s into the formula [Answer] # Python 380 characters ``` import re def t(p): q=lambda e: e!='' w=filter(q,re.split('[ ,\n\t]',p)) s=filter(q,re.split('[.?!]',p)) c=len(w)*1.0 f=c/len(s) return w,f,c def s(w): c= len(re.findall(r'([aeiouyAEIOUY]+)',w)) v='aeiouAEIOU' if len(w)>2 and w[-1]=='e'and w[-2]not in v and w[-3]in v:c-= 1 return c def f(p): w,f,c=t(p) i=0 for o in w: i+=s(o) x=i/c return 206.835-1.015*f-84.6*x ``` This is a rather long solution, but it works well enough, at least of the 3 test cases provided it does. Testing code ``` def test(): test_cases=[['I would not, could not, in the rain.\ Not in the dark, not on a train.\ Not in a car, not in a tree.\ I do not like them, Sam, you see.\ Not in a house, not in a box.\ Not with a mouse, not with a fox.\ I will not eat them here or there.\ I do not like them anywhere!', 111.38, 103.38, 119.38],\ ['It was a bright cold day in April, and the clocks were striking thirteen.\ Winston Smith, his chin nuzzled into his breast in an effort to escape\ the vile wind, slipped quickly through the glass doors of Victory Mansions,\ though not quickly enough to prevent a swirl of gritty dust from entering\ along with him.', 65.09, 57.09, 73.09],\ ["When in the Course of human events, it becomes necessary for one people to\ dissolve the political bands which have connected them with another, and to\ assume among the powers of the earth, the separate and equal station to\ which the Laws of Nature and of Nature's God entitle them, a decent respect\ to the opinions of mankind requires that they should declare the causes\ which impel them to the separation.", 3.70, -4.70, 11.70]] for case in test_cases: fre= f(case[0]) print fre, case[1], (fre>=case[2] and fre<=case[3]) if __name__=='__main__': test() ``` Result - ``` elssar@elssar-laptop:~/code$ python ./golf/readibility.py 108.910685484 111.38 True 63.5588636364 65.09 True -1.06661971831 3.7 True ``` I used the syllable counter from here - [Counting syllables](http://allenporter.tumblr.com/post/9776954743/syllables) A more readable version is available [here](http://codepad.co/s/881dd2) [Answer] # Javascript, 191 bytes ``` t=prompt(q=[]);s=((t[m="match"](/[!?.]+/g)||q)[l="length"]||1);y=(t[m](/[aeiouy]+/g)||q)[l]-(t[m](/[^aeiou][aeiou][s\s,'.?!]/g)||q)[l]*.33;w=(t.split(/\s+/g))[l];alert(204-1.015*w/s-84.5*y/w) ``` First test case gives 112.9 (correct answer is 111.4, off by 1.5 points) Second test case gives 67.4 (correct answer is 65.1, off by 2.3 points) Third test case gives 1.7 (correct answer is 3.7, off by 2.0 points) ]
[Question] [ Time to dig up your old trigonometry notes from high school! The challenge is to solve the unknown sides and angles of different triangles. And as is customary in code golf, the smallest working code wins. This is not a trivial problem; my reference implementation in python is currently down to 838 837 characters, but I'm sure you'll be able to golf solutions far smaller. Additionally, if you're stuck, this section on Wikipedia should get you going: [Triangle: Computing the sides and angles](http://en.wikipedia.org/wiki/Triangle#Computing_the_sides_and_angles). ## Input The following triangle shows the names of the sides and angles used in this challenge. Note that sides are lowercase and angles are uppercase. > > ![Triangle](https://upload.wikimedia.org/wikipedia/commons/a/a0/LabeledTriangle.svg) > > > Input is given as six space-separated values, either on `stdin` or as command-line arguments (your choice). The six values correspond to the sides `a, b, c` and the angles `A, B, C`. The unknown sides are given as question marks (`?`). Both input and output angles has to be in radians. You may assume that the input values are correct (you don't have to validate anything). You may also assume that the input triangle is non-degenerate, and that all sides and angles are nonzero. The following example input tells you that side `a` is `8`, side `b` is `12` and angle `A` is `0.5` radians: ``` 8 12 ? 0.5 ? ? ``` ## Output Output is given in the same format as the input - six space-separated numbers on `stdout`. The only exception is when it is not possible to solve the input triangle - then the string `"No solution"` must be written to `stdout`. If two solutions are possible, they are both outputted with a newline between them. Following is the output for the above input: ``` 8.0 12.0 16.0899264342 0.5 0.802561439714 1.83903121388 8.0 12.0 4.97205505116 0.5 2.33903121388 0.302561439714 ``` Output is not required to have a lot of precision, but at least a couple decimals is required. ## Rules * Input is read from `stdin` or command-line arguments * Output is written to `stdout` * If two solutions are possible with the given input, output both * If there is too little information to get one or two clear solutions, consider it a `"No solution"` case * No built-in or pre-existing code may be used (of course you can use trig functions, but not "`solveTriangle`" or such) * Shortest code wins ## Test cases **In**   `3 4 5 ? ? ?` **Out** `3.0 4.0 5.0 0.643501108793 0.927295218002 1.57079630572` --- **In**   `? 4 ? 0.64 0.92 1.57` **Out** `3.00248479301 4.0 5.02764025486 0.64 0.92 1.57` --- **In**   `? ? 5 ? 0.92 ?` **Out** `No solution` --- **In**   `? ? 5 ? 0.92 1.57` **Out** `3.03226857833 3.97800936148 5.0 0.65159265359 0.92 1.57` --- **In**   `8 12 ? 0.5 ? ?` **Out** (two solutions) ``` 8.0 12.0 16.0899264342 0.5 0.802561439714 1.83903121388 8.0 12.0 4.97205505116 0.5 2.33903121388 0.302561439714 ``` --- **In**   `8 12 ? ? .5 ?` **Out** `8.0 12.0 18.3912222133 0.325325285223 0.5 2.31626736837` ## Good luck! [Answer] ## Python, 441 chars ``` from math import* V=[map(float,raw_input().replace('?','0').split())+[0]] for i in' '*9: W=[] for a,b,c,A,B,C,R in V: if B and C:A=A or pi-B-C if a: if A:R=R or a/sin(A) else: if b and c:A=acos((b*b+c*c-a*a)/2/b/c) elif R:N=asin(a/R);W+=[(b,c,a,B,C,N,R)];A=pi-N else:a=R*sin(A) W+=[(b,c,a,B,C,A,R)] V=W V=[T for T in V if all(t>0 for t in T)] if V: for T in V:print' '.join(map(str,T[:-1])) else:print'No solution' ``` Does your typical trig to compute the answer. The current possible solutions are stored as tuples in V. Any unknown values are recorded as 0. A seventh variable R is the value `a/sin(A)==b/sin(B)==c/sin(C)`. I use a trick where the a/b/c values are cycled each iteration to avoid lots of redundant logic. The inner loop only needs to compute values of the A side or angle. [Answer] # Plain C, 565 555 530 chars C is not the best language for Code Golf, I guess, so it's just for fun. ``` float t[6],u[6],P=3.1415;x,w,j,k,D,E; #define y(V) for(V=0;V<6;++V) #define Y if(p[j]&&p[k]&& #define A(o,s,a,b,c,A,B,C) z(float*p){y(D)y(E)if(j=D%3,k=E%3,j-k){Y c)w=C=acos((a*a+b*b-c*c)/2/a/b);if(A&&B)w=C=P-A-B;Y C)w=c=sqrt(a*a+b*b-2*a*b*cos(C));if(A&&B&&a)w=b=s(B)*a/s(A);Y A&&!B&&!C)w=B=(x=A<P/2&&a<b&&p==u,1-2*x)*(asin(b*s(A)/a)-x*P);}y(j)k=w&&(p==t||x>0)&&o("%f ",a);o("\n");}main(int l,char*q[]){y(j)sscanf(*++q,"%f",t+j),u[j]=t[j];z(t);z(u);j=w||o("No solution\n");} A(printf,sin,p[j],p[k],p[3-j-k],p[j+3],p[k+3],p[6-j-k]) ``` Compiled with `cc -o trig trig.c -lm`. Reads input as command line args. [Answer] ## Perl - 412 chars As a perl one-liner, based off of Keith Randall's Python Solution: ``` use Math::Trig;@V=((map{tr/?/0/;$_}@ARGV),0);map{my@W;while(($a,$b,$c,$A,$B,$C,$R)=splice@V,0,7){$A||=pi-$B-$C if($B*$C);if($a){if($A){$R||=$a/sin$A;}else{if($b*$c){$A=acos(($b*$b+$c*$c-$a*$a)/2/$b/$c);}elsif($R){$N=asin($a/$R);push@W,$b,$c,$a,$B,$C,$N,$R;$A=pi-$N;}}}else{$a=$R*sin$A;}push@W,$b,$c,$a,$B,$C,$A,$R if($a*$b*$c>=0);}@V=@W;}(1..9);print($V[0]?join' ',map{(((6-$i++)%7)?$_:"\n")}@V:"No solution\n"); ``` Here in a more readable form: ``` use Math::Trig; @V = ( ( map { tr/?/0/; $_ } @ARGV ), 0 ); map { my @W; while ( ( $a, $b, $c, $A, $B, $C, $R ) = splice @V, 0, 7 ) { $A ||= pi- $B - $C if ( $B * $C ); if ($a) { if ($A) { $R ||= $a / sin $A; } else { if ( $b * $c ) { $A = acos( ( $b * $b + $c * $c - $a * $a ) / 2 / $b / $c ); } elsif ($R) { $N = asin( $a / $R ); push @W, $b, $c, $a, $B, $C, $N, $R; $A = pi- $N; } } } else { $a = $R * sin $A; } push @W, $b, $c, $a, $B, $C, $A, $R if ( $a * $b * $c >= 0 ); } @V = @W; } ( 1 .. 9 ); print( $V[0] ? join ' ', map { ( ( ( 6 - $i++ ) % 7 ) ? $_ : "\n" ) } @V : "No solution\n" ); ``` ]
[Question] [ A [binary max heap](https://en.wikipedia.org/wiki/Heap_(data_structure)) is a rooted tree with integer labeled nodes such that: * No node has more than 2 children. * The label of every node is greater than all of its children. We say a sequence of integers is **[heapable](https://arxiv.org/pdf/1007.2365.pdf)** if there exists a binary max heap, whose labels are the sequence's elements, such that if \$p\$ is the parent of \$n\$, then the sequence has \$p\$ before \$n\$. Alternatively, a sequence is heapable if there is a way to initialize a binary max heap whose root is its first element, and then insert the remaining elements one at a time in the order they appear in the sequence, while maintaining the binary max heap property. For example: * The sequence `[100, 19, 17, 36, 25, 3, 2, 1, 7]` is heapable, with [this heap](https://en.wikipedia.org/wiki/File:Max-Heap-new.svg) showing why. In the heap, `19` is the parent of `3`, and `19` comes in the sequence before `3` does. This is true for any parent and child. * The sequence `[100, 1, 2, 3]` is not heapable. If the sequence was heapable, each parent must be both larger, and come before, any of its children. Thus, the only possible parent of `1`, `2`, and `3` is `100`. But this is impossible in a binary heap, as each parent has at most two children. Given a non-empty array of distinct positive integers, determine if it is heapable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code as measured in bytes. ## Test cases ``` [4, 1, 3, 2] -> True [10, 4, 8, 6, 2] -> True [100, 19, 17, 36, 25, 3, 2, 1, 7] -> True [6, 2, 5, 1, 3, 4] -> True [100, 1, 2, 3] -> False [10, 2, 6, 4, 8] -> False [10, 8, 4, 1, 5, 7, 3, 2, 9, 6] -> False ``` Notes: * The typical [array representation](https://codegolf.stackexchange.com/questions/85079/is-it-a-max-heap) of a heap is a heapable sequence, but not all heapable sequences are in this form (as the above examples show). * Most sources define heapable sequences with a min heap, rather than a max heap. It's not a big difference, but I imagine programmers are more familiar with max heaps than min heaps. * This is a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") standard rules apply. [Answer] # [Haskell](https://www.haskell.org/), 100 bytes ``` x!(q@(n,y):z)=[(2,x):(n-1,y):z|y>x,n>0]++map(q:)(x!z) x!_=[] g(x:y)=[]<foldl((.(!)).(>>=))[[(2,x)]]y ``` [Try it online!](https://tio.run/##JczRCsIgFIDhe59CoYtzmA1dd5LSe4iEsFoj57bq4jh6d4u6/eH7b/F5v6RUKwlYT5BlQbOh9dBJQgN5r3/lXRzJ7FRomikusBoEEhsyEmfrAxuATPmqcLzOqU8ALQjEFpyziP4/C6HUKY7Z9jPjfHmM@cV3fOBeKyW17OQh1A8 "Haskell – Try It Online") ## Explanation We look for a heap using breadth first search. We keep track of the nodes and the number of available children in a list. We discard any nodes that already have two children. They are just not necessary any more since we only care about *if* there is a solution, not what it is. At each step we attempt to insert a value at every location allowing it if we find a node with available children and a value greater than the value we are inserting. If we manage to find a way to insert every value then we return `True` otherwise `False`. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 35 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⟨⟩:1;×⊑⍒𝕩?0;∨´∧´¨𝕊¨¨⊔⟜v¨⥊↕2¨v←1↓𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KfqOKfqToxO8OX4oqR4o2S8J2VqT8wO+KIqMK04oinwrTCqPCdlYrCqMKo4oqU4p+cdsKo4qWK4oaVMsKoduKGkDHihpPwnZWpfQoKRsKo4p+oCjTigL8x4oC/M+KAvzIKMTDigL804oC/OOKAvzbigL8yCjEwMOKAvzE54oC/MTfigL8zNuKAvzI14oC/M+KAvzLigL8x4oC/NwoKMTAw4oC/MeKAvzLigL8zCjEw4oC/MuKAvzbigL804oC/OAoxMOKAvzjigL804oC/MeKAvzXigL834oC/M+KAvzLigL854oC/Ngrin6k=) **Commented** ``` { ⟨⟩:1 ; # The empty sequence is heapable ×⊑⍒𝕩?0 ; # Not heapable if the maximum is not at index 0 v←1↓𝕩 # Now consider the sequence without the first value ∨´ # It is heapable if any ... ⊔⟜v¨⥊↕2¨v # ... way of splitting it ∧´¨𝕊¨¨ # ... results in two heapable subsequences } ``` [Answer] # JavaScript (ES7), 81 bytes Returns \$0\$ or \$1\$. ``` f=([v,...a],t=[2**32-3])=>!v|t.some((x,i)=>x/4>v&x%4<2&&f(a,b=[...t,v*4],b[i]++)) ``` [Try it online!](https://tio.run/##lZA9T8MwEIZ3foUZSOz06pCPJkUiHRETE5u5wSkOBIW4akyUgf8eXFeVWpQgYekW3z2@18@H7GW33dc7s2z1qxrHqqCiB865RDCFiIMgiZcJsmJz3X8b3ulPRekAtb0YwnTTe8NNeh97XkUllIWwoIE@SBFKUeNiwdi41W2nG8Ub/UZ98ajkTpaNQp9dnXcqKlIgEZAESIxk6jBGwpA877/UbzK6BWLpNZBskv6LtGh0Zyu3qw/06hjBZclxnszc0OqUOcX5nReo/9KKJ23I@7yIYyj3foKzIh5k002aiJ2Ggw/8L7p2XOT@lZ9EWDsZXqDjDw "JavaScript (Node.js) – Try It Online") ### How? We don't really need to keep track of the exact structure of the binary tree. In particular, we don't need to 'remember' the parent of a given node as long as we are sure that it was a valid connection when we added it. We store the tree as a list of integers where the 2 least significant bits represent the number of child nodes and the higher bits represent the value of the node. For instance a \$6\$ with 1 child node is stored as \$25\$: ``` 11001 \_/\/ | \_ 1 child node +---- value = 6 ``` We do a recursive search, looking for all valid parents for a given value. For each valid connection, we update the parent and simply add the child at the end of the list. The list is initialized with a pseudo node whose value is \$2^{32}-3\$ so that the root node can be attached to it: ``` 11111111111111111111111111111101 \____________________________/\/ | \_ 1 child +------------------ max. possible value with this encoding scheme ``` [Answer] # Python3, 170 bytes: ``` def f(v): q=[({v.pop(0):[]},v)] while q: r,V=q.pop(0) if[]==V:return 1 for i in r: if i>V[0] and len(r[i])<2:q+=[({**r,i:r[i]+[V[0]],V[0]:[]},V[1:])] return 0 ``` [Try it online!](https://tio.run/##bY7BioMwFEX3fsVbJu2jGG3VCbWf4SZkMVBDAyXG4FiGod9uX9J2YHAWBrz35J747@kyuLLxYVnOvQHDZi4zGFvFfuadHzzLuVT6jjPXGdwu9trDSAAE7NrxBdCvNUq3bSdDP30FB4IiMwSwYB2EyBMB9tSpXMOnO8O1dywoq/mxkOM22jabgFbGbKsipjGeyd0pIXX0v9bzxQfrJmaY2iMIhBKh0Jxnv7HIEahqEKp1RZ34oK@mi7E@PAfSUv2HrVJ8eDv2/wwlolzJi2SOT1hVTcpF2q3fanpPReTyAA) ]
[Question] [ If we write a sequence of numbers as the coefficients of a power series, then that power series is called the (ordinary) **generating function** (or G.f.) of that sequence. That is, if for some function `F(x)` and series of integers `a(n)` we have: ``` a(0) + a(1)x + a(2)x^2 + a(3)x^3 + a(4)x^4 + ... = F(x) ``` Then `F(x)` is the generating function of `a`. For example, the [geometric series](https://en.wikipedia.org/wiki/Geometric_series) tells us that: ``` 1 + x + x^2 + x^3 + x^4 + ... = 1/(1-x) ``` So the generating function of `1, 1, 1, ...` is `1/(1-x)`. If we differentiate both sides of the equation above and multiply by `x` we get the following equality: ``` x + 2x^2 + 3x^3 + 4x^4 + ... = x/(1-x)^2 ``` So the generating function of `1, 2, 3, ...` is `x/(1-x)^2`. Generating functions are a very powerful tool, and you can do many useful things with them. A short introduction can be found [here](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2005/readings/ln11.pdf), but for a really thorough explanation there is the amazing book generatingfunctionology. --- In this challenge you will take [a rational function](https://en.wikipedia.org/wiki/Rational_function) (the quotient of two polynomials with integer coefficients) as input as two arrays of integer coefficients, first the numerator then the denominator. For example the function `f(x) = x / (1 - x - x^2)` will be encoded as `[0, 1], [1, -1, -1]` in the input. Given this input your program must infinitely print the coefficients of the power series that equals the generating function, one per line, starting at the coefficient of `x`, then `x^2`, etc. --- Examples: ``` [1], [1, -1] -> 1, 1, 1, 1, 1, 1, 1, ... [1], [2, -2] -> 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ... [0, 1], [1, -2, 1] -> 1, 2, 3, 4, 5, 6, 7, 8, ... [0, 1], [1, -1, -1] -> 1, 1, 2, 3, 5, 8, 13, 21, 34, ... [1], [1, -2] -> 1, 2, 4, 8, 16, 32, 64, 128, ... [0, 1, 1], [1, -3, 3, -1] -> 1, 4, 9, 16, 25, 36, ... ``` [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` z=0:z (a:b)%y@(c:d)=a/c:zipWith(-)(b++z)(map(a/c*)d++z)%y _%_=z ``` [Try it online!](https://tio.run/##FYk5CsMwFAV7n@IVEXzFViIT3AgEuUDqFMaI7wUsvGASNdblFQWmmGFm/i7TuqYUrTaxIDa9FOeTBjNKy/fBRH@8fZhJSerLMkra@KA8rnL8pzgLJ5yNaWO/wyLfl8Px8XvADYGXCY3GBa2uUGc6CLRZ1KNCRtVd@gE "Haskell – Try It Online") Defines an operator `%` returning an infinite lazy list of coefficients. The list is zero-indexed, so the constant coefficient is included. [Answer] # Mathematica, 64 ~~83~~ ~~90~~ bytes ``` Do[Echo@Limit[D[#/#2/i!&@@Fold[x#+#2&]/@#,{x,i}],x->0],{i,∞}‌​]& ``` Thanks to @ngenisis and @Jenny\_mathy ! Take input as two lists. Need `Alt+.` to terminate the execution to see the result. Frontend may crash due to rapid output. 83 bytes version (@Jenny\_mathy): ``` i=1;v=Tr[#*x^Range@Length@#]&;While[1<2,Echo@Limit[D[v@#/v@#2/i!,{x,i}],x->0];i++]& ``` [Answer] ## CJam (22 bytes) ``` {\{(W$(@\/_pW*f*.+1}g} ``` [Online demo](https://tio.run/##S85KzP0fbaBgqGAYqxBtqKBrrGCsoGsY@786plojXEXDIUY/viBcK01LT9uwNr32f91/AA). Note that as many of the existing answers, this includes the 0th coefficient in the output. ### Dissection ``` { e# Define a block which takes numerator N and denominator D as arguments \ e# Flip to put D at the bottom, since that won't change { e# Infinite loop: ( e# Pop the first element of (the modified) N W$( e# Copy D and pop its first element e# Stack: D N[1:] N[0] D[1:] D[0] @\/ e# Bring N[0] to top, flip, divide e# Stack: D N[1:] D[1:] N[0]/D[0] _p e# Print a copy W*f*.+ e# Multiply by -1, multiply all, pointwise add e# Stack: D N[1:]-(N[0]/D[0])*D[1:] 1}g } ``` [Answer] # Mathematica, ~~86~~ 79 bytes ``` f=x^Range@Length@#.#&;For[n=1,8>3,Print@SeriesCoefficient[f@#/f@#2,{x,0,n++}]]& ``` Takes input as two separate lists (numerator coefficients, denominator coefficients). If the input can be taken directly as a fraction of polynomials rather than as lists of coefficients, this can be shortened significantly. It seems that `Do` can work with infinite bounds in v11. I can't test this locally, but, if this is the case, then this solution can be shortened to **75 bytes**: ``` f=x^Range@Length@#.#&;Do[Print@SeriesCoefficient[f@#/f@#2,{x,0,n}],{n,∞}]& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` JE# KchQhJ=t-M.t,Q*LKJ0 ``` [Try it online!](https://tio.run/##K6gsyfj/38tVmcs7OSMww8u2RNdXr0QnUMvH28vg//9oAx0FQyCK5YoGUrrGOgpApGsYCwA "Pyth – Try It Online") ### How it works ``` Q = eval(input()) JE J = eval(input()) # infinite loop: chQhJ Q[0]/J[0] K assign that to K (and print it, because of the preceding newline) *LKJ K times every element of J ,Q [Q, that] .t 0 transpose, padding with 0s -M subtract each pair t remove the first element = assign that back to Q ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 66 bytes ``` p->q->for(i=0,oo,print(Pol(Polrev(p)/(Polrev(q)+O(x*x^i)))\x^i%x)) ``` [Try it online!](https://tio.run/##NYc7CoAwEAWvkkbY1Swq1skVtPcDFkYCYtYgktvHtRDmMfN4jZ52zk4ZlZnsRdaFCN40OgTN0Z83DOH4FrcHGOs/L6x6SGVaPCJOoiIhZgdjo1UrzAijmDqtBJKfXw "Pari/GP – Try It Online") ]
[Question] [ A [Graceful Graph](http://mathworld.wolfram.com/GracefulGraph.html) is a type of [Simple Graph](http://mathworld.wolfram.com/SimpleGraph.html). Graceful graphs are special because there is a way to label all their nodes with positive integers so that when the edges are also labeled with the differences of the nodes they connect, no two edges have the same label and every label up to the number of edges is used. ## Worked Out Example Here is a Simple graph that we suspect is a Graceful graph [![Simple Graph](https://i.stack.imgur.com/Fg3a4.png)](https://i.stack.imgur.com/Fg3a4.png) Let us try the following labeling: [![Labeled](https://i.stack.imgur.com/JPfPb.png)](https://i.stack.imgur.com/JPfPb.png) Note we are permitted to skip integers in our node labeling. Now we label every edge with the positive difference between the nodes it connects. For increased visibility I have labeled these in red. [![Doubly labeled](https://i.stack.imgur.com/SzA5A.png)](https://i.stack.imgur.com/SzA5A.png) Each edge has a unique number and no number between between 1 and 7 (the number of edges we have) is left out. Thus our graph is graceful. # Task Given a graph, via any reasonable method of input, output a truthy value if it is graceful and a falsy value otherwise. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the objective is to minimize your byte count. ## Test Cases Here graphs are represented as an array of edges: ``` 3 nodes: [(0,1),(0,2),(1,2)] True Labeling: Node 0 -> 0 Node 1 -> 2 Node 2 -> 3 ``` --- ``` 5 nodes: [(0,1),(0,4),(1,2),(2,3),(3,4)] False ``` --- ``` 5 nodes: [(0,1),(1,2),(2,3),(3,4)] True Labeling: Node 0 -> 0 Node 1 -> 1 Node 2 -> 3 Node 3 -> 6 Node 4 -> 10 ``` --- ``` 9 nodes [(0,1),(1,2),(1,7),(1,8),(2,3),(2,6),(3,4),(4,5)] True Labeling: Node 0 -> 0 Node 1 -> 1 Node 2 -> 3 Node 3 -> 6 Node 4 -> 10 Node 5 -> 15 Node 6 -> 11 Node 7 -> 7 Node 8 -> 8 ``` --- ``` 5 nodes [(0,1),(0,2),(1,2),(1,3),(1,4),(3,4)] False ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` FSŒ!ị@€ḅ-AċJ ``` Takes an array of edges as 1-indexed node pairs. [Try it online!](https://tio.run/nexus/jelly#@@8WfHSS4sPd3Q6PmtY83NGq63ik2@v////RGoY6Rpo6GkY6xpqxAA "Jelly – TIO Nexus") (Horrendously inefficient. Don't bother with the actual test cases.) ### How it works ``` FSŒ!ị@€ḅ-AċJ Main link. Argument: A (array of pairs) FS Flatten and sum, yielding s. This is an upper bound for the labels a graceful labeling (if one exists) would require. Œ! Take all permutations of [1, ..., s]. € For each permutation P: ị@ Replace each integer in A with the element of P at that index. ḅ- Convert all pairs from base -1 to integer, mapping (a,b) to b-a. A Take absolute values. J Yield the indices of A, i.e., [1, ..., len(A)]. ċ Count the occurrences of [1, ..., len(A)] in the result to the left. ``` [Answer] ## Mathematica, 121 116 bytes *Edit: Saved 5 bytes thanks to JungHwan Min and Martin Ender* ``` Cases[Range[1+Tr[n=Range@Length[e=EdgeList@#]]]~Tuples~VertexCount@#,w_/;Sort[Abs[#-#2]&@@w[[List@@#]]&/@e]==n]!={}& ``` ## Explanation [![enter image description here](https://i.stack.imgur.com/lg31d.png)](https://i.stack.imgur.com/lg31d.png) Pure function which takes a Mathematica `Graph` object with vertices `{1, 2, ..., k}` for some nonnegative integer `k`. In the worst case, we will only need vertex labels ranging from `1` to `1 + (1 + 2 + ... EdgeCount@#)`. Since it saves us some bytes later, we will let `e` be the list of edges and `n` be the list `{1, 2, ..., EdgeCount@#}`, so the vertex weights will be drawn from `Range[1+Tr[n=Range@Length[e=EdgeList@#]]]`. We generate a list of all `Tuples` of length `VertexCount@#`, then we choose the `Cases` which give graceful labelings and check to see that the result is `Unequal` to the empty list `{}`. Gracefulness of the list of vertex weights `w` is checked by `Map`ping the function `Abs[#-#2]&@@w[[List@@#]]&` over the list of edges `e`, `Sort`ing the result, and checking whether the result is `Equal` to `n`. Here is a breakdown of that function: ``` List@@# Replace the Head of the edge with List; i.e., UndirectedEdge[a,b] becomes {a,b}. w[[ ]]& Select the corresponding vertex weights from the list w. @@ Replace the Head of that expression (List) with the function Abs[#-#2]& which returns the absolute difference between its first two arguments. This effectively passes the vertex weights into the absolute difference function. ``` [Answer] # Python3, 449 bytes ``` R=range def f(g): q=[(v:={**{i:-1 for j in g for i in j},0:0},[],{*v}-{0})] while q: m,e,n=q.pop(0) if not n: if all(i in e for i in R(1,len(g)+1)):return m continue for i in n: if(k:=[N for j in g if i in j and m[(N:=j[j[1]!=i])]!=-1]): y=[m[N]for N in k] for o in{*R(min(y)+1,max(y)+len(g)+1)}-{*m.values()}: E=[abs(Y-o)for Y in y] if all(U not in e and U<=len(g)for U in E):q+=[({**m,i:o},e+E,n-{i})] break ``` [Try it online!](https://tio.run/##jZE9b8IwEIZ3fsV1s8MFJUBbZNUjKwMSQ2VlSIsDhsQJIdCiKL@dnk1LkdpKXV6d7@Pxe3Z1atalHU2q@nyeyzq1K91b6gwytuKiBzup2FHINghaI8IYsrKGDRgLKx8aF246jETUoUqwDY5d2EYdT3rwtja5hh1BoECNVu4GVVmxiFPCZGDLBqwrukOa58yz9Dd2zmLMtSUf/ZhzUevmUFso3MRraRtjD5ria/sXi22FVLNbo8S/@ITULqFQbCbkRm1UnNxJk3DSME64H4eTVIWaJW565ma2iU@7c0nnNpizwlh2Ik9YpO8uuHqkzYNicEzzg94z3l2AMJUqfdmz57DkjvLsqKcL9WvzhX8Mv71zuHiSF6brX7j8lItdn36CvqFAI8oOdX@KNmwNvTR41kut0@25qo1tWMYUizDmSDokjUkTzns/q@PPKrIhjkhHlPmt8/89MT56nVz7h/jwOYVsjPd/OBneEEZex993nT8A) ]
[Question] [ We've all heard of the ol' Fizz Buzz problem, but what happens when you try to apply it with more factors? Fizz Buzz Crackle Pop! # The Challenge Write a **full program** that takes an *integer* input **n**, then n tuples containing an integer and a string, then another integer (>1) k, as such: ``` n int1 str1 int2 str2 (...) intn strn k ``` You can take this line from either command line or STDIN. Then, for all integers 1 to k, if it is divisible by any of *int1*, *int2*...*intn*, output all corresponding *str*s in the input order, followed by a newline. If it isn't, then just output the integer, followed by a newline. For example, with input ``` 3 2 Fizz 3 Buzz 5 Crackle 10 ``` we get ``` 1 Fizz Buzz Fizz Crackle FizzBuzz 7 Fizz Buzz FizzCrackle ``` But with input (notice the order change) ``` 3 3 Buzz 2 Fizz 5 Crackle 10 ``` we get ``` 1 Fizz Buzz Fizz Crackle BuzzFizz 7 Fizz Buzz FizzCrackle ``` Optional trailing newline is acceptable. Shortest code in bytes wins. # Edits: Obviously I've missed out a lot, sorry. * Inputs from console and STDIN, anything else gets +5 bytes (:c) anywhere * Full programs please. * Assume non-empty strings for strs * No guarantees for uniqueness of ints Sample C++ program (limited at 20 because I'm lazy): ``` #include <iostream> #include <string> using namespace std; int main() { string names[20]; int mods[20], n, max; cin >> max >> n; for (int i=0; i<n; i++) { cin >> mods[i] >> names[i]; } for (int i=1; i<=max; i++) { bool found = false; for (int j=0; j<n; j++) { if (i % mods[j] == 0) { found = true; cout << names[j]; } } if (!found) cout << i; cout << endl; } return 0; } ``` [Answer] ## JavaScript (ES6), 90 bytes Generates a leading newline. ``` f=(a,i=a.pop())=>i?f(a,i-1)+` `+(a.map((_,j)=>++j>a[0]|i%a[j*2-1]?'':a[j*2]).join``||i):'' ``` ### Test ``` f=(a,i=a.pop())=>i?f(a,i-1)+` `+(a.map((_,j)=>++j>a[0]|i%a[j*2-1]?'':a[j*2]).join``||i):'' console.log(f([3, 2, 'Fizz', 3, 'Buzz', 5, 'Crackle', 10])) console.log(f([3, 3, 'Buzz', 2, 'Fizz', 5, 'Crackle', 10])) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes ``` #¦¤U¨2ôøVXLvY`sysÖÏJDg1‹iy}, ``` [Try it online!](https://tio.run/nexus/05ab1e#@698aNmhJaGHVhgd3nJ4R1iET1lkQnFl8eFph/u9XNINHzXszKys1fn/31jBWMGptKpKwUjBLRNImSo4FyUmZ@ekKhgaAAA "05AB1E – TIO Nexus") **Or with a different input format:** # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` Lv²y³ÖÏJDg1‹iy}, ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9TdmhT5aHNh6cd7vdySTd81LAzs7JW5/9/QwOuaHWn0qoqdR11t0ww5VyUmJydk6oeyxVtrGOkYxoLAA "05AB1E – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes ``` lambda b:[''.join(''if x%b[1+i*2]else b[2+i*2]for i in range(b[0]))or`x`for x in range(1,b[-1]+1)] ``` [Try it online!](https://tio.run/nexus/python2#RcnRCsIgFIDhVzk3cbRZTKOboJuCXsKEaWmcWm7YBmMvb7ab7v6PPxyvubVvd7fgDhpx@@woMkQKMK2clhWtlfHtx4PTakHoEhBQhGTjwzOna8N5l5qp@Z3pf6RweiNNJbnJfaI4sMAo9uPAOOdZ7wQoAXiheUYBRXgal9yXPCd7e7W@SNbmCw "Python 2 – TIO Nexus") [Answer] # C++, 194 bytes ``` #include <iostream> #define p std::cout<< int main(int c,char**a){c=2*atoi(a[1])+2;int x,f,i,n=atoi(a[c]);for(x=1;x<=n;x++){f=0;for(i=2;i<c;i+=2)if(x%atoi(a[i])<1)f=1,p a[i+1];if(!f)p x;p'\n';}} ``` Ungolfed: ``` #include <iostream> int main(int c, char **a) { c = 2 * atoi(a[1]) + 2; int x, f, i, n = atoi(a[c]); for (x = 1; x <= n; x++) { f = 0; for (i = 2; i < c; i += 2) if (x % atoi(a[i]) < 1) f = 1, std::cout << a[i+1]; if (!f) std::cout << x; std::cout << '\n'; } } ``` [Answer] # PHP, 99 bytes Based on [primo´s FizzBuzz answer](https://codegolf.stackexchange.com/a/58674/55735): `õ` is chr(245), a bit inverted newline. ``` for(;$i++<($a=$argv)[$z=$argc-1];){for($k=$s="";$z>$k+=2;)$s.=[$a[$k+1]][$i%$a[$k]];echo$s?:$i,~õ;} ``` ignores the first argument; run with `-nr`. [Answer] # JavaScript (ES6), ~~105~~ 97 bytes ``` g=(m,k,i=1)=>i<-~k?([...m.keys()].filter(j=>i%j<1).map(j=>m.get(j)).join``||i)+"\n"+g(m,k,i+1):"" ``` Takes in a map of pairs **m** (integer, string) and an integer **k**. Comes with a trailing newline. Here's a non-recursive version (105 bytes), but doesn't yield a trailing newline. ``` m=>k=>[...Array(k).keys()].map(x=>[...m.keys()].filter(j=>-~x%j<1).map(j=>m.get(j)).join``||x+1).join`\n` ``` [Try it online!](https://tio.run/nexus/javascript-node#dczNCoJAGIXhfVchA8F8OH00RZvSgoJ2XcEkKDIN4/wYakQi3boZtRFq@XI4T69i6phhOuYQb3U0e5odFYjo0MhHTSHBi7aNrGgxzNMi4oAuu77LoZINLQCwKLVP067TEJKzJ6H6kCGHNSF9Xvq6tBJtqaiiXt6D0wAIsWABOeq2JQkLxHKI/e0bqyEOVZYbK0mSAAv4HGAz@QeNviP1N9S/AA) [Answer] # Java, 331 bytes Because Java. ``` import java.util.*;class A{A(int c,String x){i=c;v=x;}int i;String v;void x(String[]x){ArrayList<A>l=new ArrayList();int n=0;for(;++n<x.length-1;)l.add(new A(Integer.valueOf(x[n++]),x[n]));n=Integer.valueOf(x[n]);for(int i=1;i++<n;){String o="";boolean y=1>0;for(A a:l)if(i%a.i==0){y=1<0;o+=a.v;}if(y)o+=i;System.out.println(o);}}} ``` This is the full class required for this. However, in order to run it, you must call the method `x` on an existing instance of `A`. For the sake of testing, I have provided a command-line runnable class below, which is partially ungolfed. ``` import java.util.*; class A{ A(int c,String x){i=c;v=x;} int i; String v; void x(String[]x){ ArrayList<A>l=new ArrayList(); int n=0; for(;++n<x.length-1;) l.add(new A(Integer.valueOf(x[n++]),x[n])); n=Integer.valueOf(x[n]); for(int i=1;i++<n;){ String o=""; boolean y=1>0; for(A a:l)if(i%a.i==0){y=1<0;o+=a.v;} if(y)o+=i; System.out.println(o); } } public static void main(String[] args) { new A(0,"").x(args); } } ``` [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 85 bytes ``` args rev...2*nsgroup rev 2 chunk@s~>{!s[1#]map s[0#n|]map keep''join:[n]\¬if out}map ``` [Try it online!](https://tio.run/nexus/stacked#@59YlF6sUJRapqenZ6SVV5xelF9aAOIrGCkkZ5TmZTsU19lVKxZHGyrH5iYWKBRHGyjn1YCZ2ampBerqWfmZeVbRebExh9Zkpinkl5bUAuX@//9v/N/ov5tnVBSQ4RQKpEz/Owc5Onv7uP43NAAA "stacked – TIO Nexus") Alternatively, 86 bytes: ``` args behead...@k sgroup 2 chunk@s k~>{!s[1#]map s[0#n|]map keep''join:[n]\¬if out}map ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 121 bytes ``` ?dstsw?[rdlt:Y:Rlt1-dst0<q]dsqx?sb1sm[ln;Y;RnlP1+sP]ss[lmn]sF[1sn0sP[lnd;Ylmr%0=s1+dsnlw!<g]dsgxlP0=Flm1+dsm10Plb!<i]dsix ``` Takes input on 3 separate lines, the first line containing the integer `n`, the second housing the `int str` tuples with the strings enclosed in square brackets (`[]`), and the third line consists of the integer `k`. For example, `3 2 Fizz 3 Buzz 5 Crackle 10` could be input as: ``` 3 3 [Buzz] 2 [Fizz] 5 [Crackle] 10 ``` [Try it online!](https://tio.run/nexus/dc#FYw9C4MwFAB3f0UcOkkhr9LFDwItOAe38MhQmyLSl4B5FsU/b@N23MEdyvHCq8LoaKlM1dMC16RkM1vH86Z4APZIoTZ1H0hDwdoyI/lguUPgIFmn7GpDPl5ky1A4DrTmzZgG40Zath3503qQmoa8mVKYtuMos1Lg47fvVtwEdtMJd4HP@Hp/6WMzkH8 "dc – TIO Nexus") ### Or taking input in a different order: # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 118 bytes ``` ?dstsw[dlt:Y:Rlt1-dst0<q]dsqxsb1sm[ln;Y;RnlP1+sP]ss[lmn]sF[1sn0sP[lnd;Ylmr%0=s1+dsnlw!<g]dsgxlP0=Flm1+dsm10Plb!<i]dsix ``` This takes input in a different order, but on a single line in the format ``` k [str1] int1 [str2] int2 (...) [strn] intn n ``` For example, `3 2 Fizz 3 Buzz 5 Crackle 10` would be input as: ``` 10 [Buzz] 3 [Fizz] 2 [Crackle] 5 3 ``` [Try it online!](https://tio.run/nexus/dc#Fcs9C4MwFIXhvxKHTlLIbeniB4UWnINbuGSoTRHpTUCPRfHP27gdnpez3z1mLOxlLmzRykznBLoance4oiMElljaso1iKIdxAEuIDg0TooZJ2ZdWwnTSNSj3iLJkVZ/@/SpG142EQwNpI11WDSkM676TVvz4bZtTV8XNcIyL4uf0en/l49Qt8R8 "dc – TIO Nexus") ]
[Question] [ Find the nearest Date to a TargetDate for a given Day of Week. For example, given a date of `20161219` and a day of week of `Friday (6)`, the answer is `20161216`. Another example, given a date of `20161219` and a day of week of `Wednesday (4)`, the answer is `20161221`. A final example, given a date of `20161219` and a day of week of `Monday (2)`, the answer is `20161219`. **Rules:** * The Date format for the input and output must match. In the examples, I used `yyyymmdd`, but you may use any format as long as the year (at least two digits), month, and day of month are "human readable". * Day of Week is input as an integer. In my example, Sunday is the first day of the week, therefore it is day of week number `1`. You can have any Day of Week numbering, as long as you note it when it differs from the example. * Years 1970 through 2030 must be accommodated. * Common language date tools and libraries are allowed, but street cred is given to those that choose not to use them. * Least number of *bytes* wins. [Answer] # [Perl 6](https://perl6.org), 83 bytes ``` ->$_,\w{~(Date.new(|m/(....)(..)(..)/)-3...*.day-of-week%7+1==w)[*-1]~~{S:g/"-"//}} ``` [Try it](https://tio.run/nexus/perl6#ZVFNT4NAEL3zK0aCAhUWQUNTCZ68ePGiNzVNA4OS8tGyS2mD8NfrgNBi3GSzM2/ezLyZLTnCzmWBJ5VkvSIXniSlB7gKkpyTZ4YrgeAfzQdlabxXdas9EsAyrLTv1NIYHV0brqWbt@TPWLg6mHlkVojry/m17fuV/jYz7Y@2rV/uPy3ZlC2raY5RXkASZ8g1HWoJoMwS5ByUJdSwKQWoqgcZ7gU0EkVJlKZ0agxlUt9QcL/BQGCogw@syouQex09jmDKY89likUcwEXbwlMmgHpP4z1uMzbvlQDwdbyB7bau4iQhETssQGCRxlm3jioWX7ACSoc8gj6dXnlaT268vk6nv7PGEZQCeZkI0vpnwf8HOw0xzsdCjGhZ4SAw5mMt48whc9k1A0zoN3@J3Sbp71RQjSGhl9McnRvbtR17AS4MpiudsLsBc@wz5oy8hXQGJ/H5Dw "Perl 6 – TIO Nexus") ## Expanded ``` -> # pointy block lambda $_, \w { ~( # turn into a Str Date.new( |m/(....)(..)(..)/ ) - 3 # three days earlier ... # generate a sequence *.day-of-week % 7 + 1 == w # stop when the right day is found )[*-1] # the last one ~~ # apply the following block { S:g/"-"// # remove 「-」 } } ``` [Answer] # Bash + coreutils, 50 ``` date -d$1+$[($2-`date -d$1 +%u`+9)%7-3]day +%Y%m%d ``` [Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU1AyMjA0MzQytFQwU0LimCBzjJSsFVLyuYpTSxR0dRVUYNr/pySWpCropqgYaqtEa6gY6SbABRS0VUsTtC01Vc11jWNTEiuB/EjVXNWU/yn5ean/AQ). * `date -d$1 +%u` gives the day of week (1..7); 1 is Monday * This is subtracted from the input day of week to give a difference of day indexes. We want to add a factor between in the range [-3, 3] to the input date to get the closest date, so we add a magic factor 9, take the modulo 7, then subtract 3. The magic factor 9 is `3 + 7 - 1`. The 3 adjusts the input range for range [-3, 3], and is subtracted again after the modulo. The 7 is required because bash modulo is the same as CPU modulo and can give -ve results - adding 7 adjusts into the right range. The -1 is because in the input, 1 is Sunday, but with the %u output, 1 is Monday. * The outer `date` then parses `<input date> + <magic factor>days` and presents it in the YYYYMMDD format. [Answer] ## JavaScript (ES6), 93 bytes ``` (s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().slice(0,10) ``` Uses `%Y-%m-%d` date format. If `%a %b %d %Y` is an acceptable date format, then for 82 bytes: ``` (s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toDateString() ``` I could save a further 2 bytes by requiring Sunday = 10 to Saturday = 16, but that's a silly day of week mapping. Previous ~~142~~ 141 bytes (thanks to @Guedes) version that used the specific YYYYMMDD date format, with its explanation: ``` (s,n,d=new Date(s.replace(/(?=..(..)?$)/g,'-')))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().replace(/-(..)-(..).*/,'$1$2') ``` This feels far too long. Explanation: First, inserts `-`s into the date to get it into ISO format which `new Date` can then parse. Then, compares the desired day with the actual day to get a value between `-3` and `3` for the actual offset. The magic `9` comes from `7` (because `%` is CPU modulo, not true modulo) plus `3` (for the `-3` offset) minus `1` (because `n` is 1-indexed and `getDay` is 0-indexed). The date is then converted back into ISO format and the unwanted characters removed. [Answer] # [Perl 6](http://perl6.org/), 46 bytes ``` {~first *.day-of-week==$^b,Date.new($^a)-3..*} ``` A lambda that accepts two arguments: A date string in `yyyy-mm-dd` format, and a weekday number between `1`=Monday and `7`=Sunday. Explanation: ``` Date.new($^a) # Construct Date object from first argument. -3 # Subtract 3 days. ..* # Construct a Range from that, to infinity. first , # Iterate the range, and return first date... *.day-of-week==$^b # whose weekday number equals the second arg. ``` --- Using the date and weekday format used in the examples, it would be 88 bytes: ``` {S:g/\-//with ~first *.day-of-week==($^b-2)%7+1,Date.new(|($^a~~/(....)(..)(..)/))-3..*} ``` [Answer] # Python, ~~150~~ 149 bytes ``` from datetime import* lambda s,n,t='%Y%m%d':[d for d in[datetime.strptime(s,t)+timedelta(o-3)for o in range(7)]if(n-2)%7==d.weekday()][0].strftime(t) ``` Oouuf, 149. **[repl.it](https://repl.it/Ettx/1)** Unnamed function that takes a string `s`, the date as specified (using format string `t='%Y%m%d'` for both input and output) and a number in [1,7], `n`. Inspects the seven days from three days prior to three days after that given for the day of the week requested. The week in `datetime` starts on Monday and is zero based, so the test is `(n-2)%7==d.weekday()`. [Answer] # SAS Macro Language, 110 Bytes ``` %macro s(d,a);%put %sysfunc(putn(%sysfunc(intnx(week.&a.,%eval(%sysfunc(putn(&d,8.))-4),1)),yymmddn8.));%mend; ``` A terrible golfing language but here's the explanation (from the inside out): Create a macro `s` that accepts a date input `d` and a numeric weekday `a`. Then `%eval(%sysfunc(putn(&d,8.))-4)` converts the date to a SAS numeric date and decrements it by 4 days. The `intnx` function then returns the next occurrence of the specified weekday. `putn` then formats the date back to yyyymmdd and `%put` prints the output to the log. [Answer] ## Mathematica, ~~85~~ 49 bytes ``` #~DatePlus~Mod[#2-#~DateValue~"ISOWeekDay",7,-3]& ``` The input format for dates is either a list like `{2016, 12, 16}` or an actual `DateObject` (I think a few others work as well, but I've tested these). In either case, the output format will match automatically. The day numbering starts from `1` on Mondays. The idea is to compute the difference between the input weekday and the target weekday with `#2-#~DateValue~"ISOWeekDay"` and then to map it into `[-3, 3]` using a modulo with offset (i.e. `Mod[...,7,-3]`). The result is simply added to the input date (the default unit for date object addition is days). [Answer] ## R, 119 77 56 bytes Unnamed function that takes two inputs, the date `D` (string) and the day `d` (numeric). ``` function(D,d,s=-3:3+as.Date(D))s[lubridate::wday(s)==d] ``` Uses the function `wday()` from the `lubridate` package. It can conveniently convert `Date` objects into week days with `1` being treated as Sunday by default. Edit: I/O is now the default of the `as.Date()` function: `"YYYY-mm-dd"` **Ungolfed and Explained** ``` function(D,d){ D=as.Date(D); # Format input date s=-3:3+D; # Generate sequence of +- 3 days s[lubridate::wday(s)==d] # Match the weekday that equals to target day } ``` Edit: Now creates a sequence of `+-3` days for which any given weekday is guaranteed to be found in. Subsequently we only have to match one day which made the problem much easier. [Answer] # Shell + GNU date, 43 bytes ``` date +%F -d$1-3day`date -d$1+$2day +%w`day ``` I wish I could explain how this works, but there was so much trial-and-error tweaking it no longer makes sense even to me! We start by subtracting three days so that adding a number in range 0-6 gives the nearest. But why adding the desired weekday to the target date gives the necessary offset has slipped my grasp. Input as in the question; output format is YYYY-MM-DD. [Online test](https://tio.run/##PU@9DoMgEN55ihswaoxG6F/s1qVjl64OpQWjCzZAY4jx2SmI8Rsu9/0c3L2Z7h2TehIqy2fHmRFQJHcoOSblgTP7WqVAC0w99@7kNesWhLpRwWoPEmhNzoSSxjf0WJP6hPiIwCOGbMjMpKouy6puZsBXDdJ0kD4EU0IbSBoNZoREw6CvkEK7JzfgbNvpycxP@bcL7Esbl7vlgIO9D8Xjohiq3f6XMSI@/YgCc38) ]
[Question] [ # Challenge Given a rectangular grid of printable ascii characters as a string or through standard input, write a function or program that collapses the non-space characters into a pile on the bottom. ## The rules: * The output has the same dimensions and characters as the input. * A non-space character at `(row a,column b)` can't have a space character `' '` at `(a-1, b)`, `(a-1,b-1)` or `(a-1,b+1)`, where rows are numbered up from the bottom-most. This has the consequence that all vertical piles should collapse sideways. * A non-space character can travel at most `(initial height - final height)` places to the left or right (see Fig. 1). * You can assume the picture has enough space to collapse without characters falling out of the screen. Figure 1: possible final locations for characters `@#$` shown as `x,y,z`, respectively. ``` .............. ...@.......... ..xxx......... .xxxxx...#.... xxxxxxx.yyy.$. ``` The order in which characters collapse can be chosen freely. Trailing spaces are not okay but trailing newlines are. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Example ``` (__) (oo) /------\/ / | || * /\---/\ ~~ ~~ ..."Have you mooed today?"... ``` One possible output: ```       --(_ /----|/|(o_) /|/~\---~\\/o) ..."Have*you~mooed~today?"... ``` [Answer] ## JavaScript (ES6), ~~100~~ ~~90~~ 88 bytes ``` f=s=>s==(l=s.search` `,s=s.replace(eval(`/(\\S)([^]{${l-1},${l+1}}) /`),` $2$1`))?s:f(s) s=` (__) (oo) /------\\/ / | || * /\\---/\\ ~~ ~~ ..."Have you mooed today?"...` console.log(s) console.log(f(s)) ``` Requires the the string to have at least two lines and all lines padded to equal length. Output for the example image: ``` ( -- /|---/|-(o__ */~~\---~\|\/o)) ..."Have you/mooed~today?"... ``` Note that as it tries to move elements to the right if possible, the `*` did not fall between the `Have` and the `you`. Edit: Saved 10% thanks to @ETHproductions. Saved another 2 bytes thanks to @DanielIndie. # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` +`(?<=(.)*)(\S)(.*¶(?<-1>)?(?>(?<-1>.)*).?) $3$2 ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0HD3sZWQ09TS1MjJlhTQ0/r0DagiK6hnaa9hr0dhAmS1bPXVOBSUDFWMfr/XwEdaMTHa8LYXJiy@flYZfV1wSBGXwGLrL5CDYiqqVHAIqsFlI8BatWPwSYLBHV1MAImq6enp@SRWJaqUJlfqpCbn5@aolCSn5JYaa8ElAEA "Retina 0.8.2 – Try It Online") A slightly different approach to my JavaScript answer, this uses a balancing group to match a space below the non-space character; the `(?<-1>)?` allows the space to be one column to the left while the `.?` allows the space to be one column to the right. # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes ``` ~0L$`.(.*)¶ +s`(\S)(.{$.1,$.&}) ¶ $$2$$1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/v87ARyVBT0NPS/PQNi7t4gSNmGBNDb1qFT1DHRU9tVpNhUPbFFRUjFRUgGoV0IFGfLwmjM2FKZufj1VWXxcMYvQVsMjqK9SAqJoaBSyyWkD5GKBW/RhsskBQVwcjYLJ6enpKHollqQqV@aUKufn5qSkKJfkpiZX2SkAZAA "Retina – Try It Online") Port of my JavaScript answer. The `0L$` atomic stage takes the input and substitutes the two lengths into the second line resulting in the command that actually performs the replacement, which is then evaluated on the original input by the `~` compound stage. [Answer] ## Python 2, 298 bytes ``` a=input() L=len(a);s=' ' a=[list(s*L+l.ljust(L+max(map(len,a))))for l in a] t=1 while t: t=0 for y in range(L-1): for x in range(len(a[y])): c=a[y][x];C=a[y+1][x-1:x+2] if s!=c and s in C:t=1;a[y][x]=s;a[y+1][[[x+1,x][C[1]==s],x-1][C[0]==s]]=c for l in map(''.join,a):print l[L:].rstrip() ``` Takes input as a list of strings (one per line) Example: Input: ``` [' (__)', ' (oo)', ' /------\/', ' / | ||', ' * /\---/\ ', ' ~~ ~~', '..."Have you mooed today?"...'] ``` Output: ``` ( -----/|-(o__ //|~~\---~\|\/o)) ..."Have*you/mooed~today?"... ``` [Answer] **C, 252 bytes** ``` e=1,l,c,i,j,p,r,w,a[999];f(){while((i=getchar())>0)a[w++]=i,i<16?l++:0,l?0:c++;while(e)for(i=e=0;i<c;i++)for(j=l;j>=0;j--)e=(r=a[p=j*(c+1)+i]-32?a[r=p+c+1]-32?a[r=p+c]-32?a[r=p+c+2]-32?0:r:r:r:0)?l=a[p],a[p]=a[r],a[r]=l:e;for(i=0;i<w;)putchar(a[i++]);} ``` Ungolfed test code: ``` #include <stdio.h> e=1,l,c,i,j,p,r,w,a[999]; f() { // counting lines and columns while ((i = getchar())>0)a[w++] = i, i<16 ? l++ : 0, l ? 0 : c++; // main shaking loop while (e) // repeat while collapsing for (i = e = 0; i < c; i++) // columns loop for (j = l; j >= 0; j--) // lines loop e = ( // remember that collapsing was r = // find place to collapse a[p = j*(c + 1) + i] - 32 ? // if not space a[r = p + c + 1] - 32 ? // if char under the current is not a space a[r = p + c] - 32 ? // see one position left a[r = p + c + 2] - 32 ? 0 // then one position right : r : r : r : 0 ) ? // and if place was found l=a[p],a[p]=a[r],a[r]=l // replace values in positions p and r : e; //print resulting picture for(i=0;i<w;)putchar(a[i++]); } int main(void) { int cnt; FILE * testf = fopen("caw.txt","w"); char testd[][31] = { " (__) \n", " (oo) \n", " /------\\/ \n", " / | || \n", " * /\\---/\\ \n", " ~~ ~~ \n", "...\"Have you mooed today ? \"...", "" }; // prepare data for test printf("Initial data:\n"); for(cnt = 0; cnt < 7; cnt++) { printf("%s", testd[cnt]); fprintf(testf, testd[cnt]); } fclose(testf); // redirect standard input freopen("caw.txt", "r", stdin); printf("\n\nResult:\n"); // start test f(); } ``` Result of test: [![enter image description here](https://i.stack.imgur.com/5uRU8.png)](https://i.stack.imgur.com/5uRU8.png) [Answer] # JavaScript, 286 bytes ``` b=>eval('f=b=>b==null||" "==b;b=b.split`\n`.map(b=>[...b]);a:for(;;){for(c=0;c<b.length-1;c++)for(g=b[c],d=0;d<g.length;d++){h=g[d];if(!f(h)){e=0;f(b[c+1][d])?e=2:f(b[c+1][d-1])?e=1:f(b[c+1][d+1])&&(e=3);if(e){b[c+1][d+e-2]=h;b[c][d]=" ";continue a}}}break}b.map(b=>b.join``).join`\n`') ``` ## Examples ``` // Here I assume that you've assigned the above function to `fall` console.log(fall(` (__) (oo) /------\/ / | || * /\---/\\ ~~ ~~ ..."Have you mooed today?"...`)) ``` Output: ``` - /--(-\--(__ /|~~---/~||/oo)) ..."Have*you/mooed~today?"... ``` Another example: ``` console.log(fall(` (\__/) .~ ~. )) /O O ./ .' {O__, \ { / . . ) \\ |-| '-' \ } .( _( )_.' '---.~_ _ _&`)) ``` Output: ``` _ , / OO/__'_.. . {.(|-|.(O'))/.~{ /('---.~___-_&)_.'}\~.')) ``` ## Ungolfed function ``` function fall(input) { let move = true let lines = input.split("\n").map(line => line.split("")) let isSpace = c => c == null || c == " " loop: for (;;) { for (let y = 0; y < lines.length - 1; y++) { let line = lines[y] for (let x = 0; x < line.length; x++) { let ch = line[x] if (!isSpace(ch)) { let dx = 0 if (isSpace(lines[y+1][x])) { dx = 2 } else if (isSpace(lines[y+1][x-1])) { dx = 1 } else if (isSpace(lines[y+1][x+1])) { dx = 3 } if (dx) { lines[y + 1][x + dx - 2] = ch lines[y][x] = " " continue loop } } } } break } return lines.map(line => line.join("")).join("\n") } ``` ]
[Question] [ ## Background An unlabelled tree may look like this: ``` o / | \ o o o | / \ o o o ``` To *linearize* this tree, we first label each node `o` with it's number of child nodes: ``` 3 / | \ 1 0 2 | / \ 0 0 0 ``` and then write the numbers in a list in a breath-first manner, meaning line by line and left to right: ``` [3, 1, 0, 2, 0, 0, 0] ``` This is a unique and unambiguous representation of the tree above, meaning that no two different pure trees will have the same linearizations and that we can reconstruct the original tree from the list. Although each tree corresponds to a certain integer list, not each integer list represents a valid linearized tree: For example `[2, 0, 0, 0]` does not represent a valid tree, if we try to de-linearize it we end up with this tree ``` [2,0,0,0] -> 2 [0,0,0] -> 2 [0,0] -> 2 [0] / \ / \ / \ 0 0 0 ``` but still have a `0` left in the list and nowhere to put it. Similarly `[2, 0]` is not a valid tree linearization either, as the de-linearized tree has an empty child spot: ``` 2 / \ 0 ``` ## Task Given an integer list, decide whether it is a valid linearization of a tree using as few bytes as possible. You may write a full program or a function. **Input:** A non-empty list of non-negative integers. **Output:** A truthy value if the list is a linearization of a tree, a falsy value otherwise. ## Testcases Truthy ``` [0] [2, 0, 0] [1, 1, 1, 1, 1, 0] [3, 1, 0, 2, 0, 0, 0] [2, 0, 2, 2, 0, 0, 2, 0, 0] [3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0] [1, 5, 3, 0, 2, 1, 4, 0, 1, 0, 0, 2, 1, 0, 0, 1, 1, 0, 0, 0, 0, 2, 1, 0, 0, 1, 0] ``` Falsy ``` [0, 1] [2, 0] [2, 0, 0, 0] [1, 0, 1] [3, 2, 1, 0] [2, 0, 0, 2, 0, 0] [4, 1, 0, 3, 0, 0, 0, 0] [4, 2, 0, 3, 1, 0, 0, 0, 0, 0] ``` [Answer] ## Haskell, 44 bytes ``` f[n:k]=iterate f[k]!!n f _=[] g x=f[x]==[[]] ``` Defines a function `g` that takes a list and returns a boolean. [See it pass all test cases](http://rextester.com/MVN13465). ## Explanation This relies on the fact that depth-first and breadth-first linearizations produce the same arrays. See Martin's answers for details; basically they both give the same arithmetical condition on the array. The function `f` is given the input list wrapped in a singleton list. It pops one number `n` off the list, then calls itself `n` times on the remaining list to process the children of the popped node (depth first). Popping the empty list results in `[]`, which I use as an error state. The function `g` checks that the end result is `[[]]`, the unique non-erroneous state with no unprocessed nodes. If Haskell was weakly typed, I could just use `0` or something as the error state, and wouldn't have to wrap the input into another list. [Answer] ## Mathematica, 38 bytes ``` Last@#<0<=Min@Most@#&@Accumulate[#-1]& ``` The basic idea is that we keep track of a number of nodes to fill. Each element in the list uses up one node and adds as many as it has children. So each element `i` changes the total count by `i-1`. This count is off by one, because should be starting from `1` (the root), not `0`. For the tree to be valid we a) can never go below `0` throughout the list, because we wouldn't have anywhere to place the current node and b) need to end up with `-1` at the end, otherwise we've got unused nodes left. We obtain this running total of remaining nodes with `Accumulate[#-1]` (which computes the prefix sums of the input list minus one). And then we check that the last element and *only* the last element is `-1` with: ``` Last@#<0<=Min@Most@# ``` Note that checking that the last element is negative is sufficient, since we can never decrement by more than `1`, so if the last values was `-2` or lower it would be impossible for the minimum the others to be non-negative. [Answer] ## [Retina](http://github.com/mbuettner/retina), 29 bytes ``` \d+ $* ^(?<-1>(1)*,)*$(?(1)!) ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoKXig_PC0xPigxKSosKSokKD8oMSkhKQ&input=MAoyLDAsMAoxLDEsMSwxLDEsMAozLDEsMCwyLDAsMCwwCjIsMCwyLDIsMCwwLDIsMCwwCjMsMiwyLDEsMSwxLDAsMCwwLDAsMAoxLDUsMywwLDIsMSw0LDAsMSwwLDAsMiwxLDAsMCwxLDEsMCwwLDAsMCwyLDEsMCwwLDEsMAowLDEKMiwwCjIsMCwwLDAKMSwwLDEKMywyLDEsMAo0LDEsMCwzLDAsMCwwLDAKNCwyLDAsMywxLDAsMCwwLDAsMAoyLDAsMCwyLDAsMA) (The first line enables a linefeed-separated test suite.) ### Explanation The basic idea is the same as that of [my Mathematica answer](https://codegolf.stackexchange.com/a/101005/8478): we keep track of a running total of remaining nodes, ensure it never goes below zero but ends on zero. However, the way this is implemented with regex is very different. ``` \d+ $* ``` This simply converts the input to unary, turning each integer `n` into `n` 1s. ``` ^(?<-1>(1)*,)*$(?(1)!) ``` This is where the real magic happens. It's a fairly short regex that matches only valid trees, but it's mechanics are quite subtle. I'm using [balancing groups](https://stackoverflow.com/a/17004406/1633117) to keep track of the number of nodes, which are a way to work with stacks inside the regex. First off, of course such a stack can never have a negative depth, so we can't really end up with a representation of `-1` at the end, as we do in the Mathematica solution. However, we can note that the final element of the input *has* to be zero on a valid stack (otherwise we couldn't end up with `-1`). It turns out that it actually saves bytes to check *both* that we end on zero and with zero remaining nodes. So here is a breakdown of the regex: ``` ^ e# Anchor the match to the beginning of the string. (?<-1> e# Each repetition of this group will match one number. e# We can ignore the <-1> for now. (1)* e# Match each unary digit of the current number, pushing e# a capture onto stack 1. This increments our total of e# remaining nodes by 1 for each child. , e# Match a comma. Note that this requires that there is at e# least one more number in the list. )* e# At the end of the repetition the <-1> pops one capture from e# the stack. This is the node that the current number itself e# takes up. $ e# Match the end of the string. This requires the input to end e# in a zero, because the last thing we matched was a comma. (?(1)!) e# Make sure that stack 1 is empty, so that we don't have any e# unused nodes. ``` [Answer] ## CJam (20 bytes) ``` {X0@{+\(_0>{\}*}/|!} ``` [Online test suite](http://cjam.aditsu.net/#code=q'%2C-~%5D%0A%0A%7BX0%40%7B%2B%5C(_0%3E%7B%5C%7D*%7D%2F%7C!%7D%0A%0A%25&input=%5B0%5D%0A%5B2%2C%200%2C%200%5D%0A%5B1%2C%201%2C%201%2C%201%2C%201%2C%200%5D%0A%5B3%2C%201%2C%200%2C%202%2C%200%2C%200%2C%200%5D%0A%5B2%2C%200%2C%202%2C%202%2C%200%2C%200%2C%202%2C%200%2C%200%5D%0A%5B3%2C%202%2C%202%2C%201%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%5D%0A%5B1%2C%205%2C%203%2C%200%2C%202%2C%201%2C%204%2C%200%2C%201%2C%200%2C%200%2C%202%2C%201%2C%200%2C%200%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200%2C%202%2C%201%2C%200%2C%200%2C%201%2C%200%5D%0A%5B0%2C%201%5D%0A%5B2%2C%200%5D%0A%5B2%2C%200%2C%200%2C%200%5D%0A%5B1%2C%200%2C%201%5D%0A%5B3%2C%202%2C%201%2C%200%5D%0A%5B2%2C%200%2C%200%2C%202%2C%200%2C%200%5D%0A%5B4%2C%201%2C%200%2C%203%2C%200%2C%200%2C%200%2C%200%5D%0A%5B4%2C%202%2C%200%2C%203%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%5D). This is an anonymous block which takes an array on the stack and leaves 0 or 1 on the stack. ### Dissection In pseudocode this is: ``` p = 1 q = 0 foreach (i in input): q += i if (--p <= 0): # in practice, if (--p == 0): p, q = q, p return (p | q) == 0 # i.e. p == 0 && q == 0 ``` `q` accumulates the sum of the labels of the nodes at the current level in the tree; `p` counts down the nodes remaining in the current level. [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 17 bytes ``` ( +? ;-) ,_" @@,! ``` [Try it online!](http://labyrinth.tryitonline.net/#code=KAorPwo7LSkKLF8iCkBALCE&input=MSwgNSwgMywgMCwgMiwgMSwgNCwgMCwgMSwgMCwgMCwgMiwgMSwgMCwgMCwgMSwgMSwgMCwgMCwgMCwgMCwgMiwgMSwgMCwgMCwgMSwgMA) Truthy output is `-1` and falsy output is empty. Defining truthy and falsy in Labyrinth is a bit tricky, because Labyrinth's branches are principally ternary. However, the only way to construct a conditional with reliably two branches, you can only do this: ``` >"F T ``` In this case, I'd consider moving straight ahead falsy (because the direction of movement is unaffected) and turning truthy. These correspond to zero and non-zero respectively. The reason I'm using an empty output to represent zero is that, if you were to pipe the output back into another Labyrinth program, the input operator `?` would actually push a zero if the input is empty, so I consider the empty string a valid representation of zero. ### Explanation The algorithm is still the same as in my Mathematica and Retina answers, but due to Labyrinth's control flow, it works a bit different this time: * We don't work with the total counter off-by-one here. Instead we a) work with a negative counter and b) initialise it to `-11` initially, so that we want the counter to be negative throughout the list and hit zero on the last input. This actually simplifies the control flow here. * Instead of building the full list and checking whether it contained the wrong value, there are three possible termination conditions: 1. We hit EOF before reaching a total count of zero. In that case there are unused nodes left and we print nothing. 2. We reach zero *and* we're at EOF. In this case, we've got a valid tree. 3. We reach zero and aren't at EOF yet. In this case, we ran out of nodes before covering all elements, and we print nothing. As for the actual code, we start in the top left corner. The `(` turns the implicit zero on top of the stack into a `-1`, which will be the running total. We then enter the very tight main loop of the program, `+?-)"_,;+`: ``` + Add the top two values. This does nothing on the first iteration, but gets rid of a helper-zero on subsequent iterations. ? Read and push integer. - Subtract it from running total. ) Increment. " No-op. There is a branch at this point. If the running total is zero, we move straight ahead onto the , (see below). Otherwise, the loop continues. _ Push a zero. This is necessary to prevent the IP from turning south. , Read a character. This will either be the next separator (some positive number) or EOF (-1). If it's EOF, the IP turns south and the program terminates. Otherwise, the loop continues. ; Discard the separator. ``` That leaves only the cases where we've reduced the running total to zero at some point. The IP moves onto the lower-right `,` and reads another character to check if we've reached EOF. If not, the value will be positive and the IP turns west towards the `@` and the program terminates. If we did reach EOF, the IP turns east and prints the `-1` with `!`. The IP will then worm its way towards the lower left `@` via a slightly weird path to terminate the program. [Answer] ## Python, 82 bytes ``` lambda l:len(l)==sum(l)+1 and not any(list(l[x]>=len(l)-x for x in range(len(l)))) ``` Need more test cases. [Answer] # Pyth, 13 bytes ``` qxsM._tMQ_1tl ``` We start by calculating the current filled-ness of the tree at all points in the input representation. That portion of the idea is largely borrowed from Martin Ender, so thanks to him. `sM._tMQ` Once we have this list, we check if the first index containing `-1` (`x..._1`) is the length of the input minus one (`q...tl(Q)`). Don't believe it works? [Try it yourself!](http://pyth.herokuapp.com/?code=qxsM._tMQ_1tl&test_suite=1&test_suite_input=%5B0%5D%0A%5B2%2C+0%2C+0%5D%0A%5B1%2C+1%2C+1%2C+1%2C+1%2C+0%5D%0A%5B3%2C+1%2C+0%2C+2%2C+0%2C+0%2C+0%5D%0A%5B2%2C+0%2C+2%2C+2%2C+0%2C+0%2C+2%2C+0%2C+0%5D%0A%5B3%2C+2%2C+2%2C+1%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%5B1%2C+5%2C+3%2C+0%2C+2%2C+1%2C+4%2C+0%2C+1%2C+0%2C+0%2C+2%2C+1%2C+0%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+2%2C+1%2C+0%2C+0%2C+1%2C+0%5D%0A%5B0%2C+1%5D%0A%5B2%2C+0%5D%0A%5B2%2C+0%2C+0%2C+0%5D%0A%5B1%2C+0%2C+1%5D%0A%5B3%2C+2%2C+1%2C+0%5D%0A%5B2%2C+0%2C+0%2C+2%2C+0%2C+0%5D%0A%5B4%2C+1%2C+0%2C+3%2C+0%2C+0%2C+0%2C+0%5D%0A%5B4%2C+2%2C+0%2C+3%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%5D&debug=0) ]
[Question] [ Recently, I was introduced to a puzzle game known as [Solitaire Chess](http://www.thinkfun.com/products/solitaire-chess/). I'll summarize the rules here: * The board is a 4x4 checkerboard. * All pieces are the same color (no teams) and all pieces can capture any other piece. * Every move must be a capture. No moving to empty squares. * There must be exactly one piece remaining at the end. * All pieces move exactly like they do in chess, with one modification: the pawn can capture in any diagonal direction (which technically makes it a [*ferz*](https://en.wikipedia.org/wiki/Ferz_(chess))). For the benefit of those who may not know, I have included movement diagrams. * None of the other rules of chess (such as check, castling, etc.) apply here. It's all about captures. **King (K)** ``` K * . . | * K * . | * * * . * * . . | * * * . | * K * . . . . . | . . . . | * * * . . . . . | . . . . | . . . . ``` **Queen (Q)** ``` Q * * * | * Q * * | * * * . * * . . | * * * . | * Q * * * . * . | . * . * | * * * . * . . * | . * . . | . * . * ``` **Rook (R)** ``` R * * * | * R * * | . * . . * . . . | . * . . | * R * * * . . . | . * . . | . * . . * . . . | . * . . | . * . . ``` **Bishop (B)** ``` B . . . | . B . . | * . * . . * . . | * . * . | . B . . . . * . | . . . * | * . * . . . . * | . . . . | . . . * ``` **Knight (N)** ``` N . . . | . N . . | . . . * . . * . | . . . * | . N . . . * . . | * . * . | . . . * . . . . | . . . . | * . * . ``` **Pawn (P)** ``` P . . . | . P . . | * . * . . * . . | * . * . | . P . . . . . . | . . . . | * . * . . . . . | . . . . | . . . . ``` ## Input/output For reference, the sample puzzle from the Solitaire Chess webpage will be used: ``` . . . . . B . . R P . . . . . N ``` The solution is to take the pawn with the knight, then take the knight with the rook, and finally take the bishop with the rook. **Input** Input must be in one of three forms; you are free to pick the one that is most convenient for you. * A string of characters such as `.....B..RP.....N`, with or without newlines. The character representing a blank space may be any character that isn't one of `KQRBNP`. * A list of lists (or a flattened list) where the elements are either characters or numbers, like so: `[['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']]` or `[[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]]`. For the former, the character that represents a blank space may be anything that isn't one of `KQRBNP`. For the latter, I've given pieces the number that corresponds to their rank in my earlier list of moves (`1` is a king, `4` is a bishop, `6` is a pawn, etc.). You are free to change the numbering. * A list of coordinates where each element has the form `[x, y, 'c']`, like so: `[[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']]`. If you pick one of the list-based input formats, the separators and delimiters may be any reasonable and understandable characters. **Output** Output must be a sequence of moves or a sequence of board states. Some puzzles have more than one solution; you may output one or all of them. If you choose to output a sequence of board states, each board must be in one of the three input formats, with a reasonable separator (such as newlines) between them. If you choose to output a sequence of moves, they must be expressed as a list of pairs of coordinate pairs, like so: `[[[3,0], [1,1]], [[0,1], [1,1]], [[1,1], [1,2]]]`. `[0,0]` represents the bottom left corner, and again, separating and delimiting characters may be any reasonable choice. If a given board cannot be solved, output any falsy value (`0`, empty string, etc.). If a given board has fewer than two pieces, behavior is undefined. ## Test Cases *Note: outputs are only given as a list of pairs of coordinates since the other formats should be fairly easy to check for correctness (and I didn't feel like typing out all the possible output formats). Also, for the puzzles that have more than one solution, only one possibility is provided.* **Input 1:** ``` . . . N . . . . . R . . . . B . ...N.....R....B. [['.', '.', '.', 'N'], ['.', '.', '.', '.'], ['.', 'R', '.', '.'], ['.', '.', 'B', '.']] [[0, 0, 0, 5], [0, 0, 0, 0], [0, 3, 0, 0], [0, 0, 4, 0]] [[3, 3, 'N'], [1, 1, 'R'], [2, 0, 'B']] ``` **Output 1:** ``` [[[2,0], [1,1]], [[1,1], [3,3]]] ``` **Input 2:** ``` . . . . . B . . R P . . . . . N .....B..RP.....N [['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']] [[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]] [[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']] ``` **Output 2:** ``` [[[3,0], [1,1]], [[0,1], [1,1]], [[1,1], [1,2]]] ``` **Input 3:** ``` . N R . B . . . N . . B . . P . .NR.B...N..B..P. [['.', 'N', 'R', '.'], ['B', '.', '.', '.'], ['N', '.', '.', 'B'], ['.', '.', 'P', '.']] [[0, 5, 3, 0], [4, 0, 0, 0], [5, 0, 0, 4], [0, 0, 6, 0]] [[1, 3, 'N'], [2, 3, 'R'], [0, 2, 'B'], [0, 1, 'N'], [3, 1, 'B'], [2, 0, 'P']] ``` **Output 3:** ``` [[[2,0], [3,1]], [[0,1], [1,3]], [[0,2], [1,3]], [[2,3], [1,3]], [[3,1], [1,3]]] ``` **Input 4:** ``` . . . N . . . R R B B . N P P . ...N...RRBB.NPP. [['.', '.', '.', 'N'], ['.', '.', '.', 'R'], ['R', 'B', 'B', '.'], ['N', 'P', 'P', '.']] [[0, 0, 0, 5], [0, 0, 0, 3], [3, 4, 4, 0], [5, 6, 6, 0]] [[3, 3, 'N'], [3, 2, 'R'], [0, 1, 'R'], [1, 1, 'B'], [2, 1, 'B'], [0, 0, 'N'], [1, 0, 'P'], [2, 0, 'P']] ``` **Output 4:** ``` [[[2,1], [3,2]], [[1,1], [3,3]], [[3,2], [1,0]], [[3,3], [0,0]], [[0,1], [0,0]], [[0,0], [1,0]], [[1,0], [2,0]]] ``` **Input 5:** ``` P . . . . R . . R . R . . R . . P....R..R.R..R.. [['P', '.', '.', '.'], ['.', 'R', '.', '.'], ['R', '.', 'R', '.'], ['.', 'R', '.', '.']] [[6, 0, 0, 0], [0, 3, 0, 0], [3, 0, 3, 0], [0, 3, 0, 0]] [[0, 3, 'P'], [1, 2, 'R'], [0, 1, 'R'], [2, 1, 'R'], [1, 0, 'R']] ``` **Output 5:** ``` [[[0,3], [1,2]], [[1,2], [2,1]], [[2,1], [1,0]], [[1,0], [0,1]]] ``` **Input 6:** ``` . P . N K . . . . . B . . . R Q .P.NK.....B...RQ [['.', 'P', '.', 'N'], ['K', '.', '.', '.'], ['.', '.', 'B', '.'], ['.', '.', 'R', 'Q']] [[0, 6, 0, 5], [1, 0, 0, 0], [0, 0, 4, 0], [0, 0, 3, 2]] [[1, 3, 'P'], [3, 3, 'N'], [0, 2, 'K'], [2, 1, 'B'], [2, 0, 'R'], [3, 0, 'Q']] ``` **Output 6:** ``` [[[3,0], [2,0]], [[2,0], [2,1]], [[3,3], [2,1]], [[2,1], [1,3]], [[0,2], [1,3]]] ``` [Answer] # Haskell, ~~226~~ ~~195~~ ~~191~~ 188 bytes Returns a list of all solutions. Each solution is a list of moves. Returns an empty list if there is no solution. Saved 4 bytes Thanks to Lynn. [Try it online](http://ideone.com/fork/lK6q8G "Try it online") ``` m"P"=[2] m"N"=[5] m"K"=[1,2] m"R"=[1,4,9] m"B"=[2,8,18] m _=m"B"++m"R" l%x=[z|z<-l,fst z/=x] f[_]=[[]] f l=[(i,j):r|(i@(s,t),a)<-l,(j@(u,v),_)<-l,(s-u)^2+(t-v)^2`elem`m a,r<-f$(j,a):l%i%j] ``` Usage: ``` main = do print $ f [((3, 3), "N"), ((1, 1), "R")] putStrLn"" mapM_ print $ f [((3, 3), "N"), ((1, 1), "R"), ((2, 0), "B")] putStrLn"" mapM_ print $ f [((1, 2), "B"), ((0, 1), "R"), ((1, 1), "P"), ((3, 0), "N")] putStrLn"" mapM_ print $ f [((1, 3), "P"), ((3, 3), "N"), ((0, 2), "K"), ((2, 1), "B"), ((2, 0), "R"), ((3, 0), "Q")] ``` Output: ``` [] [((2,0),(1,1)),((1,1),(3,3))] [((3,0),(1,1)),((0,1),(1,1)),((1,1),(1,2))] [((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2))] [((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2))] [((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2))] [((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2))] [((1,3),(0,2)),((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((1,3),(0,2)),((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((1,3),(0,2)),((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((1,3),(0,2)),((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2))] [((1,3),(0,2)),((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2))] [((3,3),(2,1)),((2,1),(1,3)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3))] [((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2))] [((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3))] [((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2))] [((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2))] [((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2))] [((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2))] [((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2))] [((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2))] [((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((0,2),(1,3))] [((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((1,3),(0,2))] [((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((1,3),(0,2)),((2,0),(0,2))] [((3,3),(2,1)),((3,0),(2,1)),((1,3),(0,2)),((2,1),(2,0)),((2,0),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((2,1),(1,3))] [((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2)),((1,3),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(1,3)),((0,2),(1,3))] [((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2)),((2,1),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((2,1),(1,3)),((2,0),(0,2)),((0,2),(1,3))] [((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2)),((0,2),(1,3))] [((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2)),((1,3),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((1,3),(0,2)),((2,0),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2)),((2,1),(0,2))] [((3,3),(2,1)),((3,0),(2,0)),((1,3),(0,2)),((2,1),(0,2)),((2,0),(0,2))] [((0,2),(1,3)),((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3))] [((0,2),(1,3)),((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] [((0,2),(1,3)),((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] [((0,2),(1,3)),((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] [((2,1),(3,0)),((0,2),(1,3)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3))] [((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3)),((0,2),(1,3))] [((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((0,2),(1,3)),((3,3),(1,3))] [((2,1),(3,0)),((2,0),(3,0)),((0,2),(1,3)),((3,0),(3,3)),((3,3),(1,3))] [((2,0),(2,1)),((1,3),(0,2)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((2,0),(2,1)),((0,2),(1,3)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] [((2,0),(2,1)),((3,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))] [((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))] [((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))] [((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))] [((2,0),(2,1)),((3,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))] [((3,0),(3,3)),((3,3),(1,3)),((1,3),(0,2)),((0,2),(2,0)),((2,0),(2,1))] [((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((1,3),(3,3))] [((3,0),(2,1)),((1,3),(0,2)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,1)),((0,2),(1,3)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] [((3,0),(2,1)),((2,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))] [((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))] [((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))] [((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))] [((3,0),(2,1)),((2,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))] [((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))] [((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))] [((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))] [((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))] [((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))] [((3,0),(2,0)),((2,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))] [((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))] [((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))] [((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))] [((3,0),(2,0)),((2,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))] [((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,0)),((1,3),(0,2)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))] [((3,0),(2,0)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2))] [((3,0),(2,0)),((1,3),(0,2)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((2,1),(1,3)),((2,0),(0,2)),((0,2),(1,3))] [((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2)),((0,2),(1,3))] [((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2)),((1,3),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2)),((2,0),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((0,2),(1,3)),((2,1),(1,3))] [((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2)),((1,3),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(1,3)),((0,2),(1,3))] [((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((1,3),(0,2)),((2,1),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2)),((2,0),(0,2))] [((3,0),(2,0)),((3,3),(2,1)),((1,3),(0,2)),((2,0),(0,2)),((2,1),(0,2))] [((3,0),(2,0)),((0,2),(1,3)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))] ``` [Answer] ## Javascript (ES6), ~~372~~ ~~361~~ 358 bytes It (still) needs some optimizing. But here is a ~~first~~ ~~2nd~~ 3rd attempt. ``` b=>{for(n=-4,b=[...b];n<36;b.splice(n+=8,0,0,0,0,0));l=[];(M=(P,u,Z,z,L)=>{for(P=u=n;u--;) for((z=[640,164928,641,259,899,898]["PNBRQK".indexOf(b[u])])&&P++,L=1,s=z&1;z>>=1;L++)for(Z =u;z&1&!((Z+=L)&n)&&(b[Z]<'A'||!(M(l.push([b[Z],[u&3,31-u>>3],b[u],[Z&3,31-Z>>3]]),b[Z]=b[u ],b[u]='.'),b[u]=b[Z],b[Z]=l.pop()[0]))&&s||(L=-L,Z=u,L<0););P-37||console.log(l)})()} ``` Output format: ``` // Puzzle #1 [["B", [2, 0], "R", [1, 1]], ["B", [1, 1], "N", [3, 3]]] ``` Example: ``` let F = b=>{for(n=-4,b=[...b];n<36;b.splice(n+=8,0,0,0,0,0));l=[];(M=(P,u,Z,z,L)=>{for(P=u=n;u--;)for((z=[640,164928,641,259,899,898]["PNBRQK".indexOf(b[u])])&&P++,L=1,s=z&1;z>>=1;L++)for(Z=u;z&1&!((Z+=L)&n)&&(b[Z]<'A'||!(M(l.push([b[Z],[u&3,31-u>>3],b[u],[Z&3,31-Z>>3]]),b[Z]=b[u],b[u]='.'),b[u]=b[Z],b[Z]=l.pop()[0]))&&s||(L=-L,Z=u,L<0););P-37||console.log(l)})()} console.log("Puzzle #1"); F("...N.....R....B."); console.log("Puzzle #2"); F(".....B..RP.....N"); ``` ]
[Question] [ Anomalous Cancellation (from Wolfram Alpha): > > Anomalous cancellation is a "canceling" of digits of a and b in the numerator and denominator of a fraction a/b which results in a fraction equal to the original. Note that if there are multiple but differering counts of one or more digits in the numerator and denominator there is ambiguity about which digits to cancel, so it is simplest to exclude such cases from consideration. > [Link](http://mathworld.wolfram.com/AnomalousCancellation.html) > > > In simple terms, say you have a fraction `a / b`. If you can cancel out the digits in the fraction to create another fraction `c / d` which is equal to the original (`a / b = c / d`), anomalous cancellation can be used to simplify the fraction. Your challenge is to make a program or function that inputs a fraction string in the form `a/b` and outputs or returns a truthy value if the fraction can be simplified using anomalous cancellation, and a falsy value otherwise. `a` and `b` will always be non-zero positive integers. `a` and `b` will always have two or more digits. Also, all of the digits from either `a` or `b` will not be cancelled out (You wont get the input `12/21`), at least one digit from `a` and `b` will be cancelled each time (You wont get the input `43/21`), and the end result will never be `0` for either `a` or `b`. Your program must cancel out all common digits between `a` and `b` (ie. in `1231/1234`, you must cancel out a `1`, a `2`, and a `3`). If there is multiple possibilities for cancellation, choose the leftmost digit first (515/25 becomes 15/2 not 51/2). Examples: ``` Input Output Why 1019/5095 true Remove the 0 and the 9 from both sides of the fraction to get 11/55, which is equivalent. 16/64 true Remove the 6 from both sides, and get 1/4. 14/456 false Remove the 4s. 14/456 is not equal to 1/56. 1234/4329 false Remove the 2s, 3s, and 4s. 1234/4329 is not equal to 1/9. 515/25 false Remove the first 5 from each side. 15/2 is not equal to 515/25. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] ## Pyth, ~~22~~ 19 bytes *Thanks to @isaacg for three bytes!* ``` qFcMsMM,Jcz\/.-M_BJ ``` Explanation: ``` qFcMsMM,Jcz\/.-M_BJ Implicit: z=input(). , two-element list Jcz\/ J = split z on ',' _BJ Bifurcate reverse: [J,reversed(J)] .-M map multiset difference of elements in both lists this gives the multiset difference both ways ,Jcz\/.-M_BJ On input 1019/5095: [['1019','5095'], ['11','55']] sMM convert all strings to numbers cM map by float division qF fold equality ``` Try it [here](https://pyth.herokuapp.com/?code=qFmcFsMd%2CJcz%5C%2Fm.-Fd_BJ&input=1019%2F5095&debug=1). [Answer] # 𝔼𝕊𝕄𝕚𝕟, 17 chars / 34 bytes ``` ïČ⍘/⎖0ⓢⓈë(ïę$)≔ëï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=1019%2F5095&code=%C3%AF%C4%8C%E2%8D%98%2F%E2%8E%960%E2%93%A2%E2%93%88%C3%AB%28%C3%AF%C4%99%24%29%E2%89%94%C3%AB%C3%AF)` # Explanation ``` ïČ⍘/⎖0ⓢⓈë(ïę$)≔ëï // implicit: ï = input fraction ïČ⍘/⎖0 // get the numerator... ⓢ // split it... Ⓢ // and check if any of its items satisfy the condition: ë(ïę$) // When the item is removed from ï, ≔ëï // does its fractional value still equal the original fractional value? // implicit output ``` [Answer] # Ruby, ~~95~~ 76 bytes ``` ->a{x,y=a.split(?/).map &:chars;eval a+".0=="+(x-y).join+?/+(y-x).join+".0"} ``` ## Explanation ``` ->a{ # start of lambda a.split(?/) # splits input fraction into numerator and denominator .map &:chars; # converts them both into arrays of digits x,y= # assigns the numerator to x and the denominator to y eval # Evaluate... a+".0 # Original fraction with a .0 attached -- this forces floating-point division ==" # Equals... +(x-y).join # Numerator: Takes the relative complement of y in x (all elements in x that are not in y) and joins the resulting array into a string +?/+(y-x).join # Denominator: Takes the relative complement of x in y and joins the resulting array +".0" # Add a .0 to force floating-point division } ``` Massive thanks to Doorknob for golfing 19 bytes off. [Answer] # TeaScript, 22 bytes ``` xs`/`[0]M#E(xg(l))⌐E(x ``` Now that all the bugs are ironed out in TeaScript 3, this works nicely [Try it online](http://vihan.org/p/TeaScript/#?code=%22xs%60%2F%60%5B0%5DM%23E(xg(l))%3D%3DE(x)%22&inputs=%5B%2214%2F456%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false%7D) [Test suite](http://vihan.org/p/TeaScript/#?code=%22xs(n)m%23%20(x%3Dl,%20xs%60%2F%60%5B0%5DM%23E(xg(l))%3D%3DE(x))%22&inputs=%5B%221019%2F5095%5Cn16%2F64%5Cn14%2F456%5Cn1234%2F4329%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false%7D) [Answer] # [MATL](https://github.com/lmendo/MATL/releases/tag/6.0.0), 35 bytes ``` jtXUw'\d+'XXZ)2$XKtbm~)Kwtbm~)UwU/= ``` ### Examples ``` >> matl > jtXUw'\d+'XXZ)2$XKtbm~)Kwtbm~)UwU/= > > 1019/5095 1 >> matl > jtXUw'\d+'XXZ)2$XKtbm~)Kwtbm~)UwU/= > > 14/456 0 ``` ### Explanation ``` j % input string tXUw % duplicate, convert to number, swap '\d+'XX % apply regexp to split at '/' Z) % separate cell array of strings into two strings 2$XK % copy those two strings to clipboard K tbm~) % remove from denominator all chars present in the numerator Kw % paste both strings and swap tbm~) % remove from numerator all chars present in the denoninator UwU/= % obtain value of "simplified" fraction and compare with original ``` [Answer] # Javascript ES6, 73 bytes ``` a=>[...a.split`/`[0]].some(x=>(e=eval)(a.replace(e(`/${x}/g`),``))==e(a)) ``` ]
[Question] [ This challenge consists of two parts. The winner will be the solution with the lowest total byte count. The same language must be used for both challenges. # Part 1: Write a function or program that takes a sentence with *only [valid words](http://www.mieliestronk.com/corncob_lowercase.txt)* as input, and outputs a list of the used characters, the number of times each letter is used, and the number of letters in each of the words in the original sentence. The output from this program must be valid input to the next program (exactly as it is outputted) I'll add examples and detailed rules further down. # Part 2: Write a function or program that takes the output from the first program as input and uses [this list of English words](http://www.mieliestronk.com/corncob_lowercase.txt) and recreates a sentence with the information from the output. The sentence doesn't have to be the same as the original sentence. **More information. rules and restrictions:** Part 1: * The first input can be on any suitable format, with or without quotation marks, as function argument or from STDIN, with or without brackets etc. * The input sentence will not contain any punctuation or special characters, except for a period/dot in the end. Except for the period symbol, all characters that are in the input will be in the word list. * The first letter of the sentence will be upper case, the rest will be lower case. * The output of part 2 must start with the same upper case letter as the original sentence (so converting the input to lower case is not recommended (but OK). * The output can be on any suitable format: + **It must be possible to copy-paste the output directly into the next program / function** + **No alterations can be made when copy-pasting, the entire output must be copied and pasted as a whole, not in parts.** + You may for instance output a histogram of all letters in the alphabet, or only the ones used (in general, whatever is necessary to complete part 2) + You can not output a list of characters where multiple occurrences are repeated. For instance, `The queue` can't yield an output: `Teeehquu (3,5)`, it should be something like: `Tehqu, (1 3 1 1 2),(3 5)`. Part 2: * The program / function must accept the input exactly as is from part 1 (one exception, see comment below about taking file name as input.). + If surrounding brackets, quotation marks or similar are necessary to parse the input then these must be part of the output from part 1. * The word list can be found here. + The word list can either be saved locally as `w.txt`, or it can be fetched from the url. The url will only count as 5 bytes, so you don't need a url-shortener. + If the program can't open a file without reading the name as an input from STDIN (I believe this ~~is~~ was the case for Pyth at least), then the file name can be taken as a separate input argument. * The output must be only a sentence (list of valid words), ending with a period and an optional newline. + The output must have words with the same number of letters as the original sentence in part 1 (in correct order) + All the letters that were used in the original sentence must be used in the new output. + The sentence must start with the same upper case letter as the original input sentence and end with a period. **Both parts:** * Neither of the parts should take more than 2 minutes to execute (randomly picking out words until a solution is reached is not accepted). With the rules listed above, there should be a fair chance that the exact same sentence is reproduced, however that is not a requirement. **Examples:** In the below examples, a few different input and output formats are shown. Many more are accepted. **Part 1:** Input: ``` Zulus win. ``` Output type 1: ``` Z i l n s u w 1 1 1 1 1 2 1 5 3 ``` Output type 2: ``` (('Z',1),('i',1),('l',1),('n',1),('s',1),('u',2),('w',1)), (5,2) ``` Output type 3: ``` 'Zilnsuuw',[1,1,1,1,1,2,1],[5,2] ``` **Part 2:** Input: An exact copy of the output from part 1. Output: ``` Zulus win. ``` Note that other word combinations are accepted as long as they start with a `Z`, and the first word has 5 letters and the second has 3. The shortest code in bytes win. [Answer] # LabVIEW, 166 [LabVIEW Primitives](https://codegolf.meta.stackexchange.com/a/7589/39490) First of all i did not create 2 seperate programms because Labview does dataflow so theres really no need. Saves the histogramm with first element = ascii code of first letter rest from 1-26 go by amount. Lenght simply gets saved in an array. The first word has 3 checks, first letter, lenght and available letters in histogram. The first letter check stops after the first word. I check the histogram by decrementing it for every letter and checking if it would fall below 0. If i found my Nth word and there are no words that are buildable from the left over letters i will start deleting words from the dictonary and redo the Nth word and so on until i have found a solution. This might or might not work for sentences there are, since that would take forever to compute (my example took a few seconds already). What i tried ``` In: Zulus win. Out: Zulus win. In: Dovecot flagships oleander. Out: Dolphin advocates forelegs. In: Abash abel mammal test. Out: Amass abbe hamlet malt. ``` [![](https://i.stack.imgur.com/G6k5N.jpg)](https://i.stack.imgur.com/G6k5N.jpg) [Answer] ## Python 2.7, 353 bytes Unfortunately, I can't test it with the actual w.txt file ATM because QPython for Android can't seem to handle file I/O. It worked with data I copied and pasted though. ### Part 1, 76 bytes ``` h=lambda s:({c:s.count(c)for c in s if c.isalnum()},map(len,s[:-1].split())) ``` In: `'Hi there.'` Out: `{'H':1, 'i':1, 't':1, 'h':1, 'e':2, 'r':1}, (2, 5)` so, a list containing: * a hashmap with the histogram * a list of letter counts ### Part 2, 277 bytes ``` import itertools as i m=lambda c:' '.join([s for s in i.product(*[[w for w in open('w.txt')if len(w)==length]for length in c[1]])if sorted(''.join(s))==sorted(sum([[k.lower()]*n for k,n in c[0].items()],[]))and s[0][0]==filter(str.isupper,c[0])[0].lower()][0]).capitalize()+'.' ``` I'm really glad I managed to make it 100% pure functional. Not sure if that helps with the actual golfing, but I certainly got the obfuscation part right :D Here's A more human friendly version of pt. 2 (exactly the same flow, but with variable names): ``` from itertools import product def matching(counts): histo, word_lengths = counts first_letter = filter(str.isupper, histo)[0].lower() letters_nested = [ [char.lower()]*count for char, count in histo.items() ] letters = sum(letters_nested, []) word_options = [[word for word in open('w.txt') if len(word)==length] for length in word_lengths] sentences = product(*word_options) valid = [sentence for sentence in sentences if sorted(''.join(sentence))==sorted(letters) and sentence[0][0]==first_letter] return ' '.join(valid[0]).capitalize()+'.' ``` [Answer] # Perl, ~~516~~ 504 bytes *includes 2x +1 for `-p`* ``` @l=map{length}/\w+/g;s/\w/$c{$&}++/eg;@h=map{"$_$c{$_}"}keys%c;$_="@h @l";chomp(@w=`cat w.txt`);s/([A-Z])1//;$o=$1;s/(\w)(\d)/$h{$1}=$2,''/eg;@L=/\d/g;$l=shift@L;@O=$_,s/^.//,g([@L],%h)&&last for grep{$l==length&&/^$o/i&&h(\%h,substr$_,1)}@w;$_="@O.";s/^./uc$&/e;sub g{my%g;($R,%g)=@_;my@R=@$R;if($j=shift@R){s/./$g{$&}--/eg;my@C=grep{$j==length&&h(\%g,$_)}@w;push(@O,$_),g([@R],%g)and return 1 or pop@O for@C;0}else{1}}sub h{($y,$z)=@_;my%T;$z=~s/\w/$T{$&}++/eg;$K=1;$K&=$T{$_}<=$y->{$_}for keys%T;$K} ``` Requires to have `w.txt` in *unix* format (`\n` line endings). Uses `cat` to read the file; change to `type` for windows. Save the oneliner above in `534.pl` and run as `echo Test. | perl -p 534.pl`. Pretty large, but it's a start - lots of golfing opportunities, but I just wanted to post it to make the LabVIEW answer less lonely ;-). I've omitted the optimisations for sub-second execution, saving 30+ bytes. --- ## First snippet (73 bytes): ``` @l=map{length}/\w+/g;s/\w/$c{$&}++/eg;@h=map{"$_$c{$_}"}keys%c;$_="@h @l" ``` It produces a histogram and the word lenghts in a compact format. For input `Zulus win.` it produces a type-2 output without the `(,)`, which aren't necessary here: ``` s1 l1 u2 Z1 w1 i1 n1 5 3 ``` Here it is, ungolfed: ``` sub i{ $_=shift; # get parameter @l = map{length} /\w+/g; # cound word lengths s/\w/$c{$&}++/eg; # count letters in hash %c @h=map{"$_$c{$_}"}keys%c; # construct letter-frequency pairs "@h @l" # implicit interpolation with $" (space) separator } ``` ## Second snippet (441 bytes) This main part deals with I/O and the special treatment of the first letter, using subroutines `g` and `h` that are listed below. ``` sub o { $_=shift; chomp(@w=`cat w.txt`); # load the wordlist. s/([A-Z])1//; $o=$1; # get and remove the uppercase character, s/(\w)(\d)/$h{$1}=$2,''/eg; # reconstruct histogram in hash %h. @L=/\d/g; # get the word counts. $l = shift @L; # get the first word length. @O = $_, # initialize output with first word, s/^.//, # strip first char of word g([@L],%h) && last # call the main algoritm and quit on success for grep { $l==length && # check length /^$o/i && # only match words starting with the uppercase char h(\%h,substr$_,1) # check if the word satisfies the histogram } @w; # iterates all words (speedups removed). $_="@O."; # construct output sentence. s/^./uc$&/e; # make first char uppercase. $_ } ``` This recursive function takes a copy of the histogram, a copy of the remaining word counts, and the current word. If the word-length array is empty, returns true. Else it decrements the histogram count for the letters in the given word, takes the next word-length, and finds a list of suitable words from the wordlist. For each suitable word, it recurses. ``` sub g { my%g; # local version of histogram ($R,%g)=@_; # get parameters. my@R=@$R; # dereference arrayref copy of word lengths. if($j=shift @R) # get the next word-length. { s/./$g{$&}--/eg; # update histogram my @C = # get a list of suitable words. grep { $j==length && h(\%g,$_) } @w; push(@O,$_), # append word to output g( [@R], %g ) # recurse. and return 1 # true: append word we're done. or pop @O # remove word from output for @C # (for some reason the @C=grep doesn't work here) ;0 } else { 1 } # no more words, done! } ``` And finally, this subroutine is given a word and the sentence histogram. It calculates a new histogram for the word and checks whether all letters do not occur more often than permitted by the sentence histogram. ``` # check if first histogram is within bounds of second sub h{ ($y,$z)=@_; my%T; $z =~ s/\w/$T{$&}++/eg; # calc histogram $K=1; $K &= $T{$_} <= $y->{$_} for keys %T;#$_[0]; $K } ``` You can paste the ungolfed snippets (`sub i/o/g/h`) in a single file and append the below test code. ``` sub t { print $i=i(shift),$/,o($i),$/x2; %c=%h=@L=@X=@O=(); } t "Test."; # Test. t "Zulus win."; # Zulus win. t "Happy solstice."; # Happy solstice. t "Abash abel mammal test."; # Abase alms embalm that. t "Dovecot flagships oleander."; # Dangled horoscope festival. t 'This code requires further golfing.';# Tech deer fighting ferrous liquors. ``` --- * *update 504*: save 12 bytes eliminating a `substr` and a parameter for `sub g`. ]
[Question] [ A polynomial is divisible by a factor `(x-n)` if `f(n)=0` for a function `f`. Your job: to determine if a polynomial function `f(x)` is divisible by `(x-n)`. # The input The input is in the form of `(x-n), (Polynomial)`. **Remember, if n is negative, `(x-n)` will be in the input form of `(x+n)`**. For the polynomial, all exponents will be put in as `^`. Coefficients will be written next to the variable `x`. An example polynomial could be `2x^2 + x^1`. There will be no spaces between anything. The term `x` will be inputed as `x^1`. So what would "normally" look like `(x - 1)` will be `(x^1-1)`. The coefficients and powers will **always** be integers. **The coefficient one will be implicit if it is just `x`. I.e., `x` can be interpreted as `1x`** # The output A boolean value. Truthy, or Falsey. *Thanks to @AlexA. For helping me clarify this!* # Examples ``` Input:(x^1-1),(x^1-1) Output: True Input: (x^1+2),(2x^2+4x^1+2) Output: False Input: (x^1+7),(x^2-49) Output: True ``` ### Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins Unfortunately, I don't know how to implement the snippet leaderboard. If anyone knows how, feel free to edit the post. [Answer] # Pyth - 39 bytes This is a monstrous combination of regexp and eval. I like the approach, but will try to improve the implementation. It uses the [Polynomial Remainder Theorem](https://en.wikipedia.org/wiki/Polynomial_remainder_theorem). ``` K_sPe:z"-|\+"3!v.ssXPtw,\^\x,"**""*K"\* ``` Doesn't work online because of eval use. [Answer] # Casio Basic, 19 bytes ``` judge(mod(b,a)=0 ``` As it turns out, the fx-CP400 can do `mod` on algebraic expressions! Polynomial and factor should be entered as expressions. 16 bytes for the code, 3 bytes to enter `a,b` into the parameter value box. [Answer] # MATLAB, ~~103 99 97 95~~ 93 bytes I'm trying some different things, and got this to work to save a couple of bytes: ``` eval([regexprep(input(''),{'.+?1(.+)\),','(\d)x'},{'x=str2num(''$1'');disp(~','$1\*x'}) 41]); ``` If I can reduce that down even further, I will post an explanation. --- Old code an explanation ``` t=sscanf(input(''),'(x^1%d),%s')';x=-t(1);disp(~eval(regexprep([t(2:end) ''],'(\d)x','$1\*x'))) ``` This also works with **Octave**. You can [try it online](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). I've save the program as a script named `isFactor.m`, so you can just enter `isFactor` at the prompt. [Note: in Octave spits out a warning while running - MATLAB doesn't generate this]. The input must be in the format `'(x^1+7),(x^2-49)'` as per the question. The quotes marks are added so MATLAB/Octave knows it is a string. The output is either a `0` or a `1` depending on whether or not it is true or false. --- So, the code works as follows. First we request an input, and then parse it. The parsing string extracts the signed number after the first `(x^1` in the string - this is our value of `n`. Then it continues to extract the string (`%s`) after the `),` in the input - this is our expression. ``` t=sscanf(input(''),'(x^1%d),%s')'; ``` Next, we extract the value of `n` and set `x` equal to it - we are going to evaluate whether the expression equals zero when `n==x`, so this is why we store the value to x. Also we negate the extracted number, because of the minus sign when parsing. ``` x=-t(1); ``` We will then display the output which is a boolean ``` disp( ``` The output is basically the logical negation of our evaluated equation. If `f(x)` is zero, this will return 1, otherwise it will result in zero. ``` ~eval( ``` We are evaluating the input expression, but to do this, we need to reformat it slightly so that MATLAB can understand. When we read the string, it is actually an array of `double` type, so we need to convert that to a character array. Before the conversion we also get rid of the first element as that is what we used for `n`. We then need to replace any occurrence of `x` which is preceded by a number (e.g `4x`) by the same thing but with a multiplication (`*`) sign in between so MATLAB can calculate it. ``` regexprep(char([t(2:end) ''],'(\d)x','$1\*x') ) ) ``` [Answer] # VBScript, ~~118~~ 116 bytes ``` a=inputbox(""):for i=0 to 9:a=replace(a,i&"x",i&"*x"):next:b=split(a,","):x=-eval(b(0)):msgbox not cbool(eval(b(1))) ``` Since we know that the first part of the input is a linear polynomial, we only need to check if its root matches that of the second polynomial; and we need to prepare the term for `eval` by inserting `*` as needed. [Answer] # Axiom ~~77~~ 180 Bytes ``` f(a:UP(x,INT),b:UP(x,INT)):Boolean==(ground?(a)or ground?(b)=>false;p:=b;r:=a;if degree(a::POLY INT,x)>degree(b::POLY INT,x)then(p:=a;r:=b);(p rem r)$UP(x,FRAC INT)~=0=>false;true) ``` the previous solution ``` v(a,b)==(ground?(a) or ground?(b) or (b rem a)$UP(x,FRAC INT)~=0=>false;true) ``` was wrong because it assume degree(b)>=degree(a) one bug i wrote... test and results ``` (3) -> f(x^1-1,x^1-1) (3) true Type: Boolean (4) -> f(x^1+1,2*x^2+4*x^1+2) (4) true Type: Boolean (5) -> f(x^1+2,2*x^2+4*x^1+2) (5) false Type: Boolean (6) -> f(x^1+7,x^2-49) (6) true Type: Boolean (7) -> f(1, 1) (7) false Type: Boolean (8) -> f(1, x^2+1) (8) false Type: Boolean (9) -> f(x^8-1, x^2-1) (9) true ``` [Answer] # Mathematica, 30 bytes [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6ZgqxDzPyA/pzIvPzczMScIKJGZl5JaFK1spKOsUxFrY6j2Py1aoyLOUEFXwVBTRwHOjFXQ1w8oyswr4YLKaysYgeSNFCrijIAcEwWYIBaV5hCTjIAmmVgiFPwHAA) ``` PolynomialRemainder[#2,#,x]<1& ``` ]
[Question] [ Your boss has found out that quite a bunch of his employees (including you) like to steal code from others. He ordered you to write him a program that he can use to find people who steal code from others. ## Task: Write a program/function that detects if somebody copied (part of) his code from somewhere else. The program will get all the *existing programs and the program that it should test from two separate inputs*. **Edit:** Since there are no answers so far, you may use regular expressions! ## Output * The program should then output **all** the stolen pieces of code, separated by either a space or a newline. (It may have a space or a newline at the end.) * A piece of code is considered to be stolen/copied if it consists of 10 or more *successive* bytes. (Sorry, Java fans!) * You have to output as much as possible, but if there are overlapping ones, you may ignore one of them or output both of them. ## Twist: As mentioned before, you also love duct tape coding. That means, **everything** in your code will be copy-pasted from a stack exchange site! You can copy whatever you want (not limited to code in code blocks) and as much as you want. (But at least 10 bytes) (Same rule as above about what is considered to be stolen/copied.) (Please do note that any answers that were posted after this question may not be used.) Please provide links to where you got your code from. ## Examples: **Input:** `x = document.getElementById("ninja'd");` (The first input) `y = document.getElementById("id");` (The second input) **Output:** ``` = document.getElementById(" ``` **Input:** `foo` (The first input) `foo+bar` (The second input) **Output:** Nothing. **Input:** `public static void main(String[] args)` (The first input) `public static void main(String[] args)` (The second input) **Output:** ``` main(String[] args) ``` **Input:** `for(var i=0; i<x.length; i++){}` (The first input) `for(var i=0; i<oops.length; i++){break;}` (The second input) **Output:** ``` for(var i=0; i< .length; i++){ ``` or ``` for(var i=0; i< .length; i++){ ``` [Answer] # Python 2, 224 bytes ``` from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).get_matching_blocks() a=raw_input() b=raw_input() for start, _, size in similar(a, b): if(size > 9): print a[start:start+size] ``` Copied from [this answer](https://stackoverflow.com/questions/17388213/find-the-similarity-percent-between-two-strings/17388505#17388505): ``` from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b). ``` `get_matching_blocks()` is copied from [this answer](https://stackoverflow.com/questions/14546862/python-find-the-closest-matching-sentence/14546975#14546975) ``` a=raw_input() b=raw_input() ``` is copied from [this question](https://stackoverflow.com/questions/23221505/python-error-talentbuddyeoferror-eof-when-reading-a-line) `for start, _, size in` is copied from [this answer](https://stackoverflow.com/questions/31517381/python-comparing-order-of-list-without-sorting-existing-data/31517872#31517872) and the second occurence of `similar(a, b)` is copied from the same place as the first. `if(size > 9)` is copied from [this question](https://stackoverflow.com/questions/18583176/ascii-art-with-java-creating-a-square-rectangle-with-different-symbolled-edges). ``` : print ``` is copied from [this question](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) `a[start:` is copied from [this answer](https://stackoverflow.com/questions/509211/explain-slice-notation/509295#509295). and finally, `start+size]` is copied from [this questipn](https://stackoverflow.com/questions/27181453/quick-sort-in-python) Finally answered after one and a half years ... ]
[Question] [ ## Introduction Lately, I've been getting used to typing with [Swype](http://en.wikipedia.org/wiki/Swype). I've noticed certain words can be produced by drawing a straight line from your starting letter to your ending letter, or by skipping letters that repeat. For example, I can type the word `balloon` by Swyping across the following letters: `b` > `a` > `l` > `o` > `n`. ## Challenge Let us define the **Shortest Swype Path**, or `SSP`, as the minimum number of distinguishable line segments needed to type a string. A line segment is a continuous straight line between any two, or more, letters. Any change in direction starts a new line segment - though some words may be Swyped by drawing only a single straight line. Use this simple [QWERTY](http://en.wikipedia.org/wiki/QWERTY) keyboard layout: ``` q w e r t y u i o p a s d f g h j k l z x c v b n m ``` In the above example, the word `balloon` will have an `SSP` of `4` as detailed in the sequence below: ``` 1) Start at `b` (line segments = 0) 2) slide to `a` (line segments = 1) 3) slide to `l` (line segments = 2) 4) slide to `o` (line segments = 3) 5) slide to `n` (line segments = 4) ``` The string `qwerty` has `SSP` = 1 since no change of direction is required when Swyping this word. ## Input A single word string containing any `a-z` via STDIN, function argument, or command line. ## Output Print via STDOUT, return, or your languages closest alternative, the number `n` representing the string's `SSP`. One trailing newline optional in outut. Standard loopholes disallowed. Shortest submission in bytes wins. ## Notes * A change in direction starts a new line segment. * Letters that repeat are only counted once (e.g.: `bookkeeper` should be treated as `bokeper`). * Normally, Swpye corrects missed letters by looking at neighboring letters and filling in its best guess. For this challenge, assume there is no natural language augmentations, predictive text or error correction. * Uppercase `A-Z` inputs are treated like their lowercase counterparts. * Ignore any numbers `0-9` in the input. * Diagonal paths are allowed - that is, a straight line that covers letters `o`, `k`, `n`, for example, count as `1` segment. This rule applies to any diagonal slope (e.g.: letters `c`, `h`, `i` are in line). ## Examples ``` Input Output --------------------- a 0 aa 0 aaaaaa 0 aaaaaabc 2 in 1 int 2 java 3 qwerty 1 chicago 5 balloon 4 BALLOON 4 typewriter 5 bookkeeper 6 stackexchange 11 2hello7 3 2HELLO7 3 ``` [Answer] # CJam, ~~78~~ ~~76~~ ~~73~~ ~~68~~ 62 bytes ``` relA,s-:_2ew{:-},{{i"x8LÑejPG ÀÏi"225b28b=A+Ab}/.-:ma}%e`, ``` Note that the code contains unprintable characters. *Borrowing @isaacg's clever idea of using RLE to count the paths saved 6 bytes.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=relA%2Cs-%3A_2ew%7B%3A-%7D%2C%7B%7Bi%22x8L%C3%91ejPG%20%C3%80%C2%81%C3%8F%C2%99i%C2%9F%C2%96%22225b28b%3DA%2BAb%7D%2F.-%3Ama%7D%25e%60%2C&input=stackexchange). If the link doesn't work, copy the code from this [paste](http://pastebin.com/VjQuK7yx). ### How it works ``` rel e# Read a token from STDIN and cast it to lowercase. A,s- e# Remove all digits. :_ e# Duplicate each element of the argument (string/array). 2ew e# Push all overlapping slices of length 2. {:-}, e# Filter out slices where both elements are equal. { e# For each slice: { e# For each character of the slice: i e# Push its code point. "x8LÑejPG ÀÏi"225b28b e# Convert the string from base 225 to base 28, pushing the array e# [15 7 16 17 18 27 26 8 9 0 3 11 4 6 24 1 22 5 21 10 25 23 12 2 13 14]. e# These are the positions on the QWERTY keyboard, starting from the e# upper left corner and going right. = e# Select the element that corresponds to the code point. e# Arrays wrap around in CJam. Since 'a' has code point 97, the array has e# length 26 and 97 % 26 == 19, 'a' corresponds to the 20th element. A+Ab e# Add 10 and convert to base 10. Example: 8 -> [1 8] }/ e# .- e# Vectorized subtraction. [a b] [c d] -> [a-c b-d] :ma e# atan2. Pushes the angle of the direction. [y x] -> arctan(y/x) }% e# e` e# Apply run-length encoding. , e# Count the runs. ``` [Answer] # Pyth, ~~53~~ ~~50~~ 49 bytes ``` lrPMfT-VJm.jF.D@jC"XÖ;¿ìÇ×;¤ð$ _"28CdT@GrzZtJ8 ``` Keyboard compression format thanks to @Dennis. This answer contains some unprintable characters. See the links below for the correct code. [Demonstration](https://pyth.herokuapp.com/?code=lrPMfT-VJm.jF.D%40jC%22%11X%C3%96%3B%C2%8B%C2%BF%C3%AC%C3%87%C3%97%3B%C2%A4%C3%B0%24%09_%C2%9A%2228CdT%40GrzZtJ8&input=bookkeeper&debug=0). [Test Harness.](https://pyth.herokuapp.com/?code=FN%2Bz.z%3DzhcN)%2CNlrPMfT-VJm.jF.D%40jC%22%11X%C3%96%3B%C2%8B%C2%BF%C3%AC%C3%87%C3%97%3B%C2%A4%C3%B0%24%09_%C2%9A%2228CdT%40GrzZtJ8&input=a++++++++++++++++0%0Aaa+++++++++++++++0%0Aaaaaaa+++++++++++0%0Aaaaaaabc+++++++++2%0Ain+++++++++++++++1%0Aint++++++++++++++2%0Ajava+++++++++++++3%0Aqwerty+++++++++++1%0Achicago++++++++++5%0Aballoon++++++++++4%0ABALLOON++++++++++4%0Atypewriter+++++++5%0Abookkeeper+++++++6%0Astackexchange++++11%0A2hello7++++++++++3%0A2HELLO7++++++++++3&debug=0) Explanation: ``` lrPMfT-VJm.jF.D@jC"..."28CdT@GrzZtJ8 rzZ Convert input to lowercase. @G Take the intersection with G. This removes the numbers. m Map over the characters C"..." Treat the string as a base 256 number. j 28 Convert this number to base 28, giving: [15, 7, 16, 17, 18, 27, 26, ... ] which is the character positions from top left, rotated by 97 places. @ Cd Index this list by ord(character) .D T divmod by 10, giving the x-y position. .jF Convert this to a complex number. J Save the result to J. -VJ tJ Vectorize - over J and J[1:]. This gives pairwise diffeences between J's elements. fT Filter the differences on being truthy. This removes letter pairs with no movement. PM Map the remaining complex numbers to their phases, which indicates their directions. r 8 Run-length encode the result. l Print out the number of separate RLE groups. ``` ]
[Question] [ I am curious if I am Code Golfing properly. I set the challenge for myself to make a small hashing program into a single statement in Python. I first started off with: ``` from itertools import permutations from string import ascii_lowercase from random import sample def test(): chars = sample(ascii_lowercase, 9) sums = list(map(h, permutations(chars))) if len(set(sums)) == len(sums): print("unique results for permutations of given string") else: print("duplicate entries present in test results") def h(s): r = 0 for i in range(len(s)): r += ord(s[i]) << (i * len(s)) return r test() ``` I then made the function recursive: ``` def h(s, i=0): if i < len(s) - 1: return h(s, i+1) + ord(s[i]) << (i * len(s)) else: return ord(s[i]) << (i * len(s)) ``` I tried shortening it with a lambda for repeating code (it didn't work): ``` def h(s, i=0, f=lambda s,i: ord(s[i]) << (i * len(s))): if i < len(s) - 1: return h(s, i+1) + f(s,i) else: return f(s,i) ``` Finally I ended up with a lambda: ``` h=lambda s,i=0:h(s,i+1)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)) ``` I wanted the program to be one statement, so first I came up with: ``` def test(): chars = sample(ascii_lowercase, 9) sums = list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(chars))) if len(set(sums)) == len(sums): print("unique results for permutations of given string") else: print("duplicate entries present in test results") ``` And lastly I ended up with: ``` print((lambda x=list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(sample(ascii_lowercase, 9)))): "unique results for permutations of given string" if len(set(x)) == len(x) else "duplicate entries present in test results")()) ``` Is this how codegolf problems are worked out? I've never really done this sort of thing, so right now I just want to know if I am doing it right. **Amendment:** This program does all the work for you; so I will here refer to the function: As input, the program takes in all the permutations of a given string; here the string is nine characters randomly picked from `ascii_lowercase`. The output is a human-readable string defining whether the result of each permutation of the given string is a duplicate of another result for a different string. If there are no duplicates for all permutations, the program indicates success. Nine characters was picked as being the largest length of characters readily computed repeatedly on my box. **Amendment II** As pointed out by a studious reader, the intended purpose described is not obtained through the accompanying code. The test case is obviously inadequate. [Answer] There is no 'right' way to golf. You've done well, and the process you've used is fairly standard. Making the program into one statement isn't usually a requirement though. If it helps, here's how I would approach golfing down your program... In the hashing function, the for statement can be replaced with a sum: ``` def h(s): r = 0 r = sum(ord(s[i]) << (i * len(s)) for i in range(len(s))) return r ``` This can then be defined as a lambda function: ``` h = lambda s: sum(ord(s[i]) << (i * len(s)) for i in range(len(s))) ``` And now we remove unnecessary spaces and brackets: ``` h=lambda s:sum(ord(s[i])<<i*len(s)for i in range(len(s))) ``` As Sp3000 pointed out, this can be shortened further with enumerate: ``` h=lambda s:sum(ord(x)<<i*len(s)for i,x in enumerate(s)) ``` Moving on to the test function, we merge its first two lines: ``` def test(): sums = list(map(h, permutations(sample(ascii_lowercase, 9)))) ... ``` Since both functions are only used once, we can move everything inline: ``` sums = list(map(lambda s:sum(ord(x)<<i*len(s)for i,x in enumerate(s)), permutations(sample(ascii_lowercase, 9)))) ... ``` This is shorter as a list comprehension: ``` sums = [sum(ord(x)<<i*len(s)for i,x in enumerate(s)) for s in permutations(sample(ascii_lowercase, 9))] ``` Next, we give it a shorter name and remove unnecessary spaces again: ``` x=[sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))] ``` The if statement can be moved inside the print function: ``` print('unique...' if len(set(x)) == len(x) else 'duplicate...') ``` However, it's usually shorter to use and/or: ``` print(len(set(x)) == len(x) and 'unique...' or 'duplicate...') ``` Since `len(x)` doesn't change, we can calculate and hardcode its value: ``` print(len(set(x)) == 362880 and 'unique...' or 'duplicate...') ``` After removing unnecessary spaces and switching around the comparison, we get: ``` print(len(set(x))<362880and'duplicate...'or'unique...') ``` This lets us move everything into one statement: ``` print(len(set([sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))]))<362880and'duplicate...'or'unique...') ``` And now we can use a set comprehension instead: ``` print(len({sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))})<362880and'duplicate...'or'unique...') ``` The result is 210 bytes, excluding imports. The next step would probably be to golf down the imports or the long strings. ]
[Question] [ Imagine a rectangular grid of `|` characters represents the taut strings on a loom ([the warp](http://en.wikipedia.org/wiki/Warp_(weaving))) that other threads ([the weft](http://en.wikipedia.org/wiki/Weft)), which we will represent as `-`, can be woven around. Here is the unwoven warp of a 7×4 loom: ``` ||||||| ||||||| ||||||| ||||||| ``` There are a number of ways the weft can be woven into the warp, the simplest being the [plain weave](http://en.wikipedia.org/wiki/Plain_weave). In the first row of a plain weave the weft starts above the first warp string, goes below the second string, then above the third string, then below the fourth, and so on. The second weft row is identical to the first but offset to the right by one warp string, so it starts under then goes over, and so on. On our 7×4 loom the plain weave looks like this: ``` -|-|-|- |-|-|-| -|-|-|- |-|-|-| ``` We can describe the plain weave by saying that the weft goes over the warp *1* time, then under *1* time, and each subsequent row is shifted *1* string to the right. A generalized weave can be described by having the weft go over the warp *v* times, then under *u* times, with each subsequent row shifted by *s* strings to the right. (All values are integers, *s* may be 0 or negative, *u* and *v* must be non-negative.) A 7×4 loom with *v = 1*, *u = 2*, *s = 2*, a type of [twill weave](http://en.wikipedia.org/wiki/Twill): ``` -||-||- ||-||-| |-||-|| -||-||- ``` # Challenge Your task is to write the shortest program (in bytes) that produces a woven pattern of bars and dashes given *v*, *u*, *s*, the width and height of the loom, and the *initial shift*. The *initial shift* is the number of strings the first row in the weft is shifted to the right (0 in the examples above). Each subsequent row is shifted by *s* more strings. Your program should take in these 6 numbers in some easy to use format (stdin, a function call, etc.) and output the woven grid of bars and rectangles to stdout. You may assume all input is valid. (All values are integers, width and height must be positive, *initial shift* may be anything.) # Examples *width = 5, height = 4, initial shift = 0, v = 1, u = 3, s = -2:* ``` -|||- ||-|| -|||- ||-|| ``` *width = 5, height = 4, initial shift = 3, v = 1, u = 3, s = -2:* ``` |||-| |-||| |||-| |-||| ``` *width = 5, height = 4, initial shift = 1, v = 1, u = 1, s = 0:* ``` |-|-| |-|-| |-|-| |-|-| ``` *width = 5, height = 4, initial shift = 0, v = 1, u = 0, s = 0:* ``` ----- ----- ----- ----- ``` # Notes * The pattern always starts with the weft over the warp at the top left corner of the grid (unless initially shifted). * All the weft threads come in from the left. They **do not** spiral like [this](http://upload.wikimedia.org/wikipedia/en/e/ea/Warp_and_weft.jpg). * *u + v* is not necessarily a multiple of the grid width. * *u* and *v* may not both be 0 [Answer] ## Ruby, 72 bytes ``` w,h,v,u,s,i=$*.map &:to_i;h.times{puts ((?-*v+?|*u)*w)[-i%(u+v),w];i+=s} ``` Not a lot to say about this. I build one repetition of `-` and `|`, repeat it `w` times (just to be sure), and the I slice out the appropriate section for each line. [Answer] # JavaScript (ES 6) 128 ``` F=(w,h,i,v,u,s)=>{for(x=('-'[R='repeat'](v)+'|'[R](u))[R](w*h),l=v+u,i=-i%l+l,s=-s%l+l;h--;i+=s)console.log(x.substr(i,w)+'\n')} ``` **Test** ``` F(11,8,2,5,3,-2) ||-----|||- -----|||--- ---|||----- -|||-----|| ||-----|||- -----|||--- ---|||----- -|||-----|| ``` [Answer] # Python, 92 bytes ``` w,h,i,v,u,s=eval(A) x=('|'*u+'-'*v)*w while h:print(x[-i:]+x[:-i])[-w:];x=x[-s:]+x[:-s];h-=1 ``` Hmm... So tempted to learn ruby now. Input by assigning a string variable in this format: "width, height, initial shift, v, u, s". Paste before the program: ``` A="80,80,0,2,2,-9" ``` [Answer] # JavaScript (ES6), 111 bytes A slightly different ES6 approach, using the functional Array.from. `f` takes arguments `(w,h,i,v,u,s)` and returns a string. Newlines added to code and literal newline in string replaced by `\n` for clarity; neither reflected in byte count. ``` f=(w,h,i,v,u,s)=>(A=Array).from(A(h),(_,j)=>A.from(A(w), (_,k)=>(j*((x=v+u)-s)+x+k-i)%x<v?'-':'|').join``).join`\n` ``` ## Usage ``` console.log(f(5,4,0,1,3,-2)) /* -|||- ||-|| -|||- ||-|| */ ``` ## Ungolfed version with explanation I saved some bytes by creating an alias for Array, which is not reflected in the ungolfed version. ``` // take input and create an array of length h (height): f = (w,h,i,v,u,s) => Array.from( Array(h), // in each row position j, create an array of length w (width): (_,j) => Array.from( Array(w), // in each cell, place - or | depending on the pattern (i,v,u,s) // and current position (j,k): (_,k) => ( j * ( ( x = v + u ) - s ) + x + k - i ) % x < v ? '-' : '|' // turn each row into a string: ).join`` // join rows with newlines: ).join`\n` ``` [Answer] # C, 357 bytes ``` #include<stdio.h> int w,h,t,v,u,s,i,j,l,f;int main(){scanf("%d %d %d %d %d %d",&w,&h,&t,&v,&u,&s);l=v+u;char g[l];g[l]='\0';f=0;while(u--){g[v+u]='|';}while(v--){g[v]='-';}for(i=0;i<h;i++){for(j=0;j<w;j++){printf("%c",g[abs(t+f+j)%l]);}printf("\n");f-=s;}} ``` "It's more comfortable than it looks." "It would have to be." -- Gia and Eidon (No one's going to get this reference. Hint: "Weave Mat") So I've been working on and off on this for about five hours now, and I give up. I have no idea how to get this code to work. It keeps going backwards after the first row, and then gets entirely wrong (7 4 0 2 2 1). Here's the simpler version you can read more easily. All I do is retrieve input, make the template array, and then print within the loops. ``` #include<stdio.h> int w,h,t,v,u,s,i,j,l,f; int main(){ scanf("%d %d %d %d %d %d",&w,&h,&t,&v,&u,&s); l=v+u;char g[l];g[l]='\0';f=0; while(u--){g[v+u]='|';}while(v--){g[v]='-';} for(i=0;i<h;i++){ for(j=0;j<w;j++){ printf("%c",g[abs(t+f+j)%l]); // THIS is the line that needs help. } printf("\n"); f-=s; } } ``` You can easily test it here: <http://www.compileonline.com/compile_c_online.php> using "7 4 0 1 1 1" in the STDIN Input box at the bottom. Start editing the numbers, and you'll see the problems. Sorry I couldn't come up with a working solution; I'm hating myself for this. I've spent too much time to not upload it to have someone else fix. I've been using this printf for a while to further separate the top row (easy) to the rest of them (the problem rows): `printf("%c",g[i?abs(t+f+j)%l:abs(t+j)%l]);` [Answer] # Haskell, 126 bytes ``` f w h i v u s=putStr.unlines$take h$take w<$>(iterate(drop(mod s(u+v)))$drop(mod(-i)(u+v)).cycle$('-'<$[1..v])++('|'<$[1..u])) ``` ]
[Question] [ Your challenge today is to cheat at badges! You will build a bot that will connect to a Stack Exchange site, log in as you, visit the /questions page, visit a question, and then visit 9 other questions in the "related" sidebar (because that seems sufficient to count as "activity," and I need to standardize on something). This bot must go through this process once every day, without any input or actions from the user. It should be able to be left running, and the user should be able to never touch the computer, and the consecutive days count will still be incremented. After "visiting" the site, it must print "visited". You will assume that the user is using the Stack Exchange-provided OpenID. The input of the program will be the site URL, SE OpenID email, and SE OpenID password. For example: ``` https://stackoverflow.com/ [[email protected]](/cdn-cgi/l/email-protection) password ``` You can input these however you would like. Your program must work for a minimum of: * <https://stackoverflow.com/> * <https://meta.stackoverflow.com/> * <https://superuser.com/> * <https://codegolf.stackexchange.com/> (Just to make sure it is universal.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] # Ruby, 456 characters ``` require'mechanize' s,*e=gets.split a,o=Mechanize.new,'http://openid.stackexchange.com/' a.agent.http.verify_mode=OpenSSL::SSL::VERIFY_NONE l=a.get(o+'account/login').forms[0] l.email,l.password=e a.submit l,l.buttons[0] g=a.get(s+'/users/login').forms.find{|f|f.action=='/users/authenticate'} g.openid_identifier=o a.submit g,g.buttons[-1] loop{p=a.get s+'/questions' 10.times{p=p.links.find{|i|i.href=~/^\/questions\/\d/}.click} puts'visited' sleep 86400} ``` Ungolfed version: ``` require 'mechanize' site, email, password = gets.split agent = Mechanize.new agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE login_form = agent.get('http://openid.stackexchange.com/account/login').forms.first login_form.email = email login_form.password = password agent.submit login_form, login_form.buttons.first puts 'logged in with SE openid' site_login_form = agent.get(site + '/users/login').forms.find {|form| form.action == '/users/authenticate' } site_login_form.openid_identifier = 'http://openid.stackexchange.com/' agent.submit site_login_form, site_login_form.buttons.last puts 'logged in to site' loop { page = agent.get(site + '/questions') 10.times do page = page.links.find{|link| link.href =~ /^\/questions\/\d/ }.click; end puts 'visited' sleep 60 * 60 * 24 } ``` ]
[Question] [ The challenge is to [parse a string like Python does](http://docs.python.org/2/reference/lexical_analysis.html#string-literals) and print the contents of the string. * **Input (command-line argument or stdin)**: a string literal (e.g. `"hello"`) (or multiple literals, see *string literal concatenation* below) * **Output (stdout)**: the contents of the string (e.g. `hello`) **Rules for parsing the string:** * A string literal is enclosed in matching pairs of single quotes (`'a'`), double quotes (`"a"`), triple single quotes (`'''a'''`) or triple double quotes (`"""a"""`). The first reoccurrence of the type of quotes that opened the string ends the string. * **Backslash escapes:** `\'` within a string becomes `'`, `\"` becomes `"` and `\\` becomes `\`. You do not need to implement any other backslash escapes. A backslash that is not part of an escape sequence stays a backslash. * **String literal concatenation:** The contents of adjacent string literals are concatenated. For example, `"hello" 'world'` becomes `helloworld`. * The input may contain spaces that are not part of any literal. * You do not need to support any other kind of whitespace, neither within nor outside literals. **Additional rules:** * **`eval`, `exec` and similar stuff is not allowed** for parsing the literal or parts of it. * You may assume that the input is valid. * You may assume a maximum input length of 1023 characters. **Examples:** * `"hello" ' world'` -> `hello world` * `"""\"""'\\\A"""` -> `"""'\\A` * `( '''"""'''"""'''""" )` (without parentheses, but with spaces) -> `"""'''` Shortest code wins. [Answer] ## Perl, 54 characters ``` #!/usr/bin/perl -p s/ |("""|'''|"|')((\\?.)*?)\1/$2/g;s/\\(["'\\])/$1/g ``` Just as I was posting this, I noticed that it's almost identical to Jan Dvorak's Ruby solution. I'm a little put out by how similar it is, in fact, but I'm going to say "Great minds think alike" and let it go at that. This program highlights a weird corner case in counting characters in Perl scripts: By my reading, the presence of single-quotes in the script means that I need to count the `-p` option as two characters towards my total. Typically, when computing Perl script sizes, the initial dash character on the options is considered to be free, on the justification that it can be bundled with the `-e` that introduces the program proper ... but then you also have to account for any extra escapes you need to enter the script on the command-line. The single-quotes require lots of escaping, so to avoid that penalty I have to count it as a script run from a file, and therefore I get the `#!/usr/bin/perl` for free, but not any option characters. It's a little confusing. [Answer] ## C, 178 characters ``` char*p,*q,b[1024];d;main(t){for(p=q=gets(b);*p=*q++;) d?*p==92&!(*q-*p&&*q-34&&*q-39)?*p++=*q++:*p-d||t&&*q-d|q[1]-d?++p: (d=0,q+=2*t):*p-32?d=*p,t=*q==d&q[1]==d,q+=2*t:0;puts(b);} ``` This is one of those C solutions where everything is done inside a ternary-operator chain gang. The program works by copying characters back into the same buffer, overwriting the metacharacters. `d` holds the delimiter when inside of a string, and `t` is true if the delimiter is a triple-quote. [Answer] ### Ruby, ~~74~~ 73 characters ``` puts gets.gsub(/('''|"""|'|")((\\?.)*?)\1|./,'\2').gsub /\\([\\'"])/,'\1' ``` The core here are two regexes: The first one determines the string boundaries and selects the contents only. The alteration is there to remove everything not inside strings, and it also drops unclosed strings. ~~Backslashes are treated as possesive-optional followed by anything. Thus,~~ Since the regex engine will not backtrack into `(\\?.)` for valid inputs (thanks @breadbox), a sole backslash cannot match there. Quotes are handled via lazy repetition. The second regex then strips a backslash before each escapeable character. The regex depends on the engine to always pick the leftmost alternative first. I have also considered a state-machine approach, but it turned out quite big (19 states x 4 character classes) compared to the regex solution. I can still post the state machine if anyone is interested. ]
[Question] [ (I've tagged the question "C" for the time being, but if you're aware of another language that supports unions, you can also use that.) Your task is to build the four standard mathematical operators `+ - * /` for the following struct: ``` union intfloat{ double f; uint8_t h[8]; uint16_t i[4]; uint32_t j[2]; uint64_t k; intfloat(double g){f = g;} intfloat(){k = 0;} } ``` such that the operations themselves only ever manipulate or access the integer part (so no comparing with the double anytime during the operation either), and the result is exactly the same (or functionally equivalent, in the case of non-numeric results such as `NaN`) as if the corresponding mathematical operation had been applied straight to the `double` instead. You may choose which integer part to manipulate, perhaps even using different ones among different operators. (You can also choose to remove the "unsigned" from any of the fields in the union, although I'm not sure whether you'd want to do that.) Your score is the sum of the length of code in characters for each of the four operators. Lowest score wins. For those of us unfamiliar with the IEEE 754 specification, [here](http://en.wikipedia.org/wiki/IEEE_754) is an article about it on Wikipedia. --- Edits: **03-06 08:47** Added constructors to the intfloat struct. You are allowed to use them for testing, rather than manually setting the double / etc. [Answer] ## C++, ~1500 chars Expands the floats into an 8000-binary-digit fixed-point representation, does the operations on that, then converts back. ``` // an "expanded" float. // n is nan, i is infinity, z is zero, s is sign. // nan overrides inf, inf overrides zero, zero overrides digits. // sign is valid unless nan. // We store the number in fixed-point, little-endian. Binary point is // at N/2. So 1.0 is N/2 zeros, one, N/2-1 zeros. #define N 8000 struct E { int n; int i; int z; long s; long d[N]; }; #define V if(r.n|r.i|r.z)return r // Converts a regular floating-point number to an expanded one. E R(F x){ long i,e=x.k<<1>>53,m=x.k<<12>>12; E r={e==2047&&m!=0,e==2047,e+m==0,x.k>>63}; if(e)m+=1L<<52;else e++; for(i=0;i<53;i++)r.d[2925+e+i]=m>>i&1; return r; } E A(E x,E y){ int i,c,v; if(x.s>y.s)return A(y,x); E r={x.n|y.n|x.i&y.i&(x.s^y.s),x.i|y.i,x.z&y.z,x.i&x.s|y.i&y.s|~x.i&~y.i&x.s&y.s};V; if(x.s^y.s){ c=0; r.z=1; for(i=0;i<N;i++){ v=x.d[i]-y.d[i]-c; r.d[i]=v&1;c=v<0; r.z&=~v&1; } if(c){x.s=1;y.s=0;r=A(y,x);r.s=1;} }else{ c=0; for(i=0;i<N;i++){ v=x.d[i]+y.d[i]+c; r.d[i]=v&1;c=v>1; } } return r; } E M(E x, E y){ int i; E r={x.n|y.n|x.i&y.z|x.z&y.i,x.i|y.i,x.z|y.z,x.s^y.s};V; E s={0,0,1}; for(i=0;i<6000;i++)y.d[i]=y.d[i+2000]; for(i=0;i<4000;i++){ if(x.d[i+2000])s=A(s,y); y=A(y,y); } s.s^=x.s; return s; } // 1/d using Newton-Raphson: // x <- x * (2 - d*x) E I(E d){ int i; E r={d.n,d.z,d.i,d.s};V; E t={};t.d[4001]=1; for(i=N-1;i>0;i--)if(d.d[i])break; E x={0,0,0,d.s};x.d[N-i]=1; d.s^=1; for(i=0;i<10;i++)x=M(x,A(t,M(d,x))); return x; } // Convert expanded number back to regular floating point. F C(E x){ long i,j,e,m=0; for(i=N-1;i>=0;i--)if(x.d[i])break; for(j=0;j<N;j++)if(x.d[j])break; if(i>0&x.d[i-53]&(j<i-53|x.d[i-52])){E y={0,0,0,x.s};y.d[i-53]=1;return C(A(x,y));} if(i<2978){e=0;for(j=0;j<52;j++)m+=x.d[j+2926]<<j;} else if(i<5024){e=i-2977;for(j=0;j<52;j++)m+=x.d[i+j-52]<<j;} else x.i=1; if(x.z)e=m=0; if(x.i){e=2047;m=0;} if(x.n)e=m=2047; F y;y.k=x.s<<63|e<<52|m;return y; } // expand, do op, unexpand F A(F x,F y){return C(A(R(x),R(y)));} F S(F x,F y){y.k^=1L<<63;return A(x,y);} F M(F x,F y){return C(M(R(x),R(y)));} F D(F x,F y){return C(M(R(x),I(R(y))));} ``` I'm too lazy to remove all the spaces and newlines to get an exact golfed count, but it is about 1500 characters. ]
[Question] [ ## The challenge Write a program that takes two integers from standard input, separated by a comma, and then prints a visualisation of long multiplication of those two integers to standard output. Eg: **Input** ``` 14, 11 ``` **Program output** ``` 14 x11 _____ 14 14 ______ 154 ``` **Input** ``` -7, 20 ``` **Program output** ``` -7 x20 _____ 00 14 _____ -140 ``` Assume always correct inputs and numbers in the range [-999, 999] ## Winning criteria Shortest code wins! [Answer] # Mathematica 213 217 197 193 186 184 193 184 177 **Code** ``` a_~g~b_ := With[{e = IntegerDigits@b}, Column[Flatten@{a, UnderBar["x " <> IntegerString[b]], Table[Row @@ {PadRight[{a Reverse[e][[i]]}, i, " "]}, {i, Length@e}], OverBar[a b]}, Alignment -> Right]] ``` **Usage** ``` g[845, 921] ``` ![multiply](https://i.stack.imgur.com/8dpWW.png) [Answer] ## Perl, 108 chars Best of breed 108 char solution, incorporating some ideas from Orabig. ``` ($x,$y)=<>=~/[-\d]+/g;printf"%7s ",$_ for$x,x.$y,"-"x7,(map{abs($x*$_).$"x$i++}reverse$y=~/\d/g),"-"x7,$x*$y ``` Earlier 139 char solution ``` sub P{sprintf"%*d",@_} ($x,$y)=<>=~/[^,]+/g;$,=$/; print P(7,$x)," x".P(4,$y),"-"x7,(map{P 7-$i++,abs$_*$x}reverse$y=~/\d/g), "-"x7,P 7,$x*$y ``` [Answer] Python, 174 170: ``` a,b=input();r,s=str(a),str(b);h=len(r+s)*'-';print'\n'.join(["%9s\n%9s\n%9s"%(r,'x'+s,h)]+["%%%ii"%(9-i)%(int(d)%10*a)for i,d in enumerate(s[::-1])]+["%9s\n%9i"%(h,a*b)]) ``` Usage: exactly as requested, run and input the values in standard input. To see running: <http://ideone.com/S8xNb> Output: ``` 1234 x5678 -------- 9872 8638 7404 6170 -------- 7006652 ``` Thanks to fabiocerqueira and beary605 and David Carraher [Answer] Python, 145, another answer with a little bit different output. **Code** ``` a,b=input();h=6*'-';print'\n'.join(["%6i\nx%5i\n%s"%(a,b,h)]+["%%%ii"%(6-i)%(int(d)%10*a)for i,d in enumerate(str(b)[::-1])]+["%s\n%6i"%(h,a*b)]) ``` **Usage** just as requested **Output** ``` 999 x 999 ------ 8991 8991 8991 ------ 998001 ``` To see running: <http://ideone.com/mdR18> [Answer] **Perl**, 157 151 150 144 141 133 chars : ``` ($x,$y)=<>=~/[-\d]+/g;map{$z=~s/z/ z/g;$z=(abs$x*$_)."z$z"}split//,abs$y;map{printf"%6s ",$_}$x,"x$y",$b="-"x6,(split/z/,$z),$b,$x*$y ``` **Usage :** ``` >echo "-123, 456" | perl mult.pl -123 x456 ------- 738 615 492 ------- -56088 ``` ]
[Question] [ Another date-manipulating problem :P ## Task > > Write a program or a function that calculates the difference between two dates given by a user. > > > ## Input & Output Similar to [the previous one](https://codegolf.stackexchange.com/q/2878/1477), inputs are two `YYYYMMDD`s, separated by a space , a comma `,`, or a minus sign `-`. Example of input values: ``` 20100101-20010911 20110620-20121223 19000101 20101010 33330101,19960229 00010101 99991231 ``` Output is an integer, which is difference between two dates, in days. For example, input `20110101-20100101` yields `365`, and `33320229 17000101` yields `596124`. You may test results ~~[at here](http://www.wolframalpha.com/input/?i=difference+between+1700%2F01%2F01+and+3332%2F02%2F29%2C+in+days)~~ [at here](http://www.timeanddate.com/date/duration.html). (See rintaun's comments below.) If two dates are same, the program should returns `0`, if the date is valid (see **Score**). ## Restriction Of course, you **must** not use **any** kinds of function/class/... which are related to timestamp or date, and you should use [Gregorian calender](http://en.wikipedia.org/wiki/Gregorian_calendar). ## Score If your code doesn't keep the restriction, then `score = -∞`. Default `bonus` is 1. * If your code works regardless of order of inputs (for example, `20100101,20110101` returns `365` or `-365`), `bonus+=1`. * If your code can handle [year 0](http://en.wikipedia.org/wiki/Year_0), `bonus+=0.5`. * If your code recognizes invalid month(between 1~12)/date(between 1~31), like `20109901` or `34720132`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`. * Regardless of above rule, if your code recognizes invalid dates, like `20100230`, `20100229`, or `20111131`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`. * Regardless of above two rules, if your code recognizes invalid input string, like `20100101|20100202` or `2010010120100202`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`. `score = floor(-4.2*code.length/bonus)`. Code with highest score wins. If two top codes have same score, then codes with highest bonus wins. If two top codes have both same score and bonus, then codes with highest votes wins. (Due: When there's more than 5 codes which has more than (or equal) `+1` votes.) [Answer] ## Perl 5.14, score = -162 -163 -181 -196 -214 -167 -213 -234 * code.length = 211: 208 source characters + 3 for running perl with the `-p` option * bonus = 5.5: default, order, year 0, never-valid month/day, invalid date, wholly-invalid input ### Code ``` $_=eval(join'-',map{($y,$m,$d)=/(....)(..)(..)/;die"E\n"if!($m*$d)||$m>12||$d>30+($m&1^$m>7)-($m==2)*(2-!($y=~s/00$//r%4));$y-=($m<3)-400;$d+int(($m+9)%12*30.6+.4)+int(365.2425*$y)}/^(\d{8})[ ,-](\d{8})$/)//E ``` Calculates a modified Julian day number for each date (ignoring the epoch-related adjustments to save code length) and subtracts the two. (ref. ["Julian Day" at Wikipedia](http://en.wikipedia.org/wiki/Julian_day#Converting_Gregorian_calendar_date_to_Julian_Day_Number)). * requires perl 5.14+ for the `/r` option on the substitutions * month-length calculation to get the invalid date bonus: the `30+($m&1^$m>7)` part gives the length of any month but February; the rest adjusts for February in an ordinary or leap year ### Assumptions * "use Gregorian calendar" means the proleptic Gregorian calendar for dates before whichever Julian to Gregorian transition we're using. That is, don't subtract 11 days for intervals that cross, for example, the 3 Sep 1752 - 14 Sep 1752 British transition. * "handle year 0" means, for example, `00000101-00010101` should give 366, as 0 is an integral multiple of 400, and so year 0 is a leap year. [Answer] # PHP, Score: -539.1 * 706 characters * All bonus items; bonus = 5.5 ## Code ``` <?php $a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])';@$p=preg_match;if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z))@die(E);unset($z[0]);sort($z);foreach($z AS$x){if(!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w))die(E);$n[]=$w;}$m=array(31,28,31,30,31,30,31,31,30,31,30,31);$r=0;$b=$n[0][1];$c=$n[0][2];$d=$n[0][3];$e=$n[1][1];$f=$n[1][2];$g=$n[1][3];@$t=str_pad;if((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12))die(E);for($z=$b.$c.$d;;$s=$d,$r++){if($z==$e.$f.$g)break;if($z>$e.$f.$g)@die(E);if(@$s==$d)$d++;if((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400))))){$c++;$d=1;}if($c>12){$b++;$c=1;}$z=$b.$t($c,2,0,0).$t($d,2,0,0);}echo($r>0)?--$r:0; ``` ### Ungolfed ``` <?php $a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])'; @$p=preg_match; if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z)) @die(E); unset($z[0]); sort($z); foreach($z AS $x) { if (!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w)) die(E); $n[]=$w; } $m=array(31,28,31,30,31,30,31,31,30,31,30,31); $r=0; $b=$n[0][1]; $c=$n[0][2]; $d=$n[0][3]; $e=$n[1][1]; $f=$n[1][2]; $g=$n[1][3]; @$t=str_pad; if ((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12)) die(E); for ($z=$b.$c.$d;;$s=$d,$r++) { if ($z==$e.$f.$g)break; if ($z>$e.$f.$g)@die(E); if (@$s==$d)$d++; if ((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400))))) { $c++; $d=1; } if ($c>12) { $b++; $c=1; } $z=$b.$t($c,2,0,0).$t($d,2,0,0); } echo($r>0)?--$r:0; ``` ## Note Calculates the number of days by iterating through each valid date between the two provided. It's pretty slow on larger ranges. I'm sure this isn't the best way to solve this, but I got impatient, and this is what I ended up with. :) Also, I know the "ungolfed" code still isn't very readable, but rewriting it completely would require too much effort. [Answer] ## Python, Score: -478 * characters: 455 * bonus: reverse dates, invalid day/month, invalid date solution: ``` import re a=re.split('[-, ]',raw_input()) def c(x):return x[0] def f(x,y=3):return(1if x%400==0 or x%100!=0and x%4==0 else 0)if y>2 else 0 t=[31,28,31,30,31,30,31,31,30,31,30,31] [q,w,e],[i,o,p]=sorted([map(int,[a[x][:4],a[x][4:6],a[x][6:]])for x in[0,1]],key=c) print sum(map(f,range(q,i)))+(i-q)*365+p+sum(t[:o-1])-e-sum(t[:w-1])+f(i,o)-f(q,w)if 0<w<13and 0<e<32and 0<o<13and 0<p<32and(e<=t[w-1]or(f(q)and e==29))and(p<=t[o-1]or(f(i)and p==29))else 'E' ``` I don't have "ungolfed" version as this is how I wrote it. I didn't test it properly so if you find a bug - please comment. edit: hopefully fixed a bug pointed out in a comments and added unpacking in form of [a,b],[c,d]=[[1,2],[3,4] [Answer] ## Ruby 1.9, Score: -175 -186 -191 -199 * Code length: 229 243 250 260 characters * Bonus: 5.5 (default, order, year 0, invalid month/day, invalid date, invalid input) The code accepts input through stdin. ``` h=->n{n/4-n/100+n/400+1} u,v=gets.split(/[ ,-]/).map{|s|s=~/^\d{8}$/?(d,e,f=[s[0,4],s[4,2],s[6,2]].map &:to_i;x=[0,y=31,28+h[d]-z=h[d-1]]+[y,30,y,30,y]*2 (!x[e]||e*f<1||f>x[e])?0:d*365+z+eval(x[0,e]*?+)+f):0} puts (v*u>0)?u-v :?E ``` Notes: * h returns the number of leap years up until that year (including year 0 for the bonus). * The regex handles the invalid input bonus. * The `(!x[e]||e*f<1||f>x[e])` condition handles the invalid month/day/date bonuses. * The result is displayed as the first date minus the second date, so if the second date is later it will output as a negative number. * Does not adjust for the change between Julian and Gregorian calendars, so `33320229 17000101` results in `596134`. [Answer] ## PHP, score: -516 chars : 685 676 bonus : 5.5 ``` <? $z='/((\d{1,4})(\d\d)(\d\d))[- ,]((\d{1,4})(\d\d)(\d\d))/';if(!preg_match($z,$argv[1],$m))die('E');$s=1;if($m[1]>$m[5]){if(!preg_match($z,"$m[5] $m[1]",$m))die('E');$s=-1;}$b=array(31,28,31,30,31,30,31,31,30,31,30,31);list($x,$v,$c,$d,$e,$w,$f,$g,$h)=$m;if($d>12||1>$d||$g>12||1>$g||1>$e||1>$h||($e>$b[$d-1]&&!($d==2&&$e<30&&$c%4==0))||($h>$b[$g-1]&&!($g==2&&$h<30&&$f%4==0)))die('E');$z='array_slice';$y='array_sum';$x=$d!=$g||$e>$h;$r=$x?$b[$d-1]+$h-$e:$h-$e;$d+=$x;if($d>12){$c++;$d=1;}$r+=$d>$g?$y($z($b,$d-1,13-$d))+$y($z($b,0,$g-1)):($d!=$g?$y($z($b,$d-1,$g-$d)):0);$r+=($f-$c-($d>$g))*365;for($i=$c;$i<=$f;$i++)if($i%4==0&&$i.'0229'>$v&&$i.'0229'<$w)$r++;echo $s*$r; ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 294 bytes, ~-353 score, +3.5 bonus ``` function J($s){if($s.length-ne8){"E";exit};iex ('$Y_0,4));$M_4,2));$D_6,2))'-replace'_','=[int]($s.substring(');$B=($M-14)/12;if($m-notin1..12){'E';exit};$A=$Y+4800;($J=1461*($A+$B)/4+367*($M-2-12*$B)/12-(3*(($A+$B+100)/100))/4+$D-32075)};[math]::truncate((J("$($args[0])"))-(J("$($args[1])"))) ``` [Try it online!](https://tio.run/##TY/RioMwEEV/pUggiRqbxKwtDT60tC9CP6CIiFtSDdhYNGUL0m93k919WAZmDpfLvcxj@FLj1Km@X5bb01ytHsyqQGDCs765k/TKtLYjRm3xHJwCqV7avqVWrxWC4FLTWGAswbkWMfdwrDMPkIzq0TdXBWsYw7zUxlY@bXp@TnbUpkXQmQ85AmfCBF4zLn3dnZjBasOShHE8wxP8qwP7HFwisaVUIlDkTGQsRGAfgQNeiyjNNqEP4oTx0EuME5SG6NcRMUqd5Jb3giNJOd184Lcs743tqt3Oju7vxiqEChQABJqxnUpa4QBj8l9iPxJeloVTxqgbD9TDNw "PowerShell – Try It Online") It uses Julian Date to calculate difference between to `YYYYMMDD` dates. **Explanation** * At first, to avoid redundant code, it's better to use a function. So we declare a function named `J` which calculates the julian date of a given date in `YYYYMMDD` format, and takes the parameter as `$s`. * Next, we need to check for invalid string. If the given string length is not 8 (`YYYYMMDD` length is 8), then output `E` and exit. * Parse the string. We used substrings for that. First 4 characters are the year (`$Y`), next 2 are the month (`$M`), and next 2 are the day (`$D`). To get a substring, we use .NET `.substring()` method for that, and cast it to type `[int]`. But its a huge part of code, and to golf it we replace `=[int]($s.substring(` with `_` and build a string `$Y_0,4));$M_4,2));$D_6,2))` and while in the code replace `_` with `=[int]($s.substring(` again and evaluate the expression using `iex` (Which is an alias of `Invoke-Expression`). * Another check for month validity. `1..12` is the array of numbers between `1` to `12`, if `$M` (month number) is not in the `1..12` array, we output `E` and exit. * Then the main logic goes. We calculate the Julian date. I found the algorithm [here](https://www.robvanderwoude.com/datetimentmath.php) * End the function. * We compute date difference after that. `$args` is an automatic array in Powershell which contains the parameters provided to the script (Not the function). We cast 0 and 1 index to string (`$()` operator is sub-expression operator, which evaluates a string as code inside a double-quoted string, and then surround double quotes to cast to string), pass each to `J` function and subtract the returned integer Julian dates. * At last, truncate the result using .NET `[math]::truncate()` method. **Bonus** * Initial bonus, so bonus +1 * The code will work if the first date is smaller than second one (i.e. `20100101 20110101`), so bonus +1 * Cannot handle year 0, so bonus +0 * Can handle invalid month, but not invalid Day, so bonus +0.5 * Cannot determine invalid dates, so bonus +0 * Can handle invalid strings in parameters, so bonus +1 Total: `1+1+0+0.5+0+1=3.5` **Total score** * Code length: 294 bytes * Total bonus: +3.5 $$ floor(-4.2\*294/3.5) = -353 $$ ]
[Question] [ [Whyte Notation](https://en.wikipedia.org/wiki/Whyte_notation) is a classification method mainly for steam locomotive, that classifies by wheel arrangement. On a steam locomotive ( we're only focusing on non articulated locomotives here ), the wheels are generally disposed like this : you have a specific number of leading wheels, then a specific number of driver wheels, and then a specific number of trailing wheels. On the top of that, each different wheel arrangement has its own name. For example, look at this machine : [![SNCF Class 141R](https://i.stack.imgur.com/CGz00.jpg)](https://i.stack.imgur.com/CGz00.jpg) It has 2 leading wheels ( 1 on each sides ), 8 driving wheels ( 4 on each sides ) and 2 trailing wheels ( 1 on each sides ) Its Whyte Notation would be 2-8-2, and its name associated with it is "Mikado". Based on the Whyte Notation, we can create a visual arrangement that can be represented by a string, with the `o` character as a small wheel ( leading wheel if in front of the driver wheels, else trailing ), and a caps `O` for the driver wheels Taking the previous locomotive as an example, its visual arrangement would be this : `oOOOOo`, with one small `o` on the front ( the leading wheels ), 4 caps `O` in the middle ( the driving wheels ), and one small `o` at the end ( the trailing wheels ) Here is the conversion table that we'll use to base the code on ( the table of entries that will have to be supported by your code ) : ``` Input | Output -------------+---------- oO | Planet oOo | Jenny Lind oOO | Porter oOOo | Columbian ooO | Jervis ooOoo | Huntington oooO | Cramton OO | Four-coupled OOo | Olomana OOoo | Forney ooOO | American ooOOo | Atlantic ooOOoo | Jubilee oOOO | Mogul oOOOo | Prairie oOOOoo | Adriatic ooOOO | Ten-wheeler ooOOOo | Pacific ooOOOoo | Hudson OOOO | Eight-coupled oOOOO | Consolidation oOOOOo | Mikado oOOOOoo | Berkshire ooOOOO | Mastodon ooOOOOo | Mountain ooOOOOoo | Northern oooOOOOooo | Turbine OOOOO | Ten-coupled OOOOOo | Union oOOOOO | Decapod ooOOOOO | El Gobernador ooOOOOOo | Overland oOOOOOo | Santa Fe oOOOOOOoo | Texas ooOOOOOOo | Union Pacific ooOOOOOOOoo | AA20 ``` ## Your task Your task is to write 2 programs of functions. ### First program / function : from arrangement to name The first function / program will be taking as input a string that exists in the table given previously, and will output the associated name ( for example, `oOOOOo` will return "Mikado" ). For the input, the only inputs you have to support are the one in the table previously given. Anything else that isn't in the table leads to undefined behavior. For the output, the string has to be the exact name, with the exception of case, which can be whatever you want. Trailing spaces are fine too. Examples of acceptable output : `Mikado`, `mikado`, `MIKADO` , `mIkAdO`, `Ten-wheeler` Examples of not acceptable output : `Mi Ka Do`, `Mikado`, `Tenwheeler`, `Ten_wheeler`, `Ten wheeler` ### Second program / function : the opposite This program of function will do the opposite of the first program, meaning that when given a name, it will print / return / output the string representing the wheel arrangement of the locomotive. As input, it will take whatever name existing in the "Output" part of the previously given table. Shall the name not exist, it leads to undefined behavior As output, it will give the exact string that represents the wheel arrangement, no flexibility allowed. So for example, `Mikado` as input must return `oOOOOo`. ## Global constraints Both of the programs have to be able to take as input the other program's output, and `func2(func1(wheel_arrangement_string))` has to be equal to `wheel_arrangement_string`. Same goes the other way, with `func1(funct2(wheel_arrangement_name))` that has to be equal to `wheel_arrangement_name`. Aside from that, standard I/O rules apply, and default loopholes are forbidden ## Additionnal Rules Programs and functions can call each others, and share calls to any additional functions or use any additional data you want, as long as they are included in the score ## Scoring rules Your score will simply be the sum of each program / function code sizes, as well as the size of any additional data / function required to make the code work. Each functions need to support all the entries listed in the table previously given. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 463 bytes A function that translates whatever string it is given in both directions. ``` s=>"5Planet2Four-coupled2Jervis1Jenny lind1Porter3Olomana3Cramton2American3Columbian1Mogul5Forney3Eight-coupled5Huntington2Atlantic1Ten-wheeler7Prairie1Consolidation16Ten-coupled13Jubilee2Pacific1Mastodon13Adriatic2Mikado1Decapod31Union30Hudson2Mountain1El gobernador29Berkshire2Santa fe126Northern2Overland320Union pacific126Texas380Turbine1412Aa20".replace(/(\d+)(....\D*)/g,(_,a,b)=>(a=(t+=+a).toString(2).replace(/./g,(n,i)=>i?'oO'[n]:''))==s?b:b==s?a:'',t=0) ``` [Try it online!](https://tio.run/##XVNLbtswEN37FIQXkVgrikklaZtADtLEQRDAtYGkK8coKIm22cqkQVFpg6I9QYFuumzv0fPkAj2CS1LUJ/XCgt68eTOjefOBPJAilWyr9rnI6G4Z74p41D@a5YRTha9EKfdTUW5zmuEbKh9YgW4o548gZzxDMyEVldE0FxvCSXQhyUYJjs83VLKU8OhC5OUmYYSjiViV@dGVkJw@RmO2Wqta9ui65IrxlU1UuqxiKbqjfP/TmtKcypczSZhkFF0IXoicZUQxwdGxoTgJFN2UCcspxTOSsqXOn5BCiUzTovNMMp2R4gn7SDKBLmlKtiKL0DuuZaLhdZkVuvJE6C4I42icg5VIqOSaLPHrN1R@LNZMUnyrOyNgSRE@fqvHXmsKnj5QqTvOIjy0cmDr6mPd3mdSRK@Gd6VMGKfoEOFzgof9UNJtTlLqH/j32QD6of7dX76AB6vAfx@QIIHxyCexrwbxgMBQiVsl9dfxMWwzQ0PmAdNUduaJqTfnixPPgzCOi7PkJDEPooFAxUO4O5335n0x7Qf9aqn9RWDehQbaVTrQsuxSa8DQmjVWoNWqzFADwtDaRTrYEp0pLGT1u55yqMl2JqoRYZnGLnUNk1s7q8EMrXZNC9rZKkvUc5hsa8IGMCTnrRazes4yjZ7J7Tiyxa1EtfIOWH0LYys3jBV4ZvqmoP1CXWO3ESNTmbaDGbDxZFvTTuc830GthHN2FzZ4beJmVzZgIs6yTfP1@M935uSt79sGDdedWKegnb97WN2YXb47pI6Qgeub68BV8/a6uiJtL/UNPou6xZoDXPQWvXAp5Jika9@fb4nSbucB4GRDFxDEI/ClB0BOFZC0GIIYLH3HgYGBkIVMDJ5qYmqXR8NcrGpeuCXZmGc@whAMgPdtBDz9NBlN5PC/CApctdj2Afb2XKkYOFFwBry/f348/fqp/z1wAryn39892PsKd/8A "JavaScript (Node.js) – Try It Online") ### How? Each wheel arrangement is encoded as a binary pattern with a forced leading \$1\$ followed by \$0\$'s for `o`'s and \$1\$'s for `O`'s. Once the list has been sorted from lowest to highest pattern under this encoding scheme, each name is prefixed with the delta value that must be added to the previous pattern to get the new one. ``` Name | Arrangement | As binary | As decimal | Delta --------------+-------------+-----------+------------+------- Planet | oO | 101 | 5 | 5 Four-coupled | OO | 111 | 7 | 2 Jervis | ooO | 1001 | 9 | 2 Jenny lind | oOo | 1010 | 10 | 1 Porter | oOO | 1011 | 11 | 1 Olomana | OOo | 1110 | 14 | 3 Cramton | oooO | 10001 | 17 | 3 American | ooOO | 10011 | 19 | 2 ... | ... | ... | ... | ... ``` Which is stored as: ``` "5Planet2Four-coupled2Jervis1Jenny lind1Porter3Olomana3Cramton2American..." ``` --- # [JavaScript (Node.js)](https://nodejs.org), ~~566~~ 552 bytes *Saved 14 bytes thanks to @HatsuPointerKun* I personally think that the challenge is more interesting with two independent functions (and I originally assumed it was a requirement) so here is my attempt under this constraint. The first function outputs the name with the first letter in upper case and everything else in lower case. The second function accepts the name in the same format (but it actually doesn't care about the case). ## Arrangement to name, ~~378~~ 364 bytes ``` s=>"CramtonPorterXMountainXTurbineXEl gobernadorJervisXHudsonSanta feMikadoColumbianXXDecapodMogulBerkshireAdriaticUnionOlomanaEight-coupledXAa20ForneyOverlandAtlanticUnion pacificXFour-coupledTen-wheelerPrairieNorthernHuntingtonXConsolidationPlanetPacificTen-coupledAmericanXMastodonTexasJenny lindJubilee".match(/.[^A-Z]*/g)[s.replace(/./g,c=>c>{}?3:7)%88812%47] ``` [Try it online!](https://tio.run/##VZPhatswEMe/5ymEoSQeSbp0g4aWpGRdSglkDawDs5CBYl8crYrOyHa2UvoGg33Zx@099jx9gT1CJsmSrXwx@Ke7v@70v/tK9zSPJcuKnsAEDpvRIR@Ng2tJdwWKBcoCZDTHUhSUiei@lGsmIJpykuIapKAJyhnIPcuj2zLJUXykKpJsYM4e1Nk18nK3ZlRE0XuIaYbJHNOSvwP5kG@ZhEkiGS1Y/EkwFHccd1TQKUu3RS/GMuOQRBN69voGpYDHuz1ITkUyKdTX5ZCMxmzD4ugGS@mS7kH0vm0BOMiFpEwy@KD62Kpyb1UfTKSqs@gaRY6cJep61aeShGJRael0qzTZgWSxKn9O8wITFPfwneYzEOKRcCaSWblmHCDo72gRbzun/eWXSe/z6tVpGi7zvoSM0xgUPk278Wgcj5@er95cnIcnw@FwcHby9nx1uFy2lgHeBd2gqiFYdfU/KtBcY6GJMo44oMPqN66g0aoscQB1WNO6xSbQ@myQ0fff0VKdbb1xBE2kdsXdoXPda9VMhzm7Gmh6sw9n@9DZZjJqoIOseQ0zenZkaj2d6znecCNRWerB6i30qNpmjMDR0NUXmhfy56Q50TLVjHtMw3q2mztNd3aAPGok7Gb5WHM3sLVX5kCf2BWsi3ftH3tm5c2ONAXqWLuH3oWmf3@h/TNjvt08T0hjt@oeroo3S@KLNLW4fT06tcaqTQ9WrVWrv0E5pWqdOsuMFmraRZcIuoNVSEZj8tQihENBJORkRDYdGxJeKh4br6DPMXW8n9FkKpLOYBB2dU63ShwZRXJF2v/@/nz5/Ut92@SCtF/@/GiHrefw8B8 "JavaScript (Node.js) – Try It Online") ### How? The pattern is turned into an integer by replacing `o`'s with \$3\$'s and `O`'s with \$7\$'s. For instance, `ooOOOoo` becomes \$3377733\$. This is reduced modulo \$88812\$ and modulo \$47\$ to get the final index in the lookup table, e.g. \$(3377733 \bmod 88812)\bmod 47=10\$. The lookup table is encoded as a single string where each entry starts with a capital letter. We use a single `X` for undefined entries. ``` "CramtonPorterXMountainXTurbineXEl gobernadorJervisXHudson..." ^ ^ ^^ ^^ ^^ ^ ^^ 0 1 23 45 67 8 9| 10 ``` Hence the answer for `ooOOOoo`: `Hudson`. ## Name to arrangement, 188 bytes ``` s=>0x4489B662749DEFD3631DBEB225C432AC03F6DBD8C78503C3FE918DA62325B6895775C9FAFB8E0E03939CD081D4537BDD91B2D228n.toString(3).split`2`[parseInt(s[7]+s,33)*362%763%61].replace(/./g,c=>"Oo"[c]) ``` [Try it online!](https://tio.run/##XZNbbtpAFIbfWcXIUoTdOo7xgC@NSOUbaiOlREr6hCxlsAeYxsxY43EuqrqDSn3pY7uPricb6BKoPbHB9AWJ7/znP@efA1/QAypTTgpxSlmGd6vprpxemE/jsesFtm05Yy@KZxG04SgK4sCyJuEYWn5owpkdBZEbOu7EhCGcxd7IjXzbgtYksF1v4jiT0Jv5s8CNzdiEHvTCyHRH0XgCnSCKvFFgRZblUkOwG8EJXatQM8oiJ@LOulsUiJf4IxVquXCSt6UOofYG2taJY8MTe5QYHBc5SrF6Zpyt9XR6ocyZskgTbXe@GCwUNld05TpHFAsl0ZvvrAaXmNJnkBOatVCqGBeYd6CRhSyvtkuC6CuUXpeYP5CyA6yRfaioqLcWrNNJYcjRtkPSf8Yqfpqyqshx1tKme56zLaKoI0wqOcXP3Yym199iTtLDIrLTF3UuQdIDlNmqJckx7nI03VdsXeV70IiuOSKcHESy0884QX2/pvcW09PHDcZ59zR7C5SSVV/cvkVW7kNLg5isN@IoN2srIaMly0lWz@yebt6aX5F7lLEea2CA@X25IRwfZsp0qBQsY7RHpQWrz4LIEW74p/rMG8wPt5KFpnJb8SWheL98F//4Zq39Z3q0dKONcIoKlvUGyvw5WLNlPbAOxPs1efwHzOsj9t5F4pv6rgiscA@/Ln@Ln1DZNznsAor/D7Lv8pFlKskgGRgrxmOUblS1/luJ@tdOdUDRFicamF6ArwMAciwAxyWYgpXaVLTzGqbyUNjI2VpCo0BZTDN1ZGt6o9ZfW6agNQXvwfDvnx8vv37Wn0PwDgxffn8faoNv2u4f "JavaScript (Node.js) – Try It Online") ### How? We can't use `parseInt` directly on the name because, for instance, `Union` and `Union pacific` would both be parsed as `Union`. Instead, we use: ``` parseInt(s[7] + s, 33) ``` Example: ``` "Jenny lind" ~> "iJenny lind" ~> 22045409 ``` We apply a slightly more complicated formula to the result: $$f(n)=((n\times 362)\bmod 763) \bmod 61$$ Example: $$f(22045409)=2$$ The patterns are encoded in ternary, with \$0\$'s for `O`'s, \$1\$'s for `o`'s and \$2\$'s for the separators. This leads to a pretty huge integer which is stored as a BigInt in hexadecimal. ``` 0x4489B66274...28n.toString(3).split`2` ``` gives: ``` [ '110001', '', '101', '0000', '10001', ... ] ^ 'oOo' ``` Hence the answer for `Jenny lind`: `oOo`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~698~~ ~~671~~ 670 bytes * -26 thanks to ceilingcat * -2 using `\n` instead of `\012` I encoded the Whyte notation into a bit encoding `xxyyyzz`, with `xx` being the leading wheels, `yyy` the driving wheels and `zz` the trailing wheels; these are stored at the beginning of each train name to save space. `f()` is the name-to-type conversion and `g()` is the type-to-name conversion. ``` #define F(a,b)for(;i/a;i-=a)printf(#b); #define G(a,b)for(i*=a;b*s;s++)i++; char*a[]={"$Planet","%Jenny Lind","(Porter",")Columbian","DJervis","FHuntington","dCramton","\8Four-coupled","\tOlomana","\nForney","HAmerican","IAtlantic","JJubilee",",Mogul","-Prairie",".Adriatic","JTen-wheeler","KPacific","LHudson","\020Eight-coupled","0Consolidation","1Mikado","2Berkshire","PMastodon","QMountain","RNorthern","iTurbine","\024Ten-coupled","\025Union","4Decapod","TEl Gobernador","UOverland","5Santa Fe",":Texas","ZUnion Pacific","^AA20"},**b;i;f(char*s){for(b=a;strcmp(s,1+*b);b++);i=**b;F(32,o)F(4,O)F(1,o)}g(char*s){G(0,111==)G(8,79==)G(4,)for(b=a;i-**b;b++);puts(1+*b);} ``` [Try it online!](https://tio.run/##hVNdb5swFH3Pr7DcVQICG8lSrRtiUtaWtFkzsi192bpJBgyxSuzINu2qir@@7NqEtG/jAc61zz33kzyo8ny3OypoyThFiUP8zC2FdCL2hkQsiIm7lYzr0jnK3GjQ82YHHvNiEmWeitRw6LLhMBrkayI98vNX/IRfLWvCqcY@Pp5Tzh/RNeMFWM5SSE0lIPdM1M0mY4SDcT6n8p4pQMllwzXjlRbmvDiTZNPB29NENDLIRbOtqZG61WktNoQTg3kiJKePAC@nGypZbmWvphrS0CwHPJ83GaspBegvRNXUAIKlJEwyc/Z6WkhG9tQV5cHDmtLaZvp5SXJW2pvry6ZQXTrhOLxg1Vq/yCg8E1yJmhWgY0mjBbsjhQA0/kTlnVozaWItF0RpUVjK14WAggkz@NsXaM6aSoPZqpEZNLwLNTEZvSg9HJ/c8C7G5JzmZCvM8eqiRjORgQAENZnfpPdUQgfM5cl36ARBiVH8sKJ/iOn2D6uCngv8PZ2OQ9z6npdFLCodO1LlPpmBZzBvpWW@2TrKHw09WIsMRh@x2LAT5@3YF27iTPwU3iPAbXXwnzmhPxqN4tidOaf@u/cWTHy312WB0bBy20Yrp5Nvd7CAaAPdce4FK1z0NEDISCJP2TXrtwzhfq8Q7jcB4X6pEO7ngPC@bQjbQn0Utj7yPB0dhBsrLFLDESIV1ivdf0Wapp3dfY2div4kPXDS3r17rHPYRgOIYirWsYoQBEW2VozdrjKE9n8cPlYo/ojAydNuZG9Kx9OmO2C0zzKNlfm/d/XSu939zcuaVGoXPPwD "C (gcc) – Try It Online") [Answer] # C#, 846 Bytes ``` using System;using System.IO;using System.IO.Compression;class P{ string[]D(){byte[]b=new byte[565];new GZipStream(new MemoryStream(Convert.FromBase64String("H4sIAAAAAAAAClWRbU7DMAyG//sUvcAkxA3K2ECIkkmMA6SNWa2l8eSmg90e52MD+ssfr53Hb9nAztuAEdgwvGAIl+aVgtNUOywRJYUMa/bL1JMNwGxUKGeaU8gMz0uIFA6RU0+ba7FTSnTDlhdZDbycPDrNGYznyQabYtauBLykLQbaCYWGsl51bVSqSENJlWzpySMmFgMdHxafQ4adWBIqDdW1Tshe5wzsMay+RkSfzqgDdqDPqyDTuznDqnxDhzHeeJNAr+EwsyenW9OBRj+Gjo7Wcc0YHlCO80iiGGWos3Nklw2pA6wmWboVGN7U3BGleJZLDPtFegqYYQr8r3d5zUe4QRh4xMGeWDlrvvHNE/e6UtHqudnyM4qaWe/Rwrs6a5tt8azA7PHb5t/5953mn1VV2bb3dz9Z/JdzNQIAAA==")),(CompressionMode)0).Read(b,0,565);return System.Text.Encoding.ASCII.GetString(b).Split('\n');} public string A(string i){var L=D();return L[Array.FindIndex(L,s=>s==i)-1];} public string B(string i){var L=D();return L[Array.FindIndex(L,s=>s==i)+1];}} ``` ## How? I edited the table into a bare minimum text file where the Whyte Notation lines are followed by a line with their name. Then I gzipped the text and encoded those bytes in base64 to make a compressed string literal to store in the code. The original text data took up 565 bytes and the base64 string is just 444 bytes. Making a constant literal array for these strings in C# would have taken at least 781 bytes. The function to decompress and return the array is only 622 bytes. When either function `A()` or `B()` in the program runs, it decodes and decompresses the base64 string into an array of strings. Using some simple `Array.FindIndex` I can find the line matching the function input and return the line either above or below the matched index. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~478~~ 474 bytes Latest edit: rearranged the order of names to allow for all to be in caps. Saved a few bytes by grouping constants and minor formatting. ``` ->q{s=w=3;r=p=0;e="-WHEELER";z=46 'H`0 PDavU$J24(d:1E,_I8F9iXYZeV5*%hTy'.bytes{|i|t="UNION PACIFICCONSOLIDATIONEL GOBERNADORJENNY LINDHUNTINGTONCOLUMBIANBERKSHIRESANTA FENORTHERNMOUNTAINMASTODONOVERLANDATLANTICADRIATICAMERICANPACIFICTURBINECRAMTONPRAIRIEOLOMANAJUBILEEDECAPODJERVISPORTERFORNEYHUDSONPLANETMIKADOTEXASUNIONMOGULEIGHTAA20FOURTENTEN"[p-=w,w] x=(y=[?o*(i/4%4)+?O*(i/16-1&7)+?o*(i%4),t+e*(1&z/=2)]).index q x&&r=y[~x] u=t.sum u>s||w+=w/10*2+1 s=u e="-COUPLED"} r} ``` [Try it online!](https://tio.run/##LVHbbtpAEH33V1hWQriDCU0vaBMt3jFeYs9Y610ailDbKEThoS3BuMYJ6a/Tpao0mus5c9Fsi/vq@MiOnevn15yV7HK0ZRvWH62Y1/kcAcSgvNELG145F9G3vpOK77/N2XQwrD988qH9VX4IP67v5l9Ws3fN8yddXXTvq90qfz2sDzvmGZSEbsoDGcogIMwoloJrm4TYndAYFHJBagqIczeWKCKDWuJEEwYUm2QsOVrQbRZJBRlHzd0QkJSOLDMhC@YSE55pEoQ0AxVztP2t1jLgQkl@sgkoq/H/GtqosUQIFE/smFRxqSRQTAlHPjVjGQMICHhKYgpqJrPUjgMVkkKYR0ZklmP7g07krd1dwx3P/p2Z0MTEICeR5nzQD8lYGlrxFpsOK9vl0tmzesUWN7@a9XVveD5stG7o5PpXHb/23kangk23d61Vs@7XXnps0Fg2uuufD6u9@@zsa7UtqxZ/9kunYLtuXvxwiuv8cChbrOz5/eag5Ts5K5zT5wIyaQzCe3O2b8eN@7jwiLzl8S8 "Ruby – Try It Online") A single function which takes either kind of input and returns the correct output. This is written to allow for further compression of the name string later. The names of the configurations are generated in order from the shortest to the longest per the table below. A checksum is made by adding all the characters and normally this checksum is nondecreasing; when the checksum decreases the code increases `w` by the length of the name by 1 (or when jumping from `Jenny Lind` to `El Gobernador` by 3), thus the trigger to increase the length of the name is encoded in the string of names itself. After unpacking `-wheeler` or `-COUPLED` is added as a suffix. We iterate through the names using a string of single characters that corresponds to the wheel configuration. This is unpacked using the string `?o*(i/4%4) + ?O*(i/16-1&7) + ?o*(i%4)` which covers the possibility of the front and back wheels numbering 0 through 3. Driven wheel counts `n` of 1 through 6 are encoded by `(n+1)*16`. For 7 pairs of driven wheels, the encoding is zero, plus `10` for the idler wheels giving ASCII 10 (newline) for the only locomotive with this number of wheels (`AA20`.) During the decoding process, this gives `n=-1` which is corrected to 7 by ANDing with -7. ``` ["ooOOO", "TEN-WHEELER"] ["OOOOO", "TEN-COUPLED"] ["OO", "FOUR-COUPLED"] ["ooOOOOOOOoo", "AA20"] ["OOOO", "EIGHT-COUPLED"] ["oOOO", "MOGUL"] ["OOOOOo", "UNION"] ["oOOOOOOoo", "TEXAS"] ["oOOOOo", "MIKADO"] ["oO", "PLANET"] ["ooOOOoo", "HUDSON"] ["OOoo", "FORNEY"] ["oOO", "PORTER"] ["ooO", "JERVIS"] ["oOOOOO", "DECAPOD"] ["ooOOoo", "JUBILEE"] ["OOo", "OLOMANA"] ["oOOOo", "PRAIRIE"] ["oooO", "CRAMTON"] ["oooOOOOooo", "TURBINE"] ["ooOOOo", "PACIFIC"] ["ooOO", "AMERICAN"] ["oOOOoo", "ADRIATIC"] ["ooOOo", "ATLANTIC"] ["ooOOOOOo", "OVERLAND"] ["ooOOOO", "MASTODON"] ["ooOOOOo", "MOUNTAIN"] ["ooOOOOoo", "NORTHERN"] ["oOOOOOo", "SANTA FE"] ["oOOOOoo", "BERKSHIRE"] ["oOOo", "COLUMBIAN"] ["ooOoo", "HUNTINGTON"] ["oOo", "JENNY LIND"] ["ooOOOOO", "EL GOBERNADOR"] ["oOOOO", "CONSOLIDATION"] ["ooOOOOOOo", "UNION PACIFIC"] ``` # [Ruby](https://www.ruby-lang.org/), 499 bytes This is the compressed version. The characters `A..U` are compressed in groups of 3 down to 2 characters in printable ASCII range. Q does not appear in any locomotive name and is used for other characters. After decompression Q is replaced by the other characters `Y VVYX20H` . It's a bit of a fail as it's longer than the original. Also many compromises were made in the original to make this compression possible so maybe I will revise the original later. ``` ->q{s=w=3;r=p=0;e="-WHEELER";z=46;d="" 261.times{|i|d<<('a`$9*wHx`m(`b5mHA{?`V(]pE7]k]|pd{^t1dp]x]+px!p!$9y)6$esqb[#)53fKnj|;`Dui]\\"{$a`?5B ;t^^'[i/3].ord*95+"I2._M7Du2GLm>FzF{zM=p0)M7'3-ziSJzjAt`\\,u,w7z2X2+_E:2J}#A[WSngy>8fBi`wf)>,Z{~7[2fsVrW.))"[i/3].ord-3135)/21**(i%3)%21+65} ' Y VVYX20H`0 PDavU$J24(d:1E,_I8F9iXYZeV5*%hTy'.bytes{|i|d=~/Q/?d.sub!(?Q,i.chr): (t=d[p-=w,w] x=(y=[?o*(i/4%4)+?O*(i/16-1&7)+?o*(i%4),t+e*(1&z/=2)]).index q x&&r=y[~x] u=t.sum u>s||w+=w/10*2+1 s=u e="-COUPLED")} r} ``` [Try it online!](https://tio.run/##PZFZc5pQAIXf@RVIXLischGJkitjKsZYHZOmcQmiaIGGdDTIElb961ZnOn07y8M3c44fbdOzg85s55AHKEai4iMP1RUbEexsoGkj7QehZKjRVCxEEBhsClzo7uwgL9zCursjaxuz3KLiQWLuSHMr7QbdXDWnpOFpsvHHKDwrX4WC5RmJQXtJySuVWylolu3gsNVvgCQ63/cfhWL2ItdYLom8vDFV6R5XwtWqpru8aHCfvkW1JJp4hNx6LPci@DDadfpZP8/GyKuDsVwT2cx9GWYf3dBcLpmIieUMziG91tpweLzp6rOX/e@0c@vcu2bsgA7zlp9kHTrB1J9xABD/MawoiBLgoUBRpFsRQQUKdFM6YjUcX@D4dLqYw/rArGNPvc3Xa3kIG6TVFjRm/Xjbb7nzxZs9lajK@8@0xm3T8N9A6MQ/86rFBdG2RKrPjMv9evdBGydDZOkei2ImNrAEkSnS1c8Llm9UGoBWJ1cpNFmhKl/ctbjETEjbFClUMx5BYADO3Vt2gh@wpFr1UaqfEgOLUHhB7bCoExRFTKOYF@oUpAUsQBF2ffTb5PVppPUIcMT849nDHZ2YTAjj/Bc "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), (445+262)= 707 bytes ## Notation -> Name, 445 bytes ``` O+ $.& oo V V2V Jubilee V2o AtlXtic o2o ColumbiX 2V Forney V2 AmericX o2 Porter 2o OlomXa 2 FourY V7V AA20 Vo4Vo Turbine o6V Texas V6o 5o V3o V4V Northern V5o OverlXd V3V HudsW o4V Berkshire V4o Mountain V5 El Gobernador o5o SXta Fe o3V Adriatic V3o Pacific o4o Mikado V4 MastodW 5o UniW o5 Decapod V1V HuntingtW o3o Prairie V3 Ten-wheeler o4 CWsolidatiW Vo1 CramtW o3 Mogul o1o Jenny Lind V1 Jervis o1 PlXet 5 TenY 4 EightY W on X an Y -coupled ``` [Try it online!](https://tio.run/##RVDLbtswELzPV/hQ9FKkqF/pWXWTFkFTGWhCy0daYu1FaG5AUWnz9e5QjwYQuavdmdlZRpck2PnlUn7Au4/voQoDszC46w7inWOuKJKvktRQ5hv13fkgFYi51RjcKyEozi5KXRGBrcbkIggtvZ4riwVxXdzDfDYoisUnGF0ZxUMXDxIc9Nrgwf21Lcy1Yq0zs6SHlcFPCp1cDDBrar246KsGZmnwvWvaHSiCLy4@tSeJtLlS3GsXkpVMwI2ffdMD2bbRCKXCryrZ2S3nUaFooti8UZ61tbX8zttlCXkigWq4t23SZkdDeAzCcWt8dbV9VnqYZw@BD3dMbGSJaCUKXSy5Srj6c3LO8w10hc2uVS8Nh@249xybaM89iW6PnYfOFXcuhNfZDwlZmn/xRVo2sPWVS1hnyT1WuJHjKe1BckAFG7DHVa3ds3fN5aIltFSeHHOSC6zkjGmZP82nb/W9AdVXyoE2CEyYATSicrGcYOOtYxgRI34iTLP7bCCXwz3yJvz/ONWn@Kb8JtpX/wE "Retina – Try It Online") ### Approach Replace each run of `O`s with its length, giving us for example `oo7oo`. Replace each `oo` with `V`, giving us for example `V7V`. Then replace that shortened notation with the appropriate name. There wasn't a whole lot of similarity between names -- the only substrings I found to be worth extracting were `-coupled`, `an`, and `on` ## Name -> Notation, 262 bytes ``` Hun.* ZOZ ....(..?).* $1 AA20 Z7Z at o3Z ic Z2 nt Z2o sh o4Z mb o2o ol o4 to ZoO po o5 ob Z5 t- 4 ey 2Z -c 2 on Z3Z y oOo is ZO le Z2Z od Z4 do o4o ta Z4o he Z4Z an 2o la Z5o et oO er o2 ri o3o fi Z3o a o5o wh Z3 co 5 s o6Z in Zo4Zo n Z6o n 5o l o3 Z oo \d *O ``` [Try it online!](https://tio.run/##PZJBb9swDIXv71f4sMNWIMGaJt1x8LJ2RbDOAdpdhF1oi42FymIgy@3y67PnDZ0PFkiK73uknbWEJJfn892UlhdwjcOSz/vl8vMHxu8uUderj3CfHKTArhxCB7dCKnwbxh62dhhaGCOLjFAMzhocGW9gLdwGZYE19ISVw6LDCpbgKHWqYI0hjOQiKhUdzMOt4dm8NhRhYOhZIkUSCInMbQxKNw00E4wc6MzwFKhqEKrywmvPCJ1hgxF2TeOE0qwhVXDXPMBbdHwFUg2/PC6a83kfJVF7pymdqu8heewtF3K2FqehDTSx0/xCz9wYd3coHGabZZjPW5vyorPpGNWjiTZIEiZz4uz1oDl0bK8LEYVr3E1tiKq4t8MUsc8SclDUPgeZy4@aFq@9aiR8L114Yu5u8iM5N@HQl/@graXRYvDsYu0@PAvX90Xz89iHTHkZi/m5YnQsXMMPTtRrTnicchuS/kW9qf1Ms8pX7eTIb3ETq2/W8i41M5oXzTTv8cAJpLqdO3/L@K@nejM5/zF/AA "Retina – Try It Online") ### Approach Extract 2 unique characters from each name, and use that to determine the notation. I found the 5th and (if present) 6th characters to work pretty well. `Huntington` clashes with `Turbine`, so `Hun.*` is replaced in advance. The shortened notation is the same as what's used for the Notation->Name program, but in reverse. ]
[Question] [ ## Challenge Given a [graph](https://en.wikipedia.org/wiki/Graph_theory) (a structure consisting of nodes and vertices), classify it according to a few categories. Specifically, you will be given an unweighted [directed](https://en.wikipedia.org/wiki/Graph_theory#Directed_graph) graph, which is a set of nodes and edges from one node to another (but not necessarily both ways). You can take this in any reasonable and consistent format, like an adjacency list/matrix. You may take a list of nodes, but it is unnecessary. *No edge will appear twice exactly* (however, \$A\rightarrow B\$ and \$B\rightarrow A\$ might both appear). Every node will be a part of at least one edge, so you can gather all needed information from the edges and don't need a list of nodes if you don't want it. Then, you must classify it according to the following categories: 1. If every pair of connected nodes is connected both ways, the graph is **undirected**. Otherwise, it is **directed**. 2. A **cycle** is a path in the graph from one node to another where the first and last nodes are the same, no other nodes appear multiple times in the path, and there are at least three distinct nodes in the path. If a such cycle exists, the graph is **cyclic**, and otherwise, it is **acyclic**. 3. If, for every pair of nodes \$A, B\$, there exists either a path from \$A\$ to \$B\$, the graph is **strongly connected**. If replacing every edge with an undirected edge (that is, substituting each edge \$A\rightarrow B\$ with \$A\leftrightarrow B\$) makes the aforementioned condition true but the graph isn't strongly connected, then the graph is **weakly connected**. Otherwise, the graph is **disconnected**. Note that it is impossible to construct a strongly connected acyclic directed graph; if every pair of nodes has a path in both directions, either they are the same, and it is undirected, or they are different, and it is cyclic. It is impossible to construct a weakly connected undirected graph by definition (replacing the edges with undirected edges doesn't mean anything on an undirected graph, so the graph would've been strongly connected already). ### Formal specification If the first part made sense and you understand the graph theory, this part is probably not worth reading. It is just here to be exceedingly clear about the definitions. To be extremely formal, a graph \$G\$ is a set of nodes \$N\$ and edges \$E\$ where each edge connects a node \$A\$ to a node \$B\$. The first condition asks if \$(A\rightarrow B)\in E\Leftrightarrow(B\rightarrow A)\in E\$ for all \$A,B\in N\$. If so, the graph is **undirected**, and otherwise, it is **directed**. Then, we define a path as the following: There exists a path from \$A\$ to \$B\$ if and only if \$(A\rightarrow B)\in E\$ or there exists some node \$C\$ such that there is a path from \$A\$ to \$C\$ and a path from \$C\$ to \$B\$. The second condition asks the following: does there exist a node \$A\$ such that there is a path \$A\rightarrow B\rightarrow C\rightarrow\dots\rightarrow A\$ where no node appears more than once except for \$A\$ and there are at least three distinct nodes in the path? If so, the graph is **cyclic**, and otherwise, it is **acyclic**. (Note that the "at least three distinct nodes" condition prevents \$A\rightarrow B\rightarrow A\$ from being treated as a cycle in both undirected and directed graphs.) The final condition asks the following: for every \$A,B\in N\$, does there exist a path from \$A\$ to \$B\$? If so, the graph is **strongly connected**. If not, if we add \$(B\rightarrow A)\$ to \$E\$ for every \$(A\rightarrow B)\in E\$, does this condition become true? If so, the graph is **weakly connected**. Otherwise, it is **disconnected**. ## Formatting As mentioned above, you can take the graph in any reasonable format. You should output one of 9 distinct values for each possible combination of (undirected, directed) × (cyclic, acyclic) × (strongly connected, weakly connected, disconnected); these can be any 9 consistent and distinct outputs, including erroring. For example, you may choose to output 7 various values for 7 of the categories, output nothing for the 8th, and crash on the 9th. You cannot error for more than one category (this is to prevent needing to formally define distinct classes of errors). Outputting the same value to STDOUT and STDERR count as two different outputs. **There will be at least one edge.** This means that a graph containing a single node is also invalid. ## Test Cases You can find an image representation of these test cases [here](https://i.stack.imgur.com/eSRXQ.png), which includes an example for each of the categories in a table format. These test cases are given as a list of edges in the format `[[src, dest], [src, dest], ...]`. The output is descriptive, but you don't need to output the full name, of course. ``` [[1, 2], [2, 3], [3, 4], [4, 1]] -> Directed, Cyclic, Strongly Connected [[1, 2], [2, 1], [2, 3], [3, 2]] -> Undirected, Acyclic, Strongly Connected [[1, 2], [2, 1], [2, 3], [3, 2], [3, 1], [1, 3]] -> Undirected, Cyclic, Strongly Connected [[1, 2], [2, 3]] -> Directed, Acyclic, Weakly Connected [[1, 2], [2, 3], [3, 4], [4, 2]] -> Directed, Cyclic, Weakly Connected [[1, 2], [3, 4]] -> Directed, Acyclic, Disconnected [[1, 2], [3, 4], [4, 5], [5, 3]] -> Directed, Cyclic, Disconnected [[1, 2], [2, 1], [3, 4], [4, 3]] -> Undirected, Acyclic, Disconnected [[1, 2], [2, 1], [3, 4], [4, 3], [4, 5], [5, 4], [5, 3], [3, 5]] -> Undirected, Cyclic, Disconnected ``` ## Related * [Is the graph acyclic?](https://codegolf.stackexchange.com/questions/122344/is-the-graph-acyclic) - determines if a directed graph is acyclic (input format is required to be an adjacency list) * [Is this figure connected?](https://codegolf.stackexchange.com/questions/801/is-this-figure-connected) - determines if an undirected grid graph is connected (input format is required to be a list of grid coordinates) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins per language category. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 65 bytes ``` ;U,Ɗṭ;Ɱ¥0ị⁹ẹ@ịƭƒƲḟḊƊ$€ẎQɗƬZṪƊ€.ịⱮfƑ@ɗ€;ṪL>3ƊƇ.ịⱮƲE€ẸɗɗFQœ!2Ʋ;fƑU$ ``` [Try it online!](https://tio.run/##y0rNyan8/986VOdY18Oda60fbVx3aKnBw93djxp3Pty10wHIOrb22KRjmx7umP9wR9exLpVHTWse7uoLPDn92JqohztXHesCCuiBNGxcl3ZsosPJ6UC@NVDCx874WNexdqjUsU2uYI07Tk4/Od0t8OhkRaNjm6yBGkJV/h9uf7hzn/WjhjkKNroKjxrmAnXv4zrcDlQPFHPWCdaJ1AkFCocfWmINUuVs65yfl5eaXJKaAuQF2waXFOXnpedUKiQjCUfaJkcm52QmA5mhtqF5KZlFUJm5kf//R3NFRxvqKBjF6ihEG@koGINoYx0FExBtoqNgGBurg6rCEE2lEREqIDRY3BAkjq4DmwiqO9BsActgikDUmoJoU2ymGqKpJEYFqpkmcLMh6kxjY7liAQ "Jelly – Try It Online") A monadic link taking a list of edges in the same format as the question and returning a list of zeros and ones in the order `[connected, strongly connected, cyclic, undirected]`. Strongly connected graphs will have both of the first two list members set whereas weakly connected will just have the first of those two set. ## Explanation A monadic link taking argument `x`, a list of edges in the format `[src, dest],[src, dest],…` and returning a list of 4 integers as specified above. Works by generating all possible paths through the graph and through the graph with the opposite direction edges added before running some tests. Apologies if this is a bit tricky to follow - Jelly’s tacit style of programming can get a bit convoluted when as long as this! ``` Ɗ | Following as a monad: ;U | - Concatenate x to x with each of its members reversed , | - Pair with x Ɗ€ | For each of these (call each one y) do the following: ɗƬZ | - Do the following to y until no change, using the transposed version of y as the right argument $€ | - For each member of the list z: Ɗ | - Following as a monad: Ʋ | - Following as a monad: 0ị | - Last member (call this a) ⁹ ƒ | - Reduce the transposed version of y using a as the initial argument and the following: ƭ | - Alternate between: ẹ@ | - Indices of a in the first member of the transposed y ị | - Index into the second member of the transposed y ḟḊ | - Filter out members of z except for the first ¥ | - Using the above as the right argument (call this b) and z as the left: ṭ | - Tag z onto ;Ɱ | - The result of concatenating each of b onto z Ẏ | - Tighten (concatenate outer lists) Q | - Unique Ṫ | - Tail (call this w) Ʋ | Following as a monad applied to x: F | - Flatten Q | - Unique œ!2 | - Permutations length 2 (call this v) ɗ | Using v as the right argument and w as the left argumemt ɗ€ | - For each member u of w: .ịⱮ | - Take the last and first members of the list fƑ@ | - Check whether filtering v just to the members of u leaves v unchanged (gives the connected and strongly connected results) ; ɗ | - Concatenate to the following: Ʋ | - Following as a monad Ṫ | - Tail L>3ƊƇ | - Filter to keep only lists of length at least 4 .ịⱮ | - Last and first members E€ | - Check if each is equal (returns whether x is cyclic) Ẹ | - Any ; $ | Concatenate to: fƑU | - Check whether x left unchanged if filtering only to the x with each member reversed (undirected) ``` [Answer] # [Julia 1.0](http://julialang.org/), ~~138~~ 130 bytes ``` !a=(z=1:size(a,1);~a=all(sum([a].^z).>0);a/i=any(j->a[i,j]>0&&(a[[j,i],i]=0:1;a[j,j]>0||+a/j),z);[a!=a',any([+a]./z),~a,~(a.|a')]) ``` [Try it online!](https://tio.run/##rZRRS8MwEMff9ykyhJlg3JZue7GkINuLzyI@hAhH10lqmo4uwlbGnv0Ifj6/yLx2OpywWdEScu3l0t/9k@PSZ2tALLfbNkhaSnG1MGVCgQsWbkCCtXTxnFEFuvtQsm7UZyH0jAS3oullBMrwVEf9ToeCUik3GofsX4kQ8KtaWa8voJcyXrJQQVvCOa@2qgv8X69kfAN8Q6G7hnOm2dZL1VJKcBJoTlTAyaCyA06GlR1yIrQmPz/87DIiE1MksU@mHB3jVWxNjG@3vsjdo12Rce5cvXzIE9@4QXPenZvuidfxB/D3vJ2t/aLy6ya8xvoGjfT8eJ57ffcJPJ2iHd5e8MfbO0GrKf@rbWIW8THSTs@osqOmp3pc1xHSZ318IQ7@WI@/IR1qHO617uJGdSbHK/GApFswTemSEUlohlMGS5NhV4lzazGC3vikAJ8Xi@7MgveJw1jGQgIYOzPYgvqcZDjQNcsLYtC9JNh7VJW1UVVdSSJI4qa4h7UymNN5YZy37u3llbYZzpgA92z7Dg "Julia 1.0 – Try It Online") Takes input as an adjacency matrix (In TIO footer it is constructed from edge list by `adj` function), outputs a boolean array with the following members: ``` [directed? cyclic? strongly_connected? connected?] ``` ### Explanation Checking directedness is trivial: if adjacency matrix is equal to its transpose: \$(A = A^T)\$, then all nodes are bidirectional and the entire graph is undirected. Connectedness can be checked using a known property of matrix powers: the elements of \$A^n\$ indicate the number of \$n\$-length walks between the respective nodes. Therefore, if we calculate \$A^n\$ for all \$n\$ from \$1\$ to size of \$A\$ and find a non-zero element in each position at least once (this function is assigned to `~` operator in the code), it means that we can reach any node starting from any other node and the graph is strongly connected. Repeating this test with the analogous undirected adjacency matrix, where all edges are set to bidirectional `(a.|a')` shows whether the graph is at least weakly connected. Finally, presence of cycles is detected using depth-first search (`/` operator taking a copy of `a` and a starting node `i`). The nodes are marked as visited by setting the respective diagonal positions `a[i,i]=1`, and when passing through the edge `i->j` we also temporarily set `a[j,i]=0` to prevent going back through the same edge in opposite direction and detecting a pseudo-cycle. Since we can have multiple disconnected components, the search procedure is repeated for every possible starting node to ensure that no cycles are missed. *Note: The number of connected components can also be determined algebraically as the number of zeroes among eigenvalues of [Laplacian matrix](https://en.wikipedia.org/wiki/Laplacian_matrix). And according to this [Math.SE answer](https://math.stackexchange.com/a/911040), Laplacian can also be used to check for cycles. However, that formula works for undirected graphs only, and importing LinearAlgebra module is too costly for golfing anyway.* ]
[Question] [ ## Background Mathematicians are interested in all kinds of algebraic structures, e.g. groups, rings, boolean algebras. Generally, we have several operations (addition, multiplication, meet, join, etc.), and some equational relationships on the operations (e.g. associativity of multiplication). This makes up an **algebraic theory**. Formally, we want \$k\$ functions, the \$i\$-th of which takes \$s\_i\$ arguments. We also want some equalities to hold between the functions. In our case, we only consider equalities between expressions of depth at most 2, e.g. \$f(g(x), h(x, y), h(y, z), f(x, y, w, z))\$. The equalities should hold whatever values you plug in for the variables. Let's take a quick example. A **semigroup** is such an algebraic structure. We need to have one function \$f\_1\$, with \$s\_1=2\$. There is just one equational relationship: \$f\_1(f\_1(x, y), z) = f\_1(x, f\_1(y, z))\$. We are interested in **models** of the algebraic theories. A model, simply put, is just an implementation of the functions. We choose an underlying set \$M\$, and we implement the required functions \$f\_i\$ as taking \$s\_i\$ arguments from the set \$M\$, and returning an element of \$M\$, so that the equations hold when you plug in any element of \$M\$ for the variables. For example, if we take \$M = \{0,1,2\}\$, and \$f\_1\$ to be the addition modulo 3, we get a model for the semigroup. The **order** of a model is simply the size of \$M\$. So the model above has order 3. Suppose that, for a fixed algebraic theory, there are two models, with underlying set \$M\$ and \$N\$, and functions \$f\_i\$ and \$g\_i\$, respectively. If, after some relabeling of the elements, two models become exactly the same, we say they are **isomorphic**. In that case, the two models are essentially the same, and usually we don't care about their difference. > > More formally, if we can find a mapping \$\sigma: M \to N\$ such that \$g\_i(\sigma(m\_1), \sigma(m\_2), \dots, \sigma(m\_{s\_i})) = \sigma(f\_i(m\_1, \dots, m\_{s\_i}))\$, we say that \$\sigma\$ is a **morphism**. Furthermore, if there is another morphism \$\pi : N \to M\$, and \$\sigma(\pi(x)) = x\$, \$\pi(\sigma(y)) = y\$ holds for every \$x \in N, y\in M\$, we say that the two models are isomorphic. > > > # Task Your challenge is a very natural question that arises when studying algebraic theories. > > Given an algebraic theory (whose equations involve only expressions of depth at most 2) and a natural number \$n\$, compute the number of distinct models of order \$n\$, up to isomorphism. > > > You may write a function or a complete program. You can suppose the input is reasonably parsed for you. See the examples. Standard loopholes apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the shortest byte length wins. ## Example Cases ``` Input: The theory of groupoids. There is one function f taking 2 arguments. f(f(x, y), z) = f(x, f(y, z)) n = 2. Output: 5. ``` We'll fully work this out. For the rest of the example cases the basic idea is the same. Let's take `M = {0, 1}`, the actual labelling of the elements obviously doesn't affect the outcome. We have four values to decide on, `f(0, 0)`, `f(0, 1)`, `f(1, 0)`, `f(1, 1)`. Let's case split on `f(0, 1)`. * **Case 1:** `f(0, 1) = 0`. So `0 = f(0, 1) = f(f(0, 1), 1) = f(0, f(1, 1))`. We further case split on `f(1, 1)`. + **Case A:** `f(1, 1) = 0`. Then `0 = f(0, f(1, 1)) = f(0, 0)`. If further, `f(1, 0) = 0`, then `f` is a constant function, and obviously satisfies the equation. If `f(1, 0) = 1`, then `1 = f(1, 0) = f(1, f(1, 1)) = f(f(1, 1), 1) = f(0, 1) = 0`, contradiction. + **Case B:** `f(1, 1) = 1`. Let's consider `f(0, 0)`. - **Case i:** `f(0, 0) = 0`. Then `f(1, 0) = f(f(1, 1), 0) = f(1, f(1, 0))`. If `f(1, 0) = 1`, plugging that in yields `1 = f(1, 1) = 0`, contradiction. SO `f(1, 0) = 0`. So `f(x, y) = x and y`, which satisfies the equation, as you learned early in discrete mathematics. - **Case ii:** `f(0, 0) = 1`. Then `f(1, 0) = f(f(0, 0), 0) = f(0, f(0, 0)) = f(0, 1) = 0`. So the whole thing is just the `xnor` function. Now let's look back: we've already got the constant function `0`, the boolean `and`, and `xnor`. We proceed: * **Case 2:** `f(0, 1) = 1`. We could do the case analysis all over again. But note that everything exactly mirrors case 1, except that `0` and `1` are inverted, and the two arguments of `f` is swapped. Since swapping the arguments doesn't affect associativity, we immediately get what we wanted: the constant function `1`, the boolean `nand` and `xor`. Now we need to make sure they are all non-isomorphic. In fact, the two constant functions are isomorphic, since the relabelling that swaps `0` and `1` converts between them. So we've got 5 different possibilities. ``` Input: There are three functions f, g, h taking 1, 2 and 0 arguments, respectively. The equations are: g(g(x, y), z) = g(x, g(y, z)) g(x, f(x)) = h() g(f(x), x) = h() g(h(), x) = x g(x, h()) = x n = 3 Output: 1. ``` You may assume that the functions are labeled with natural numbers, here we use letters to make it more readable. Note that the expressions on both sides of the equalities should be implemented as trees or nested lists. You can assume that such trees are passed to your function as argument, so you can skip the parsing part. But in case you want to fiddle with `eval`-like stuff you can also accept string input. The model of this algebraic theory is exactly the groups. And all groups of order 3 are isomorphic to \$\mathbb Z\_3\$, which takes the underlying set to be \$\{0,1,2\}\$, and `g` is the addition modulo 3, `f` is negation, `h()` equals 0. Then the equations translate to: * \$(x + y) + z = x + (y + z)\$; * \$x + (-x) = 0\$; * \$(-x) + x = 0\$; * \$0 + x = x\$; * \$x + 0 = x\$. These are just the familiar properties of addition. ``` Input: Same as previous, except `n = 6`. Output: 2. ``` In fact, for this algebraic theory, the answer should be [the very first sequence of OEIS](http://oeis.org/A000001), which demonstrates the importance of such sequences. --- ``` Input: There are 4 functions f, g, h, i, that takes 2, 2, 0, 1 arguments, repectively. The equations are: f(f(x, y), z) = f(x, f(y, z)) g(g(x, y), z) = g(x, g(y, z)) f(x, y) = f(y, x) f(i(x), x) = h() f(h(), x) = x g(x, f(y, z)) = f(g(x, y), g(x, z)) g(f(y, z), x) = f(g(y, x), g(z, x)) n = 10. Output: 4. ``` This is OEIS [A027623](http://oeis.org/A027623). ``` Input: There is just 1 function f taking 1 argument. The equations are: f(x) = f(x) f(f(y)) = f(f(y)) n = 30 Output: 10712682919341. ``` > > Note that the equations are redundant. `f` is simply any function. We draw a directed edge from `a` to `b` if `f(a) = b`, this produces a graph where every vertex's out-degree is 1. Since we consider things up to isomorphism, we need to count such graphs with unlabeled nodes. We first consider a connected component. Since the out-degree is always 1, you can uniquely follow the edges until you hit a previously visited vertex. This produces a cycle (possibly with length 1 or 2). We consider the rest of the vertices in this connected component. They have to be on trees rooted on the cycle. Counting such graphs should be standard practice. The number of connected component is [A002861](http://oeis.org/A002861), and the total number is [A001372](http://oeis.org/A001372). > > > ``` Input: 2 functions f, g both taking 2 arguments. f(x, y) = f(y, x) g(x, y) = g(y, x) f(f(x, y), z) = f(x, f(y, z)) g(g(x, y), z) = g(x, g(y, z)) f(x, g(x, y)) = x g(x, f(x, y)) = x Output: OEIS A006966. ``` It is clear that this challenge is a very general generalization of various counting problems. --- Below are some degenerate corner cases. ``` Input: There are no functions. There are no equalities. n = 7. Output: 1. ``` This is just finding sets with 7 elements, and if there are bijections between two sets they count as the same. Of course, there are bijections between every two sets with 7 elements. So the answer is 1. ``` Input: There are no functions. The only equality is x = y. n = 7. Output: 0. ``` The equalities should hold for all `x` and `y`. So there can only be at most 1 distinct element, but we require 7. ``` Input: Same as above, except `n = 1`. Output: 1. ``` ``` Input: Any algebraic theory, n = 0. Output: 1. (Regardless of the theory.) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~482~~ ... ~~408~~ 402 bytes * -5 thanks to @ovs * -18 by inlining functions that are used just once * -12 by introducing short names of constants and removing parentheses * -11 by making a function local so it can take less arguments * -29 thanks to @Laikoni and @Trebor * -6 bytes by preferring list comprehension to `filter`, and turn `F Int[A]` into `Q[A]Int` for 1 space (I changed the letter to ease the changing of the test cases). ``` import Data.List data A=Q[A]Int|V Int t=map w=sequence y(V i)=i y(Q l _)=maximum$0:t y l (0!_)_=1 (n!e)q=c[b|m<-w$t(a.(n^))e,let b=[\b->f!!sum(zipWith(*)b(t(n^)r))|f<-m],and[h l==h r|(l,r)<-q,v<-a$1+y l`max`y r,let h(V i)=v!!i;h(Q e f)=b!!f$h<$>e]]where;a i=w$r<$[1..i];d#w=all(\p->or[(t(.t(p!!))d!!f)q/=(t((p!!).)w!!f)q|(f,z)<-zip r e,q<-a z])$permutations r;c[]=0;c x=1+c(filter(head x#)x);r=[0..n-1] ``` [Try it online!](https://tio.run/##nVbbbuM2EH3XV4y8eiAbSZXkbNPGVgADuw8BsmiDFOmDomZlm4qI6maKvgX@93QoWbaUeLvpEgZBDs@cuXA4chJV/7A0fXnhWVkICZ8iGdk3vJLaHFcw8W@DSXidy9094KxJP4tKbe1XbLFk@YxpW3IPnPocF7eQwiNFwIZny8xwLiVsIdWIoz/SR9/VSK4zuvBnwXSXja21IUlkk/xvSpmZMglTP3iYWlexrlfLjDzz8i8uE/ITnRKpUILSXTy2stCM8nmQQOr7CYgdSU1Bx9bCXI2tyHDP0OJX9ODrFkTNmjT@rXSdjxJ0kUFM/amux0YyNq5YGK4TJtgoAu6vDTE2Ate2eTiaf1j7UZqSh9K6KkSALtiSlLpO6Rx16eJnH0W1wKbrWrIjsfmMnqDjIICZC/QHnkNqlExkSxlJXuQViNEsCH1nNION757NSMxTyQRJWDSHzQe6oSPhB45t55YbvsQL8CFOkfAWwLLqZcnmIAuoohWDImeQFYLBdCuZplUs40@iWJaPTCkGQAAZHAia@R4cE@7BDdXs4dwRt0u3OQuBQlibjASXnFWKzgtHMHG8i18/ulrXjAZAUN@t7bin7bhHO27XDjWP2j1HnLBR9CDogY7nisH5JkiJWgTOp@woyP5UexsteuiZqK5iVsNFAgW5xqynW0jwvmTCoMR7Ve9A3ck64hLiQsCyVNvcH5qAtQp/Xv/eKLVyT9MEz5/6@fuhe3oV9Y9mv2@1Z8TpoXAe/nf6nfemvxeHeaxU97UvR8HbgLskHY86TG5HXAu8RhCeunSvuXQTTTe1/os3tDVtvsymby6ra@xEmhrPepG1opPl1hSaO7zwbFVpTalVUhT5E1aOYLMiyxgW07ZYwrJidfGxrJRbwE5cNxeosN3xvJLYS1oKHtcK6yiXqvTYigmEMSzLrUywBBGP7YdVUq2TCLtLbms17T7eUJOCr3iU7vekvRsaappERbi8hAC/DCFYV3g8MWFC6zVBoam@GVTt8AkQ2ii0Ubd@V0By9VCqNRMUbcyL2nvVvAWL0kl9gHKSg94q06N2DS6X8k4KMGDweVOymcQmOYCzM6iSYr2nVtuB@SCfCtk5O1qoeTBfe7Tvvz5TA7Oe743d5DB4kH9M7u4@fxocACzFu@kC4sXk@kYhtCziucpWk4p6dwi2Tgx2WDiMXjMnWJUf6buQ2HO88y60bWRKcoCpoUhd2lbK98DD/wM@x5Oeu8d3BW3nO/jQQ7qdwNpnd0AOGyT@A/nyCOSg0NYrxTMD1Pd37xr6fF7zqT1uLtCB38K3HM57Ofa/0xTHh0JbCqfGH1j2FE7zC991n84h799L@mvkt5PeIF/@BQ "Haskell – Try It Online") The function `(!)` accepts input as `(n ! arities) equations`, where `n` is the given `n`, `arities` is a list of \$s\_i\$, as specified in the challenge, `equations` should be in the predefined datatype `A`, whose ungolfed version reads ``` data Expression = Func Int [Expression] | Var Int ``` An expression is either a `Var` variable, indexed by natural numbers (here `Int` saves bytes), or `Func i [arg1, arg2, arg3, ...]`, which is just the \$i\$-th function, applied to the list of arguments. I have entered the equations in the footer in TIO, in case you are interested. (`Func Int [Expression]` becomes `Q[A]Int` in the golfed code to save one space.) As mentioned by @fireflame241 it is very hard to get anything interesting done within the time limit. Nonetheless I've written a decent set of tests to check against OEIS. --- Ungolfed version (still messy but hopefully the comment makes it clear): ``` import Data.List data Expression = Func Int [Expression] | Var Int deriving (Show) tabulate n arity f = intercalate "\n" [ "f" ++ show assv ++ " = " ++ show (f assv) | assv <- sequence (replicate arity [0 .. n - 1]) ] showModel n arities m = intercalate "\n\n" [tabulate n a f | (a, f) <- zip arities m] -- auxiliary function to find the largest variable number -- this is less efficient, but saves the hassle of having to bookkeep the used variables vars (Var i) = i vars (Func _ l) = maximum $ 0 : map vars l -- the 0 is to avoid empty lists -- evaluates an expression in the model `funcs` evaluate :: [[Int] -> Int] -> [Int] -> Expression -> Int evaluate funcs varass (Var i) = varass !! i evaluate funcs varass (Func f es) = funcs !! f $ map (evaluate funcs varass) es -- auxiliary function to generate all possible variable assignments varasss n l r = sequence (replicate (1 + max (vars l) (vars r)) [0 .. n - 1]) -- I think this can be further golfed, but havent come up with good ones yet checkValid :: Int -> [Int] -> [(Expression, Expression)] -> [[Int] -> Int] -> Bool checkValid n arities equations funcs = and [ evaluate funcs v l == evaluate funcs v r | (l, r) <- equations , v <- varasss n l r ] -- generates all models. The outer list comprehension runs over a cartesian product M1 * M2 * ..., -- where Mi is the (flattened) table of all the possible implementation of the i-th function -- Then the complicated `sum $ zipWith` stuff computes the index of the flattened table Mi -- from the un-flattened index allModels :: Int -> [Int] -> [[[Int] -> Int]] allModels n arities = [ [\b -> f !! (sum $ zipWith (*) b (map (n ^) [0 ..])) | f <- m] | m <- sequence (map (\i -> sequence (replicate (n ^ i) [0 .. n - 1])) arities) ] -- see if two models are identical, by comparing the values. ident :: Int -> [Int] -> [[Int] -> Int] -> [[Int] -> Int] -> Bool ident n arities m1 m2 = and [ (m1 !! f) assv == (m2 !! f) assv | f <- [0 .. length arities - 1] , assv <- sequence (replicate (arities !! f) [0 .. n - 1]) ] -- see if two models are isomorphic, by testing all permutations. -- (p !!) computes the permutation -- the mysterious `((p!!).)` was generated by http://pointfree.io/ from `(\f -> \i -> p !! (f i))`. -- It is understandable, but I couldnt have come up with that ;) isom :: Int -> [Int] -> [[Int] -> Int] -> [[Int] -> Int] -> Bool isom n arities m1 m2 = or [ ident n arities (map (flip (\i -> ($map (p !!) i))) m1) $map ((p !!) .) m2 | p <- permutations [0 .. n - 1] ] -- used to partition the valid models into isomophic classes -- This was taken from one of my projects, which ultimately -- comes from some StackOverflow code snippet, which Ive lost the source splitOffFirstGroup :: (a -> a -> Bool) -> [a] -> ([a], [a]) splitOffFirstGroup equal xs@(x:_) = partition (equal x) xs -- splitOffFirstGroup _ [] = ([],[]) -- Not really necessary equivalenceClasses _ [] = 0 equivalenceClasses equal xs = let (fg, rst) = splitOffFirstGroup equal xs in 1 + equivalenceClasses equal rst -- putting everything together... answer 0 _ _ = 1 -- corner case answer n arities equations = equivalenceClasses (isom n arities) $ filter (checkValid n arities equations) $ allModels n arities ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~393~~ 382 bytes *-11 bytes thanks to @ovs* ``` from itertools import* T=tuple P=product def C(A,e,n): G=range(n);t=0;c=[] for m in P(*[[dict(zip(P(*[G]*a),o))for o in P(*[G]*n**a)]for a in A]): E=lambda x,f:f[x]if x*0==0else m[x[0]][T(E(s,f)for s in x[1:])] if m not in c: c+=[T({T(r[a]for a in k):r[f[k]]for k in f}for f in m)for r in permutations(G)];t+=all(E(q[0],f)==E(q[1],f)for q,N in e for f in P(*[G]*N)) return t ``` [Try it online!](https://tio.run/##pVbfb@M2DH73X8G5D5USL0h6Kw5IoQHF4VYMGA4Frm@uUaixnHixZUeW75J2/ds7UnJ@OMn6MhdtJeoj@ZEiadcbu6j0p/f3zFQl5FYZW1VFA3lZV8YOggdh27pQwb2oTZW2MxukKoMv7DZSkebTAO6EkXqumOY3VoxvZiJOIICsMoDmNNyzQRyn@cyyl7xmtLtLBpJHFeeEqbYYlOoBHiQklSS9Tcg8fBWFLJ9TCesom2bxOskzWA/GQoxV0Sgo43U8TpL4gX1lTZQ5ow2pr@PJNOEJWkCFEnRlSTqbwmwoEP36wEws996WfGriLF4mTrQkUfZGy4yWpbNraFkrU7ZW2rzSDbvjyY0dClkU6H6FRJCBELScJB2ZVfSN1BTsjHXhfuM8AKNsazTYd59v3AfBTDaqeWqsyfUcRBiGF8EFpGqutDLSqmASfA7o6QnHJFyLzenJBH/OCMdBJq6CjK2jDRfrDjGrWm3BLhTotnxWeD8ZzE3V1g2tKpOi6AqVUVFMYC6uYCHGwZzN0QxseAQvHAS43ZxtaMsDt0M/nI4WjAS0i2C9F@Dfbr/2eBT4nee1Z0NJQTIarkAVqlTaNsiG@Fw5PjnyIk4ZOTnglHkWO04fMe40ndaGeKEk71POTilvjTu1nXm38C47QKdFGGecMC@04MexFtLafKa6cFtdyGeMOcVaTlXT3YKL@gzj@U4y38XwPzPSAXohH0iO2SudVlmrZ65TKITr/Y399jm4phIiwx0XT3DT5c@tTkw2qsy35dirgGufi49jxE4KAupCarBtf2E/GjVq6iK3LHzUr5@itzCCwxZ0UwigyDXehDhU3quF3GEu0FZZ/VAduLHSWHLyM7cLCC/CDmQXeQNphQiaSp3KcyH10iv2/MWDLC9wLLNuDJJ86hRphT3p/uPo@UWgh8jrubkHoNa1mlmsGIFxWuaORnVVszH3hPV/nuDQdEIfPD2ZJDZyG7QIOeym56F@B9hSwCF9bMOf7GrjyeIbpMFiV3j4@uYOpclt7uP3aIvLsddDp2yr/KRlqSIHx2KnoS0PvJ16iHuKCRq1O3jncyTrGmuXUV68Xb6DWBgKmBzRN8T7kl3CEMJ/wtHfVa7ZGdejpdo0NNaGcMkvfXJWrX@RHGQFo1OrXU73waBQuFJtn1kWstdD/2/88ZHh3ZswfpxEgCu12pP2CYvA@gSdYYav/RKp7Z3tHKrVyKi6kDNFFrDsmT1IxzEk5GEUJuEHgAiSI8gPac4VAD30pUHHFHJzxI7kdIWo0YzcTMDS6yHybA/CuHt@@rbo6V7EPVS81U96cCpFykShNOvhOT@heMZWr@YOXNuzVx3G8teXZIiJ6zLRv9smT12XuI80VsqaqR@yiA5GWjMQ@OtLond1Xelty505Uzg/TqPyWkY1bUGxf2Fdp0R7KxHo7QjE@qpKGsv@O0Ktu0llK5zfCn4upD/Jdd3iUVUtGwQsVadem23jnXjAyha/UyQ6FZfYRE7D4z05BNzffv8e0t17iRC7Geg@F8M/bv/8C6vv/V8 "Python 3 – Try It Online") Takes each equation in the list as a pair of two expressions (LHS and RHS) and the number of free variables. Each expression is a tree representation, where the first non-negative integer of each list represents the index of the function, and the rest of the list are the function's arguments. (Uncomment the second-to-last line of the TIO link to see what the input looks like). The footer performs a bunch of parsing on the input string before passing to the function. This generates all possible mappings of inputs to outputs for each function and tests if each one works. Ideally implemented, this general algorithm would have worst-case time complexity something like \$O(\frac{n^{\sum A}LEn^L}{n!})\$ (very slow), where \$n\$ is the order the given, \$\sum A\$ is the sum of the arities of the functions, \$L\$ is the average length of each equation (the whole equation is evaluated), and \$E\$ is the number of equations. There are \$n^{\sum A}\$ possible models, but sets of \$n!\$ on average are mutually isomorphic. Each class of models gets tested once (Ideally, we could ignore all but \$1\$ of each class, but it is not trivial to skip over isomorphic models. Hence, there is probably a full \$n^{\sum A}\$ term added for my implementation, and even higher since it checks for `dict` membership in a list of `dict`s). In the worst case, all of these \$n^{\sum A}/n!\$ models are valid, but they have to be verified by checking all \$E\$ equations and all \$n^L\$ possible inputs, each of which take (on average across the equations) \$L\$ time to evaluate. In the average case, I"m guessing only the log of this number has to be checked, so the average case would be roughly \$O(\frac{n^{\sum A}L\log(En^L)}{n!})=O(\frac{n^{\sum A}L^2\log(E)}{n!})\$. In the best case, for example with the equation `x=y`, each model gets invalidated with the first or second check (`0=0` ... `0=1`), so best case is \$O(\frac{n^{\sum A}}{n!})\$. With these unwieldy time complexities, I have had to (greatly) shrink some of the orders input in order to run on TIO. The OEIS sequences that list millions of elements were generated with some specialized algorithm or formula. However, this has to run in the general case, so it can't easily make logical deductions that a human can (SAT is NP-hard, so I doubt the time complexity can be much improved). ### Commented golfed code ``` from itertools import* T=tuple P=product def C(A,e,n): G=range(n); t=0;# t: total number of models found so far c=[] # c: list of isomorphic models of those already considered # A set would be better for time, but it takes a few too many bytes # to stringify dicts in a consistent way for m in P( # m is a model *[ [ dict(zip( P(*[G]*a), # inputs o )) for o in P(*[G]*n**a) # possible outputs ] for a in A # Why does this have to be enclosed in a list? ] # P: choose one mapping for each function ): # I place the definition of E here so it can take advantage of scope to access m,n E=lambda x,f:f[x]if x*0==0else m[x[0]][T(E(s,f)for s in x[1:])] # E: evaluate an eXpression given free variables f # haven't already considered an isomorphic model: if m not in c:\ c+=[ # append all isomorphic models T( { T(r[a]for a in k):r[f[k]] # apply mapping for k in f # to keys (inputs) and values (outputs) } for f in m ) for r in permutations(G) # r is a remapping, e.g. [0,2,1] on n=3 swaps 2 and 1 ];\ t+=all( # is the model valid? E(q[0],f)==E(q[1],f) # LHS and RHS are equal for q,N in e # when given each possible list of free variables for f in P(*[G]*N) ) return t ``` ### General idea ``` from itertools import* def execute(expr,free_vars,model,n): try: func_id, *params = expr params = tuple(execute(subexpr,free_vars,model,n) for subexpr in params) return model[func_id][params] except: # expr is an int ==> a variable return free_vars[expr] def get_all_models(): return product( *[ [ {i:o for i,o in zip( product(*[range(n)]*arity), # inputs output )} for output in product(*[range(n)]*n**arity) ] # possible outputs for arity in arities # Why does this have to be enclosed in a list? ] ) def relabellings(model,n): return [ tuple( { tuple(relabelling[a] for a in k): relabelling[e] for k,e in func.items() } for func in model ) for relabelling in permutations(range(n)) ] def model_works(model, equations, n): return all( execute(eq[0],free_vars,model,n) == execute(eq[1],free_vars,model,n) for eq, num_free_vars in equations for free_vars in product(*[range(n)]*num_free_vars) ) def count(arities, equations, n): total=0 considered = [] for model in get_all_models(): if model in considered: continue for r in relabellings(model, n): considered.append(r) if model_works(model, equations, n): total += 1 return total ``` ]
[Question] [ Related: [Read a crossword](https://codegolf.stackexchange.com/q/76966/78410) ## Task Given a completed Crossword puzzle, extract the words in it with their respective clue numbers, with "across" (horizontal) and "down" (vertical) words grouped and ordered like a real crossword puzzle. The words are numbered in the row-major order of their first letters. If an "across" word and a "down" word share the first letter, the two words share one number. (As in regular Crossword, single-letter words don't count; they should not be numbered or included in the output.) The input is given as a character matrix (or equivalent), with letters being uppercase (or lowercase if you want) and non-letter cells being blank. You can assume that single-letter islands won't appear in the input. If you want, you can assume the grid is rectangular (shorter rows are padded with spaces). The output must be clearly grouped into "across" and "down" (you don't need to return or print these strings though), and the words must be ordered in the increasing order of the clue number (see test cases). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` Input: MESS YAWN SAID TYPO Output: Across: 1. MESS 5. YAWN 6. SAID 8. TYPO Down: 1. MY 2. EAST 3. SWAY 4. SNIP 7. DO Input: RECURS PARAPET TRIANGLE COOLS RAW HUTS MATE ORE CODED INCLUDES RETIRES SYSTEM Output: Across: 1. RECURS 7. PARAPET 8. TRIANGLE 9. COOLS 10. RAW 11. HUTS 12. MATE 13. ORE 14. CODED 15. INCLUDES 17. RETIRES 18. SYSTEM Down: 1. RAILS 2. ERAS 3. CAN 4. UPGRADES 5. RELATES 6. STEWED 7. PROTECTS 8. TOURNEY 9. CHOIRS 12. MODEM 14. CURE 16. LIT Input: MICROWAVE U S M OCEAN C M OWL A I SWELL P E E SCHEDULES Output: Across: 1. MICROWAVE 3. OCEAN 7. OWL 8. SWELL 9. SCHEDULES Down: 1. MUMMIES 2. ESCAPES 4. COW 5. EWE 6. ALL Input: TAB A U BUBBLE B O LOVED E E Output: Across: 1. TAB 3. BUBBLE 5. LOVED Down: 1. TAB 2. BUBBLE 4. LOVE ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 118 bytes ``` WS⊞υιP⪫υ¶≔⟦⟧θFυ«Fι«F‹ κ«≔✂ιⅈLι¹η≔⪫KD⁻Lυⅉ↓ωζ≡÷⌕2374ce6⍘↨EKV‹ μ²φ³¦²⊞θ⟦ηζ⟧¹⊞θ⟦ηω⟧⁰⊞θ⟦ωζ⟧»→»⸿»⎚E²⪫EΦEθ⟦⊕μ§⪪§λι ⁰⟧§λ¹⪫λ ¦ ``` [Try it online!](https://tio.run/##VVLfa9swEH6u/orDTyfQoE3HBtlTPLuQ4axhWUpLmwfjqPFRRU5tOR4r/du9k@XQzPikT/fd6X6pKPO6qHLT911JRgPO7aF1K1eT3aGUsGybElsFJL@JRWscHZhx@KMi69XRk40kU7OmoZ3Fx42CVz4@VzVgK@FNXAyQBhhwppsGI4gUvMigvhi9V4YKjaTgHqWCTNudK9lVwRVLydd@mA7xl1q/JFTrwlFlcUG2bXD0atnjgfNXME2qzvLesfwNdzQduaL0pbqEjrTVeEN2i9Hk@uvnQn/hzOK80WMPPMRFfhii3VX2p273ubUhw1Mlex9pwvLswfWproJ9YTINTXxV8FhyDpuQxMBd/c9159zlGdd9@L2LIIvqqHH6i3al8wSrlsNkoqc6YsW7@G50XiPDoPclTBQMjfP4hozT9QB9hLktar3X1ukt7rmGmZvbrf6Dq4Mhh6eT8Q@Bpw4Rr5dyc2Zo/JjkGMAEm9GUH0jf/57FWZqAmMEa@BfxOmYFiAxiuAUQKWS3d2kiknUKKZ@Bv4T3/tPR/AM "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangular string of newline-terminated lines. Explanation: ``` WS⊞υιP⪫υ¶ ``` Input the rectangle and print it to the canvas. ``` ≔⟦⟧θ ``` Start off with no clues. ``` Fυ«Fι« ``` Loop over the rows and columns. ``` F‹ κ« ``` If the current character is not a space, then... ``` ≔✂ιⅈLι¹η ``` Get the substring of the current line starting at this character. ``` ≔⪫KD⁻Lυⅉ↓ωζ ``` Get the substring of the current column starting at this character by reading it from the canvas. ``` ≡÷⌕2374ce6⍘↨EKV‹ μ²φ³ ``` Check which orthogonally adjacent characters are spaces. ``` ²⊞θ⟦ηζ⟧ ``` If only the characters to the left and above are spaces, then a word starts both across and down. ``` ¹⊞θ⟦ηω⟧ ``` Otherwise if the character to the left is a space but the character to the right is not, then a word starts across but not down. ``` ⁰⊞θ⟦ωζ⟧ ``` Otherwise if the character above is a space but the character below is not, then a word starts down but not across. ``` »→»⸿» ``` Move on to consider the next character on each iteration. ``` ⎚ ``` Clear the canvas. ``` E²⪫EΦEθ⟦⊕μ§⪪§λι ⁰⟧§λ¹⪫λ ¦ ``` Map over the across and down clues, numbering them all, but keeping only those clues with words in the respective direction. (Out of interest I tried using just string manipulation instead of canvas operations but that cost 29 bytes.) [Answer] # perl -M5.010, 348 bytes ``` @a=map{[s/ /0/gr=~/./g,0]}<>;push@a,[(0)x@{$a[0]}];for$y(0..$#a-1){for$x(0..$#{$a[0]}-1){if($a[$y][$x]){$h=$a[$y][$x+1]&&!$a[$y][$x-1];$v=$a[$y+1][$x]&&!$a[$y-1][$x];$c++if$h||$v;if($h){print" $c. ";$i=$x;print$a[$y][$i-1]while$a[$y][$i++]}push@v,[$c,$y,$x]if$v}}}say;for(@v){($c,$y,$x)=@$_;print" $c. ";$i=$y;print$a[$i-1][$x]while$a[$i++][$x]}say ``` [Try it online!](https://tio.run/##ZU89b4MwFNzzK9z0KcLiywyZXCqCypYqS5MFWZWFQrCUBgQpBTn0p5faEOhQezjd3fOdX3Esz@u@D7j/wQsZVy5yiXsq/W/XcU8WYd3TMy0@qyzgVmwQ3AQSeKxkRtO8hNYgjgOP3Paw1LwZ@X1GqyI1FIGWxdAwLCHzZ2p6bLV6mKntMQr1aCtLz0@2PVIKiWmKFLLbDWqqkzMsi1JcrksEiYOWFIQPDR2kKVeox1@ZOB9nwTRZN6xUWzEkFrSWylaxddd1FW/1YkZQY2lMJvYDeKf/itq/InH/4VykS7SgA/v@bRMifRYbtB8w3IfhNkILhEK0Qxq3u0P0ojBSF/3kxVXkl6q3X9cO8cgv "Perl 5 – Try It Online") Requires the input to be a proper rectangle, that is, shorter lines should be padded with spaces. [Answer] # [Python 2](https://docs.python.org/2/), ~~284~~ ~~283~~ ~~281~~ ~~272~~ ~~267~~ 263 bytes *-2 bytes thanks to @Noodle9 for suggesting a different output format* ``` x=input() A=[];D=[] d=1;b='!' i=j=0 L=len while i<L(x):r=x[i];h=(r[j:].split()or b)[0];c=L(h)*(j<1or-~-q)>1;g=(''.join(r[j]for r in x[i:]).split()or b)[0];q=r[j]>b;a=L(g)*q*(i<1or x[i-1][j]<b)>1;D+=a*[d,g];A+=c*q*[d,h];d+=a+c*q>0;j=(j<L(r)-1)*-~j;i+=j<1 print A,D ``` [Try it online!](https://tio.run/##ZZBBj6IwFMfvfIq3XqAoE9mjtSYFmh2SIobCEEN6GJWREgPKulnnMl/dbdE9DSTk/@O9/vra8@e16buf931/qIlt2/cbUd35z9VBFiWVxJH@WAfi4x2xf9iWIi2ZW5yc6s7626hTDWrJnRtaDORWKYkb4gxVu5Avv88npSX9ADtUzSXeE@40yHXapd8P3pd3QSsfH4lj2y9trzqzSn7o7gFUB1q1kOib40JM12qH37XsiNyL6yijM/2eL3VtuTPaaEre3eowO0pMp2Sv@zQ0Eh/0/6nG1Ry3RE/CnQF5PnK9rxarKdGjWedBdVegs@iu7@J5Qn9R3@q9Y24I3atJwoSAyQwmW1quxwCCxtEY8u0mnUirsgEgY2GRCXsGGjY0oxuWj5BnMV3/4sxAmKZcQEZLA69FLiCh@VhJMwZhGrHIQLwOeRExAQYylseZziOIrchZonezza5JHGZpSd9GQwGPZxwhgTRkdA3hAyAtOQAd3SBKxjlsDLDnmlEgwlcWFZyJ0Z3TwFRMgULxPwZFEHAGj1MGkMIz8vTtMbp26VeP9w8 "Python 2 – Try It Online") Takes input as a list of strings representing the rows. The basic approach involves iterating over every square of the grid in left-to-right and top-to-bottom order. The counter `d` is incremented when a word can be made either across or down starting from the current square. **Some other notes** * `A` and `D` keep track of the lists of "across" words and "down" words respectively * To determine whether a square contains a space or a letter, the character gets compared to the `!` character (smaller means a space, larger means it's a letter) * When a word gets added to one of the lists, `.split()[0]` is called on the remaining portion of the row/column to get the entire word, which ends at the next space character [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 49 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ȧ€Œg⁸ṁȦƇḊƇZ€ḢḢ,Ɗ€)ẎṢ n⁶a⁸ŒĖṁ⁸Ç,ZÇ$ƊµẎZḢQṢiⱮⱮⱮȯ""" ``` A monadic Link which accepts a (rectangular) list of lists of characters which yields a list of lists of pairs of numbers and lists of characters ...i.e. `[across, down]` where each of `across` and `down` are lists of `[clueNumber, answerWord]`. **[Try it online!](https://tio.run/##y0rNyan8///EskdNa45OSn/UuOPhzsYTy461P9zRdaw9Cij6cMciINI51gVkaz7c1fdw5yKuvEeN2xKBao9OOjINqB7IOtyuE3W4XeVY16GtQDVRQB2BQIWZjzaug6AT65WUlP4/3L3lcHsW0CAQatynp@ANYjTMcUwuyi8utgKyXPLL84D03KN7QFKR//8rKCgEK2ABXAoKjgGuSFKOAY5BIRCJIEc/kIgPiHADS4Z7@vhwBQS5Onv6hwYr@Ct4Bvs4@rkEK7j4Q3QouLqArAFq81cIQrYDClxRLQcA "Jelly – Try It Online")** (The footer splits at newlines, calls the Link and formats the result like the question examples.) ### How? We find all the 2+ letter horizontally written words along with the (2d) index of their first letter in the input matrix for each of the input matrix and its transpose, then sort these (by those indices), and look up each of these starting-indices in a list of the unique starting-indices for the combined results to find the clue-numbers. ``` Ȧ€Œg⁸ṁȦƇḊƇZ€ḢḢ,Ɗ€)ẎṢ - helper Link: list of lists of pairs of 2-d indices and their characters (or 0s where spaces were) ) - for each row: Ȧ€ - for each pair: any and all? (0 if it contains a 0 (i.e. character was a space)) Œg - group runs of equal elements ⁸ṁ - mould like the input Ƈ - filter keep those for which: Ȧ - any and all? - i.e. throw away "words" of 0s Ƈ - filter keep those for which: Ḋ - dequeue - i.e. throw away words of length 1 Z€ - transpose each € - for each: Ɗ - last three links as a monad - f(X=that): Ḣ - head (modifies X too) Ḣ - head (modifies X too) , - pair with (the modified X) Ẏ - tighten Ṣ - sort n⁶a⁸ŒĖṁ⁸Ç,ZÇ$ƊµẎZḢQṢiⱮⱮⱮȯ""" - Link: list of lists of characters (C) ⁶ - space character n - (C) not equal (space)? (vectorises) a⁸ - logical AND (C) (vectorises) -> C but with 0s not spaces ŒĖ - multi-dimensional enumerate -> [[[1,1],'A'],...,[[n,m],'Z']] ṁ⁸ - mould like C Ɗ - last three links as a monad - f(X=that): Ç - call the helper Link with X $ - last two links as a monad: Z - transpose X Ç - call the helper Link with that , - pair these together µ - start a new monadic chain - f(V=that): Ẏ - tighten V Z - transpose Ḣ - head -> all word-start indices Q - deduplicate Ṣ - sort ⱮⱮⱮ - 3-deep map across v in V with: i - first 1-based index of v or 0 if not found """ - zip across, 3-deep with: ȯ - logical OR (V) -> replace the 0s with the words from V ``` [Answer] # JavaScript (ES6), 179 bytes Takes input as a matrix of characters. Returns a pair of objects. ``` m=>m.map(F=(r,y)=>r.map((c,x)=>i+=1/c?0:(g=(d,s=c,Y=y)=>!(C=m[Y+=d]&&m[Y][x+=!d])|C<F?s[1]&&!!(o[d][i]=s):g(d,s+C,Y),!y||m[y-1][x]<F?g(1):0)|(!x|r[x-1]<F&&g(0))),i=1,o=[{},{}])&&o ``` [Try it online!](https://tio.run/##fZFfa6swGMbv@yleeyEJzVy9LctGTNNN0KYYnUjIRdFNOuYcdYyWuc/e2XN2IB7Ykps8P95/z5un7fu2K/e717eLl7Z6OD3SU0OvG6/ZvqIVRXtyxPR6/0eikhwGsZtR/7K8mS9QTVFFOlqSgp6jHMRpo4sZrYzrDg@jDzPqVAb3/Gp102l/wI6DWl0ZvTO0w4v6nD/jpMDEOfZ9o48X/pBlhvAa@Xgxxz1yDv1eHwZ@tXLdGs0xxmRHfdJS/fFJPj4Ndt32VLYvXfv84D23NXpEegKgPc@bxkIpmBryTxcsX9saFAuXtk6LjZyaicF48kNJAEgEzxJlp8GGJWwj0lGpJGTr20hYjEsZKUhYbrG7LFUQs9SOk4kALpfCHi1c8yhbipGdRKRhMiCbqUKlIoYz@81GHPJE5uzebpvB32Nbi0FywdbARwxkHgEwezxQuYgi2FhMfNezeyh@J5ZZJNTv46UsABj5YpD9R4IsCCIx@k4IQMKYRPJ@tMdhnOF@b@f0BQ "JavaScript (Node.js) – Try It Online") ]
[Question] [ At the time of writing this puzzle, there are soon to be [269 puzzles related to primes](https://codegolf.stackexchange.com/questions/tagged/primes). To celebrate/mourn this event (269 is prime), this challenge will be about exploding primes. In preparation for this task, I've obtained a permit (legal, I assure you) for dynamite charges of military grade, along with enormous dynamite itself. Unfortunately, I also have a lot of junk in my warehouse, and I've packaged everything (and I mean *everything*) into ASCII text. From sizes 1 to 6 (actual input sizes can be arbitrarily large), here are examples of my enormous dynamite: ``` + ___L__ + | | __L__ | | + | || | __L_ | || | + | || || | _L_ | || || | + | || || || | _L | || || || | + | || || || || | L | || || || || | | || || || || || | |_||__||___||____||_____||______| __________________ _______________ | | ____________ | | | | _________ | | | | | L-* ______ | | | L-*| L-*| | ___ | L-*| L-*| | | | | | |___L-*|______| |_________| |____________| |_______________| |__________________| ``` The pattern for size `n` vertical dynamite is two `2n`-high columns of `|` separated by `n` spaces in the middle/`_`s on the bottom and top. The bottom `_`s will be surrounded by `|`s, but the top `_`s will be surrounded by spaces. There will be an `L` under a `+` replacing the mid-point (biased right) of the top `_`s. The pattern for size `n` horizontal dynamite is two `n`-wide rows of `_` separated by `n-1` space-filled rows in the middle. There will be `n+1`-high columns on the left and right, out of which the top character will be a space, and others will be `|`. There will be an `L` with a `*` on the right replacing the mid-point (biased upwards) of the right `|`s. As my best and brightest assistant, you will need to help me determine how many primes each ASCII package (input grid) can destroy. Your task is to count all the valid dynamite within a package, taking into account the size. You will output a string like so: `BOOM! # prime(s) primed for destruction`, where `#` is the total computed dynamite size in the package. # Examples ``` Input: ______ | L-* |______| Output: BOOM! 2 prime(s) primed for destruction Reasoning: Single piece of dynamite of size 2 Input: Output: BOOM! 0 prime(s) primed for destruction Reasoning: Empty string contains no dynamite Input: __+_ \_|_\ /_|_/ ___L___ ~~\_____/~~ Output: BOOM! 0 prime(s) primed for destruction Reasoning: Despite being cute and non-empty, this ASCII ship from my warehouse has no dynamite in it Input: ____________ | | | ___ L-* | |___L-* | |____________| Output: BOOM! 1 prime(s) primed for destruction Reasoning: Dynamite is non-recursive - the outer dynamite doesn't count at all, but the inner dynamite is valid and will blow up 1 prime. Input: + L | | |_| Output: BOOM! 0 prime(s) primed for destruction Reasoning: A space character is missing to the right of the L - the box must be fully complete, although the + for vertical and -* for horizontal dynamite are not necessarily space-padded; all that is required for those elements is that they be aligned with the L. Input: + __L__ + | | __L_ | | + | || | _____________________ _L_ | || || | + | || || || | _L | || || || | + | || || || || L-* L | || || || || | | || || || || || | |_||__||___||____||_____||_____________________| Output: BOOM! 18 prime(s) primed for destruction Reasoning: The size-4 dynamite is malformed, but all the other pieces of dynamite are valid. Summing the dynamite sizes within this package yields 1 + 2 + 3 + 5 + 7 = 18 units of dynamite. Input: A C+C M L M E | | E M|_|M C C A Output: BOOM! 1 prime(s) primed for destruction Reasoning: The dynamite's box is properly surrounded by spaces, and the tip is not required to be surrounded by spaces. Therefore, this is a valid piece of dynamite that can explode 1 prime. Input: + L ______ | | L-* |_|______| Output: BOOM! 3 prime(s) primed for destruction Reasoning: Although the 2 pieces of dynamite intersect, each on their own satisfies the parameters for enormous dynamite. Therefore, the pieces can explode 1 + 2 = 3 primes together. ``` # Rules Input will be an ASCII grid/string of characters in any reasonable format. Output must be a correctly computed string consisting of `BOOM! # prime(s) primed for destruction`, where `#` is the total computed dynamite size in the input. Your answer may be a function or full program (both will be scored according to the same metrics). Exploiting standard loopholes is forbidden. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest code wins. Go out there and explode some primes :) [Answer] # JavaScript (ES8), ~~298 ... 272~~ 267 bytes Takes input as an array of strings. ``` a=>`BOOM! ${a.map((s,y)=>s.replace(/ _*(L?)_*(?= )/g,(s,L,x)=>t+=(w=s.length,L?y&&s[d=w+1>>1]+a[y-1][k=w*2-1,x+d]=='L+'&&~-w:k=w/3|0)*(v=L?0:++k+1>>1,g=c=>!--k||(a[y+k]+g).indexOf('|'.padEnd(w,c)+(--v?'|':'L-*'),x)==x&g())`_`),t=0)|t} prime(s) primed for destruction` ``` [Try it online!](https://tio.run/##lVNtr5owFP7ur@hNFtpSCrp9Mynkzvitxh@gpBJA5vQCASaadf511wLeqw63eZKW8/acN06/B/ugDItNXtE0i@Lzmp0D5q6@zuezF/DpZ2C/BTlCpXXEzC3tIs53QRgjBwgTcQ@r22MAO4mlXLh1UE4VYahmpb2L06T6ZnHvaBjlImI1GbnuyCfB4khH/mLLavMzHVkHEvmMQU6gYZxoPVZ654scYhPtGfeGY0K2DdBKWMjcF0q3UiIVg2x9kmB7k0bxYb5GUEI7D6JpGqHaCjFBlO49pRxDTk2IdWXsYCQI45VYYatiQyyrXyAvNm8xKnHLRGCdFSCKy6r4EVabLF2dwywts11s77IErdFiAIFoCEBrACVoSGfQUmuRcOBjPLgH9umgAgtBhEYrdrkUUiyXneQowWl5FZWro4XTSXlpck4n@CCouKLrOluS7xptvq5fG3Uqal68riPJR@lIUyRvQ3S4h859RNTpmr6npvFeIwHyo50/ML1GladRy854M6jbib3HuoS6YGRvBx952rLkMxjBn8Q0OeT/Yrq/C/hTqG5L5PMYIdXa6NNe3X353NNfFuW1HdCETBpmpjqYaW6qGpFg2ipVulnnBybdRF//sam3T/j@Ed884/Nv "JavaScript (Node.js) – Try It Online") ## How? For each line, we look for the following pattern: ``` / _*(L?)_*(?= )/g ``` The above regular expression matches a space followed by a sequence of `_` with or without a single `L` within it, followed by a space. We use a lookahead for this last space, so that it can be combined with the first space of another pattern immediately following. If a `L` is captured, the pattern is interpreted as the top of a vertical dynamite stick. In this case, we make sure that the `L` is located at the expected position and that there is a `+` above it. If no `L` is captured, the pattern is interpreted as the top of a horizontal dynamite stick. In both cases, we use the recursive helper function \$g\$ to test the body of the stick. There's a special case in this function to make sure that we have `L-*` at the end of the middle row of a horizontal stick. All other rows are expected to be a sequence of `_` or spaces surrounded by two `|`. ## Commented ### Wrapper ``` a => `BOOM! ${...} prime(s) primed for destruction` ``` ### Main code ``` a.map((s, y) => // for each string s at position y in the input a[]: s.replace( // for each string s / _*(L?)_*(?= )/g, // matching / _*(L?)_*(?= )/ (s, L, x) => // with L = captured 'L' and x = position: t += ( // update t: w = s.length, // w = length of matched string L ? // if a 'L' was captured: y && // if y is not equal to 0 s[d = w + 1 >> 1] + // and the character at floor((w+1)/2) a[y - 1] // followed by the character above it ... [k = w * 2 - 1, x + d] // (set k to 2w-1) == 'L+' && ~-w // ... form the string 'L+', yield w-1 : // else: k = w / 3 | 0 // yield k = floor(w/3) ) * ( // multiply this by the result of g(): v = L ? 0 // if a 'L' was captured, set v to 0 : ++k + 1 >> 1, // else, increment k and set v to floor((k+1)/2) g = c => // g is a recursive function taking a character c: !--k || // decrement k and stop if it's equal to 0 (a[y + k] // otherwise, take the entry at y+k, + g) // coerce it to a string in case it's undefined, .indexOf( // look for the position of this substring: '|'.padEnd(w, c) + // a '|' followed by c repeated w-1 times (--v ? '|' : 'L-*'), // followed by either a '|' or 'L-*' if v = 0 x // starting from x ) == x // and make sure it's equal to x & g() // recursive call with c undefined )`_` // initial call to g with c = '_' ), // end of replace() t = 0 // start with t = 0 ) | t // end of map(); return t ``` [Answer] # [Perl 5](https://www.perl.org/) (`-Minteger` `-00p`), 323 bytes Gives the correct output for tests, to be golfed more ``` for$s(2..y/ //){$t=$s-1>>1;$u=$s/2-1;$v=2*$s-1;s/^ (___){$s} .* (\|( ){$s}\|.* ){$t}\|(?3){$s}L-\*.* (?2){$u}\|(?1){$s}\||^...{$u}\+.* __{$u}L_{$t} .* (\| {$s}\|.* ){$v}\|_{$s}\|/$\+=$s;$&/gme}s/^ ___ .* \|___L-\*|^.\+.* L .* \| \|.* \|_\|/$\++;$&/gme;s/^.//gm&&redo}{$\|=0;$\="BOOM! $\ prime(s) primed for destruction" ``` [Try it online!](https://tio.run/##lVRNb@IwEL37V0yRBWmi2MBqL43Saot6S9Q/YDGHJa2QConyUWmF4ac3nbFDxRYOxZKdmXnznp9tRFXUb797ielksn7RS6Ok3iTSUJpU9Xrbwmi9rbr2TkgUZeeiUbLrX8paNsFcqX9aaH27k20qm3h2fz9LZEehnscUvafzkMtJo5cQICI1NntQoQiMDQDA5cZSgSUoCh5@uVoWm5DbHuaUdg6YDc12qZRyxYg6AJHjDJk/KMOp6jtF6Atamoi8JXKsXzfFnk2RJyZRCyLvSeJeNvNlcDIEe3Y0cPlASlM0HtfFqtzvpLHplO9t9Pj8nN@ANEDXtymC5tYHK6Arg1XRtHX3t12X21FP7SqdiEnibn/fsxn2Iyy4kcWhsL5mhRBKCCoiRshfg@SJA02BFgxgRlMcDsZR9OFAJDGIfpP2w/qUga/9uOzuInT4KZtNQERXQ10MufzSiGheQpzDcyQCO9g56z5HSNvV7ID8d76Tg36pHEWOBHvR8rCDt2J/TMDsGoJTtz8l8HNAdhWFH9ReSUBLj8zTL8N6/Hwfw5v/oWURLQTk5DAXT@TSwhOlJJczBgvfJj7Kin/tTR9Pp1Uf5/SXUrwW9Sc "Perl 5 – Try It Online") ]
[Question] [ # Background An **ex-increasing set sequence** of order \$N\$ is defined as a sequence of integer sets \$S\_1,S\_2,\cdots,S\_n\$ which satisfies the following: * Each \$S\_i\$ is a non-empty subset of \$\{1,2,\cdots,N\}\$. * For \$1\le i<n\$, \$S\_i \cap S\_{i+1} = \varnothing\$, i.e. any two consecutive sets have no elements in common. * For \$1\le i<n\$, the mean (average value) of \$S\_i\$ is strictly less than that of \$S\_{i+1}\$. # Challenge Given a positive integer `N`, output the length of the longest ex-increasing set sequence of order `N`. # Test cases These are based on [the results by Project Euler user **thundre**](https://projecteuler.chat/viewtopic.php?f=16&t=3605#p39060). ``` 1 => 1 // {1} 2 => 2 // {1} {2} 3 => 3 // {1} {2} {3} 4 => 5 // {1} {2} {1,4} {3} {4} 5 => 7 // {1} {2} {1,4} {3} {2,5} {4} {5} 6 => 10 // {1} {2} {1,4} {3} {1,4,5} {2,3,6} {4} {3,6} {5} {6} 7 => 15 // {1} {2} {1,4} {3} {1,2,7} {3,4} {1,2,5,7} {4} {1,3,6,7} {4,5} {1,6,7} {5} {4,7} {6} {7} 8 => 21 9 => 29 10 => 39 11 => 49 12 => 63 13 => 79 14 => 99 15 => 121 16 => 145 17 => 171 18 => 203 19 => 237 20 => 277 21 => 321 22 => 369 23 => 419 24 => 477 25 => 537 ``` ## Rules Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest valid submission in bytes wins. # Bounty This problem has been discussed [here on Project Euler forum](https://projecteuler.chat/viewtopic.php?f=16&t=3605) about 4 years ago, but we failed to come up with a provable polynomial-time algorithm (in terms of `N`). Therefore, I will award +200 bounty to the first submission that achieves this, or prove its impossibility. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` ⟦₁⊇ᶠk⊇pSs₂ᶠ{c≠&⟨+/l⟩ᵐ<ᵈ}ᵐ∧Sl ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGh91tT/ctiAbSBUEFz9qagJyqpMfdS5QezR/hbZ@zqP5Kx9unWDzcGtHLZB@1LE8OOf/f@P/UQA "Brachylog – Try It Online") This is really damn slow. Takes about 30 seconds for `N = 3`, and it didn't complete after 12 minutes for `N = 4`. ### Explanation ``` ⟦₁ Take the range [1, …, Input] ⊇ᶠk Find all ordered subsets of that range, minus the empty set ⊇ Take an ordered subset of these subsets pS Take a permutation of that subset and call it S Ss₂ᶠ Find all substrings of 2 consecutive elements in S { }ᵐ Map for each of these substrings: c≠ All elements from both sets must be different &⟨+/l⟩ᵐ And the average of both sets (⟨xyz⟩ is a fork like in APL) <ᵈ Must be in strictly increasing order ∧Sl If all of this succeeds, the output is the length of L. ``` ### Faster version, 39 bytes ``` ⟦₁⊇ᶠk⊇{⟨+/l⟩/₁/₁}ᵒSs₂ᶠ{c≠&⟨+/l⟩ᵐ<₁}ᵐ∧Sl ``` This takes about 50 seconds on my computer for `N = 4`. This is the same program except we sort the subset of subsets by average instead of taking a random permutation. So we use `{⟨+/l⟩/₁/₁}ᵒ` instead of `p`. ``` { }ᵒ Order by: ⟨+/l⟩ Average (fork of sum-divide-length) /₁/₁ Invert the average twice; this is used to get a float average ``` We need to get a float average because I just discovered a ridiculous bug in which floats and integers don't compare by value but by type with ordering predicates (this is also why I use `<ᵈ` and not `<₁` to compare both averages; the latter would require that double inversion trick to work). [Answer] ## CJam (81 bytes) ``` {YY@#(#{{2bW%ee{)*~}%}:Z~{)Z__1b\,d/\a+}%$}%{_,1>{2ew{z~~&!\~=>}%0&!}{,}?},:,:e>} ``` [Online demo](http://cjam.aditsu.net/#code=%7BYY%40%23(%23%7B%7B2bW%25ee%7B)*~%7D%25%7D%3AZ~%7B)Z__1b%5C%2Cd%2F%5Ca%2B%7D%25%24%7D%25%7B_%2C1%3E%7B2ew%7Bz~~%26!%5C~%3D%3E%7D%250%26!%7D%7B%2C%7D%3F%7D%2C%3A%2C%3Ae%3E%7D%0A%0A3%5C~). It should execute for input `4` in a reasonable time, but I wouldn't try it with higher inputs. ### Dissection ``` { e# Declare a block (anonymous function) YY@#(# e# There are 2^N subsets of [0, N), but the empty subset is problematic e# so we calculate 2^(2^N - 1) subsets of the non-empty subsets { e# Map integer to subset of non-empty subsets: { e# Define a block to map an bitset to its set indices; e.g. 9 => [0 3] 2bW%ee e# Convert to base 2, reverse, and index {)*~}% e# If the bit was set, keep the index }:Z e# Assign the block to variable Z ~ e# Evaluate it { e# Map those indices to non-empty subsets of [0, N): )Z e# Increment (to skip the empty set) and apply Z __1b\,d/ e# Sum one copy, take length of another, divide for average \a+ e# Wrap the subset and prepend its average value }% $ e# Sort (lexicographically, so by average value) }% { e# Filter out subsets of subsets with conflicts: _,1>{ e# If the length is greater than 1 2ew e# Take each consecutive pair of subsets { e# Map: z~ e# Zip and expand to get [score1 score2] [subset1 subset2] ~&!\ e# No element in common => 1 ~= e# Different scores => 0 > e# 1 iff both constraints are met }% 0&! e# 1 iff no consecutive pair failed the test }{ , e# Otherwise filter to those of length 1 }? }, :,:e> e# Map to size of subset and take the greatest } ``` [Answer] # JavaScript (ES6), 175 bytes A naive and rather slow recursive search. Takes about 15 seconds to compute the 7 first terms on TIO. ``` n=>(a=[...Array(n)].reduce(a=>[...a,...a.map(y=>[x,...y],x=n--)],[[]]),g=(p,b=a,n)=>a.map(a=>(m=a.map(n=>s+=++k*b.includes(n)?g:n,s=k=0)&&s/k)>p&&g(m,a,-~n),r=r>n?r:n))(r=0)|r ``` [Try it online!](https://tio.run/##JY3LboQwDEX38xVZobgxaburpnVG/Q6URQYCmgIOcjrVoD5@nQbNxvY9utb5CF8ht3JZPmtOXdx62picDtRYa99FwqoZvJXYXdtYsNt5wH3YOSx6LeS2x9XjjbiuwWPTeA84kF7wTAEZyN3L5V3PdL@LJRsyZnw42wu307WLuahOw5Ex00hPUFX5cQS3VNWgZwxY/zGgkDg@yZEBtJTSj2x9Es2K1POrYvWmXsoyBtT3Qak2cU5TtFMaNKPqiwAOv9s/ "JavaScript (Node.js) – Try It Online") or [test this modified version](https://tio.run/##JU67bsMwDNzzFZocqqLVdiuc0oHXDC2QjoYGxS@4tmlDSoIYRfvrrpwsPN6Bd8dve7W@cO10jnksq6WmhSkFS7nWOnPOzsDSaFeVl6IKcrrqFtehBzvBHJTbSmeDN@I4lgbz3BiJDcGEJ7LImFFuJKUPR8iAgR57qPKKlOqeTrrlor@UlQ99@yZh9NTRi4wi/9zJdIqiBga0GP8x3l9DGzocuZT3LoEjZchSSnB3z3GpRwcsSLzuBIt38RZAKSl@NkIUI/uxr3Q/NuFEiW0itgEOX58f2p9dy01bz1DDmrf5Xf4B) that outputs the longest ex-increasing set sequence. ### How? We first compute the powerset of \$\{1,2,\dots,n\}\$ and store it in \$a\$: ``` a = [...Array(n)].reduce(a => [...a, ...a.map(y => [x, ...y], x = n--)], [[]] ) ``` Recursive part: ``` g = ( // g = recursive function taking: p, // p = previous mean average b = a, // b = previous set n // n = sequence length ) => // a.map(a => // for each set a[] in a[]: (m = a.map(n => // for each value n in a[]: s += // update s: ++k * b.includes(n) ? // increment k; if n exists in b[]: g // invalidate the result (string / integer --> NaN) : // else: n, // add n to s s = k = 0) // start with s = k = 0; end of inner map() && s / k // m = s / k = new mean average ) > p // if it's greater than the previous one, && g(m, a, -~n), // do a recursive call with (m, a, n + 1) r = r > n ? r : n // keep track of the greatest length in r = max(r, n) ) // end of outer map() ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~205~~ ~~197~~ ~~184~~ 182 bytes * Saved ~~eight~~ twenty-one bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` f=lambda N,c=[[1]]:max([len(c)]+[f(N,c+[n])for k in range(N)for n in combinations(range(1,N+1),k+1)if not{*c[-1]}&{*n}and sum(c[-1])/len(c[-1])<sum(n)/len(n)]);from itertools import* ``` [Try it online!](https://tio.run/##Nc1NDoIwEAXgq8zKTAFjGjdG5QpcoOmi/FQb6QwpNdEQzo5Q4ixeJt9bvOEbn0znZbFlb3zdGqiKplRKan315oOq7wgboXNlcW1yRVpYDvACRxAMPTqsEtAGDfvakYmOacS9lUWVS1G81nAWiOOUNeoo9XyYMpoNtTC@PSYSpzSW3vumtAsJLW42sAcXuxCZ@xGcHzjEbBmCo4i9GyN6M6At4D8LF7He8gM "Python 3 – Try It Online") ]
[Question] [ An ordinary N-digit combination lock consists of N rotating discs. Each disc has digits 0-9 inscribed in order, and you need to turn them to the correct password to open it. Obviously, if you don't know the password, you will need to try at most 10N times before unlocking it. That's not interesting. [![combination lock](https://i.stack.imgur.com/4OUuM.jpg)](https://i.stack.imgur.com/4OUuM.jpg) So let's consider a variant of combination lock, name it distance-revealing lock. In every unsuccessful attempt to open an distance-revealing lock, it will respond the minimum number of movements to unlock. One movement is defined as a rotation by one position, for example it needs 1 movement from `890` to `899`, and 9 movements from `137` to `952`. # The Challenge Given a distance-revealing lock with its password unknown, try to open the lock with a minimal number of **attempts** (not movements), while keeping the program from getting too long. # Rules & Scorings * You should write a full program which inputs from stdin and outputs to stdout. The program should do input/output as following: ``` Start Input an integer N (number of digits) from stdin Do Output a line containing decimal string of length N (your attempt) to stdout Input an integer K (response of the lock) from stdin While K not equal 0 End ``` * Your program should handle up to N = 200, and should run less than 5 seconds on any input. * Leading zeros in output shouldn't be omitted. * The are 5 testdata for every length, so the total number of testdata is 1000. The testdata are randomly generated. * **The final score will be (total number of guesses in all testdata) \* ln(code length in bytes + 50).** Lowest score wins. (ln is natural log) * **I will score the program for you.** If you want to know how I will score your program, or you want to score it by yourselves, take a look at [previous edits on this post](https://codegolf.stackexchange.com/revisions/148639/11). * This challenge will end at 2017/12/07 14:00 UTC. I will post my solution then. # Running Example Lines starting with `>` represent input, and others represent program output. **You can have a password in your mind and interact with your program to test it.** ``` > 3 # 3-digit lock. The hidden password is 746 000 # 1st guess (by program) > 11 # response to the 1st guess 555 # 2nd guess > 4 # ... 755 > 2 735 > 2 744 > 2 746 # finally the correct answer! The program attempts 6 times. > 0 # this is not necessary ``` # Sample Program **EDIT:** Maybe the input/output format above was not clear. Here's a sample program in Python. **Python, 369 bytes, total number of attempts = 1005973, score = 6073935** ``` import sys N = int(input()) # get the lock size ans = '' for i in range(N): # for each digit lst = [] for j in range(10): # try all numbers print('0' * i + str(j) + '0' * (N - i - 1)) # make a guess result = int(input()) # receive the response lst.append(result) ans += str(lst.index(min(lst))) print(ans) # output the final answer ``` *Thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah) for simplifying the challenge.* [Answer] # C, ~~388~~ ~~374~~ 368 bytes, total attempts = 162751, score = 982280 ``` char s[999];i;G;H;t;n;h;e;R(x){scanf("%d",x);}W(i,x,a){printf((i-n?0:4)+"%0*d%0*d\n",i,x,n-i,0);R(a);}S(k,i){if(!(t=e=k>4?s[i]=48:k<1?s[i]=53:!G?H=k,G=i:0)){for(;t++<n;)putchar(48|t==i|t==G);puts("");R(&t);t==h?W(G,e=1,&t):0;s[G]=t>h?53+H:53-H,s[i]=t>h^e?53+k:53-k;G=0;}}main(){R(&n);for(W(n,0,&h);i++<n;S(t-h+5>>1,i))W(i,5,&t);s[G]=53+H,puts(s+1),s[G]=53-H,puts(s+1);} ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 617 bytes, total attempts = 182255, score = 1185166 ``` using System;namespace p{class C{static void Main(){var l=Console.ReadLine();int L=int.Parse(l);var g=new int[L];var p=n(g);for(int i=0;i<L;i++){g[i]=5;var d=n(g);var f=d-p;var s=f;switch(s){case 5:g[i]=0;d-=5;break;case-5:break;case 3:g[i]=1;d=n(g);f=d-p;if(f>0){g[i]=9;d-=2;}break;case 1:g[i]=2;d=n(g);f=d-p;if(f>0){g[i]=8;d-=4;}break;case-1:g[i]=3;d=n(g);f=d-p;if(f>0){g[i]=7;d-=4;}break;case-3:g[i]=4;d=n(g);f=d-p;if(f>-3){g[i]=6;d-=2;}break;}p=d;}n(g);}static int n(int[] g){foreach(var i in g){Console.Write(i);}Console.WriteLine();var s=Console.ReadLine();var d=int.Parse(s);if(d<1) Environment.Exit(0);return d;}}} ``` Hopefully C# in this format works for you. It is in the form of a complete program, so there should be a way to compile to an executable. Let me know if there's anything I can do to make it easier. Bytes are part of the scoring even though the Code Golf tag is removed so my official submission removes all the unneeded whitespace and useful names. My explanation below will use fragments of the ungolfed code: ### Explanation This program uses only a single helper method: ``` static int newGuess(IEnumerable<int> guess) { foreach (var item in guess) { Console.Write(item); } Console.WriteLine(); var distanceString = Console.ReadLine(); var distance = int.Parse(distanceString); if (distance < 1) System.Environment.Exit(0); return distance; } ``` This writes the guess to stdout, then reads the distance from stdin. It also immediately ends the program if a guess is the exact combination. I call it a lot. Next the initial setup: ``` var lengthString = Console.ReadLine(); int length = int.Parse(l); var guess = new int[length]; var prevDistance = newGuess(guess); ``` This gets the length of the combination, then starts guessing with all 0s. Afterwards, it iterates through each digit in a `for` loop. ``` guess[i] = 5; var distance = newGuess(guess); var difference = distance - prevDistance; var switchVar = difference; switch (switchVar) ``` For each digit, it guesses 5, then decides on the next step based on how the distance changed since the previous guess (where that digit was 0). ``` case 5: guess[i] = 0; distance -= 5; break; ``` If the distance increased by 5, then 0 was correct for that distance. Adjust that digit back to 0. Altering the recorded distance manually prevents an extra guess. ``` case -5: break; ``` If the distance decreased by 5, then 5 is the correct digit and we move to the next digit immediately. After that things are tricky. Using `5` and `0` for my initial guesses means that the remaining difference possibilities are `3, 1, -1, -3` with 2 possibilities for each, which need 1 additional guess to distinguish. Each of these cases takes a similar form ``` case 3: guess[i] = 1; distance = newGuess(guess); difference = distance - prevDistance; if (difference > 0) { guess[i] = 9; distance -= 2; } ``` Some of the numbers change, but essentially we try one of the two possibilities, and check whether the change was the correct one for that digit. If it wasn't, then the other digit is correct so we set that digit then adjust the difference manually. This method means we should require, at most, 1 guess for the initial 0s, 2 guesses per digit, and then 1 final guess to ensure the last digit doesn't fall through. ~~It might be buggy though, it works as far as I've checked manually but that's no guarantee.~~ Bug found and squashed thanks to Colera Su [Answer] # Python 2 and 3: 175 bytes, total attempts = 1005972, score = 5448445 This program takes ceil(log(n))\*10 attempts per combination or every single digit takes 10 attempts (so, `333` takes 30 attempts). ``` N=int(input());o=0 def c(a): print("0"*(N-len(str(a)))+str(a)) return int(input()) for j in range(N):m={c(i):i for i in reversed(range(0,10**(j+1),10**j))};o+=m[min(m)] c(o) ``` Huge thanks to Colera Su for helping me with the input/output functionality. # Python Version of Challenge ([Modified by OP](https://codegolf.stackexchange.com/posts/148642/revisions)). I wrote a version of the lock code inside of Python. You can go ahead and use if you're trying to solve this in Python (like me). The following works in Python 2 and 3. It made a lot more sense just to implement lock as a class you can test against and I decided to create a generator function for guessing the inputs. ``` import sys class Lock: def __init__(self, number): self.lock = str(number) def l(self): #lengthOfNumber return len(self.lock) def c(self, guess): #check a guess guess = str(guess) guess = "0" * (len(self.lock) - len(guess)) + guess difference = 0 for i in range(len(self.lock)): d1 = abs(int(self.lock[i]) - int(guess[i])) d2 = 10 - d1 difference += d1 if d1 < d2 else d2 return difference def masterLock(): testdata = ["000","555","755","735","744","746"] for answer in testdata: yield Lock(answer) class LockIO: def __init__(self): self.lock = int(input()) def l(self): return self.lock def c(self, guess): guess = str(guess) guess = "0" * (self.lock - len(guess)) + guess print(guess) sys.stdout.flush() return int(input()) for l in masterLock(): # Write your code here that tries to guess it # When you're done testing you can unindent your code, # replace "for l in masterLock():" with "l = LockIO()" # and submit the code. # # Examples: # l.l() # returns the length of the lock # l.c("952") # returns the distance to the lock # l.c(952) # number also works pass ``` [Answer] # [R](https://www.r-project.org/), ~~277 bytes (score=1175356)~~ 258 bytes, total attempts = 202999, score = 1163205 ``` f=file("stdin","r") w=function(b=1,A=X){cat(A,"\n",sep="");if(b){b=scan(f,n=1)};b} M=0:9 s1=c(-5,-3,-1,1,3,5,3,1,-1,-3) s2=s1+rep(c(1,-1),,,5) L=w(1,"") X=S=rep(0,L) v0=w() for(i in 1:L){X[i]=5 v1=v0-w() X[i]=4 v2=v0-w() S[i]=M[s1==v1&s2==v2] X=0*S} b=w(0,S) ``` [Try it online!](https://tio.run/##NY6xasMwEIb3e4qgIejaM0h23JKEG7I7kxdDmiFWLBAUJViuMhg/uysVOtzwf//x3Y3ratm670GKMN2dFyRGgfBi@@PN5B5e9qzpxB3O5jbJE4mvtBOGJwuBR2dlj3PPwdy8tORZ43LsFzizOuwhaDayqKmoqNCkqaI6jc6hqBBCyUG/j8NTGpkhElGN0PArxWSHjlvOtaIGIarEEexjlG7j/EYfGpy7i7tyDVFzVEWu/8AOYvkP2gzOl/QKR71NJzmW12RWb@0CfVIqanFdS6hhBxV8wOcv "R – Try It Online") Stdin-stdout version, as requested by the OP, no boilerplates. Thanks to Colera Su for fixing an initial bug. This is a marginally shorter version than the one in the comments. --- Here below the TIO submission to run a batch of tests within TIO # [R](https://www.r-project.org/), 189 bytes ``` M=0:9 s1=c(-5,-3,-1,1,3,5,3,1,-1,-3) s2=c(-4,-2,0,2,4,4,2,0,-2,-4) f=function(L){S=rep(0,L) v0=v(S) X=S for(i in c(1:L)){X[i]=5 v1=v0-v(X) X[i]=4 v2=v0-v(X) S[i]=M[s1==v1&s2==v2] X[i]=0} S} ``` [Try it online!](https://tio.run/##XVHBisIwEL3PVwTFJYMTSGo9rJjj3upl64LiytLW6BZqW9oaBPHb3URlRQmBmTfz8mZemkufpVVemKYuks4A7IoqTYqfrDqUnWmYZhJgo7eHMuvyquQJpTTXSuIJGKv3ecl5KpLhHAeDOfFEpLcQ4Qxgn2h6@SC@iEyn4gUaKtfVHvZ846l4fa5sTO3mUVJKiFoXuZxnXE0CKZHGCLU12R2WxApT7rpfHrWOfZlpOXmHVumMizGJEQlFikY0dlf5RIwQ2sCXQxIBSQoodMdHLhUhwvaxTYSnWN9kIgQrteUxwkLHsK0anrO8ZH6uCPG0WOVrPQartJXC8oVr80gINvhHYo/MVm46bdWbm0LbYH3rk2eIz5f@vmrM0zdddbwfdynvDXprIx21K19ZA1s6M9pkXxfG2eT2R4po/vn1gcCOeuu2cK5mScfZUhyJtabWPdaj3nfZwyv@/CW3wuUP "R – Try It Online") Let's consider a vector of zeros as the initial guess. Let's call V the distance between the current guess and the solution. For each position you only need to check the changes in V when you replace 0 with 5 and with 4. In fact, the differences between changing 0 with 5 are listed in my vector s1. The differences between changing 0 with 4 are listed in my vector s2. As you see these two vectors uniquely map the digits of the solution. The total number of tests is thus ~~3\*L~~ 2\*L + 1, where L is the length of the code: an initial check against all zeros, then two checks for each digit, one against 5 and one against 4. The improvement from a factor 3 to a factor 2 was inspired by Kamil Drakari's submission. The rest of the TIO submission is boilerplate for R. The TIO submission showcases the running time and the total number of operations for 1000 runs with L=1...200, 5 replicates for each value of L. ]
[Question] [ Since tomorrow is the 4th of May, here's a little Star Wars themed post to prepare you mentally to all the bad jokes coming tomorrow. **BACKSTORY** During a session of the galactic senate all the senators are sitting in an `n*n` grid. A sudden outbreak of JarJar flu (which lasts forever and causes the infected to speak like JarJar Binks) causes some of the senators to get infected. Here's an example with a `6*6` grid where the `X` are the infected senators, the corresponding list is : `[[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[0,5]]`: [![enter image description here](https://i.stack.imgur.com/siLh2.png)](https://i.stack.imgur.com/siLh2.png) After that the infection begins to spread step by step. Two senators are **adjacent** if they share a whole edge on the grid (i.e., top,bottom,right,left), which means we exclude diagonals. We can conclude a senator can be adjacent to 2,3 or 4 other senators and claim the following rules for the infection : * A senator that has been infected stays infected forever * A senator is infected at a step if he was adjacent to 2 or more infected senator at the previous step Here's an example with the previous grid which shows the 2 first steps of the infection : [![enter image description here](https://i.stack.imgur.com/98L7h.png)](https://i.stack.imgur.com/98L7h.png) After the nexts steps all the senate will be infected **YOUR TASK** Your code doesn't need to handle invalid inputs like a list greater than `n*n` or coordinates that aren't distincts. Your code will take as input a list of couples of integers (or a binary grid or any other format that suits your language) and an integer `n` (which can be unnecessary if you use another format than a list) , for instance : ``` 8 [[1,2],[1,1],[7,4],[2,7],[4,3]] ``` n being the side of the grid which means the grid will be a n\*n grid, and the list of couples of integers being the coordinates of the cells of the initally infected senators. The bottom left of the grid is [0,0] and the top right is [n-1,n-1]. The top left is [0,n-1]. Your code must output an integer : `-1` or a falsy value or an error if the whole grid will never be totally infected or the minimum number of steps required to infect the whole grid **Test cases** ``` 6 [[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]] => 7 4 [[1,1][0,3][1,0][3,0][3,3]] => 9 ``` Remember that this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), thus the shortest answer in bytes wins ! [Answer] # APL (Dyalog 16.0), 54 characters or 60 bytes Takes enclosed matrix as argument, returns the step number which completes infection, i.e. 1=is already fully infected. 0=does not fully spread, which is just 1 + the OP's numbers. 54 characters (Unicode): ``` (≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡ ``` 60 bytes (Classic): ``` (≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⎕U233A 3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡ ``` `⌺` is equivalent to `⎕U233A` Examples' run: ``` g←(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵ ⋄ (⊂f⊃⍵),⍵}⍣≡ ⎕IO←0 b←⊂⊖⍉~@(⎕JSON'[[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]]')⊢0⍴⍨2⍴6 g b 8 b←⊂⊖⍉~@(⎕JSON'[[1,1],[0,3],[1,0],[3,0],[3,3]]')⊢0⍴⍨2⍴4 g b 10 ``` The steps are as follows: ``` ┌─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┐ │ X X │ X X X │ X X X X │ X X X X X │ X X X X X │ X X X X X │ X X X X X │ X X X X X X │ │ X │ X X X │ X X X X │ X X X X X │ X X X X X │ X X X X X │ X X X X X X │ X X X X X X │ │ X X │ X X X │ X X X X │ X X X X │ X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ │ │ X │ X X X │ X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ │ X │ X X │ X X X │ X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ │ X X │ X X X X │ X X X X │ X X X X │ X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ └─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┘ ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ X X │ X X │ X X │ X X │ X X │ X X │ X X X │ X X X X │ X X X X │ X X X X │ │ │ │ │ │ X │ X X │ X X X │ X X X X │ X X X X │ X X X X │ │ X │ X │ X X │ X X X │ X X X │ X X X │ X X X │ X X X │ X X X X │ X X X X │ │ X X │ X X X │ X X X │ X X X │ X X X │ X X X │ X X X │ X X X │ X X X │ X X X X │ └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ ``` [Answer] # MATL, ~~29~~ 28 bytes ``` tn:"tlY6Z+1>Z|t?@.]]Nl=?l_]& ``` Input is in the form of a 2D matrix of 1's and 0's Try it at [**MATL Online**](https://matl.io/?code=tn%3A%22tlY6Z%2B1%3EZ%7Ct%3F%40.%5D%5DNl%3D%3Fl_%5D%26&inputs=%5B1+0+0+0+1+0%3B+0+1+0+0+0+0%3B+0+0+1+1+0+0%3B0+0+0+0+0+0%3B0+0+1+0+0+0%3B0+0+0+1+0+1%5D%0A&version=19.10.0) **Explanation** ``` % Implicitly grab user input as a 2D matrix t % Duplicate the inputs n: % Count the number of elements in the input (N) and create the array [1...N] " % Loop this many times (maximum number of steps we analyze) t % Duplicate the top element lY6 % Push the 2D array => [0 1 0; 1 0 1; 0 1 0] Z+ % Perform 2D convolution (and maintain the size) l> % Find all values that are >= 2 Z| % Perform an element-wise OR with the previous state t? % If all elements are 1's @. % Push the current index and break out of the loop ] % End of if ] % End of for loop Nl=? % If there is only one element on the stack l_ % Push a negative one ] % End of if statement & % Display the top stack element ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 49 bytes ``` J^UE2*lK.uS{+NeMf>hT1r8S@Jsmm+VdkNs_MB_MBU2Q)qJeK ``` [Test suite](http://pyth.herokuapp.com/?code=J%5EUE2%2alK.uS%7B%2BNeMf%3EhT1r8S%40Jsmm%2BVdkNs_MB_MBU2Q%29qJeK&test_suite=1&test_suite_input=%5B%5B1%2C2%5D%2C%5B1%2C1%5D%2C%5B7%2C4%5D%2C%5B2%2C7%5D%2C%5B4%2C3%5D%5D%0A8%0A%5B%5B0%2C5%5D%2C%5B1%2C4%5D%2C%5B2%2C3%5D%2C%5B2%2C1%5D%2C%5B3%2C3%5D%2C%5B3%2C0%5D%2C%5B4%2C5%5D%2C%5B5%2C0%5D%5D%0A6%0A%5B%5B1%2C1%5D%2C%5B0%2C3%5D%2C%5B1%2C0%5D%2C%5B3%2C0%5D%2C%5B3%2C3%5D%5D%0A4&debug=0&input_size=2). Uses 1-indexing for the output. [Answer] # Python, 231 bytes ``` g=input() q=lambda r,c:g[r][c]if(0<=r<m)*(0<=c<m)else 0 m=len(g);p=t=0;n=range(m) while not all([r for k in g for r in k]):h=[[g[r][c]or sum([q(r+1,c),q(r-1,c),q(r,c+1),q(r,c-1)])>1 for c in n] for r in n];t+=1;0/(g!=h);g=h print t ``` It raises an error if it isn't possible. [Try it online!](https://tio.run/nexus/python2#bY1BbsMgEEX3PsV0BzJRYRs6uQhiQQjBKHjiEKIc37VjO5XaSiP9p6evP2PERMOjMt7cMLv@eHJQhN9HU6zxNp2hfPXg6ATlgHJOv@XkQ74HkE2PORCLXA9YUWrC4igG1vPm2aUcgK4VXM7MFDhfC1wgEcQXlhkvlu87NGb9Oen7o2fmxkqrhOdigt0GwrdqhZ3ilh/Ua8fPO2R/Nsnq2qLS8pPFD@y4jtg1Q0lUoY6jMUqA3G5mK8xK71vUYtUv9X9L/m0tVln7DQ) [Answer] ## JavaScript (ES6), 132 bytes ``` f=s=>(w=s.search`\n`,t=` `.repeat(w+1),t+=s+t,t=s.replace(/0/g,(_,i)=>1-t[i]-t[i+=w]-t[i+=2]-t[i+w]>>>31),t==s?0/!/0/.test(s):1+f(t)) ``` Where `\n` represents the literal newline character. Takes input as a string of `0`s and `1`s in a newline-delimited array. Returns `NaN` if the grid will never become fully infected. ]
[Question] [ Given two [permutations](https://en.wikipedia.org/wiki/Permutation) in disjoint cycle form, output their product/composition in disjoint cycle form. [![Q · P = (1 5)(2 4) · (1 2 4 3) = (1 4 3 5).](https://i.stack.imgur.com/FtEK0.png)](https://i.stack.imgur.com/FtEK0.png) To find the composition, convert the disjoint cycles to permutations in two-line notation. Each number in a disjoint part of a cycle is mapped to the number following it in the same part. It wraps around. So `1 -> 5`, `5 -> 1`, `2 -> 4`, `4 -> 2`. If a number is not found, `3 -> 3`, it is mapped to itself. The first disjoint cycle could also be written `(1 5)(2 4)(3)`. These mappings are converted to two lines, like so (note that the order of **P** and **Q** are reversed): [![Wow, this image is massive!](https://i.stack.imgur.com/4ZSAj.png)](https://i.stack.imgur.com/4ZSAj.png) > > [T]he product of two permutations is obtained by rearranging the columns of the second (leftmost) permutation so that its first row is identical with the second row of the first (rightmost) permutation. The product can then be written as the first row of the first permutation over the second row of the modified second permutation. > > > [![enter image description here](https://i.stack.imgur.com/ByS1E.png)](https://i.stack.imgur.com/ByS1E.png) [Wikipedia article](https://en.wikipedia.org/wiki/Permutation_group#Composition_of_permutations.E2.80.93the_group_product) --- ### Rules: * Input will be given as a list of lists or similar format * You may **not** take something like `(1 5)(2 4)` as `[5, 4, 3, 2, 1]`, already in two-line form (mapping index to value) * Not all numbers have to occur in each group, so you could have `(1 5)·(1 2)`, resulting in `(2 5 1)`. * Your output should be able to be used as your input. * You do not need to support input with an empty cycle `(1 5)·()`. That would instead be given as `(1 5)·(1)` or something equivalent. * Since cycles wrap around, the order doesn't matter as long as the result is correct. * You can start at zero or one. It doesn't matter, because the results are the same. * The numbers can be larger than `9`. * You may not include the same number more than once in the output. So `[[1],[1]]` is not allowed. * Note that this operation is **not commutative**! I put Q before P, because that's what Wikipedia did. You can choose any order, but specify which if it's different. * Shortest code wins * Built-ins are allowed, but if you use one, show a solution without using it as well. ### Examples: Not all equivalent output possibilities are shown ``` Input Output [[1, 5], [2, 4]], [[1, 2, 4, 3]] [[1, 4, 3, 5]] (or [[4, 3, 5, 1]] or ...) [[1, 5]], [[1, 2]] [[2, 5, 1]] [[10, 2, 3]], [[2]] [[3, 10, 2]] [[1]], [[3]] [[]] (or [[1]] or something equivalent) [[10,2,3,15],[1,7],[5,6],[14,4,13,11,12]], [[5,6,7,9,14],[2,8,3,10],[1,11]] [[12, 14, 6, 1], [8, 15, 10, 3, 2], [13, 11, 7, 9, 4]] (arguments in reverse order from above gives a different answer) [[5,6,7,9,14],[2,8,3,10],[1,11]], [[10,2,3,15],[1,7],[5,6],[14,4,13,11,12]] [[9, 14, 4, 13, 1], [10, 8, 3, 15, 2], [7, 11, 12, 5]] ``` [Answer] # Mathematica, 15 bytes ``` ##⊙Cycles@{}& ``` Yes Virginia, there is a builtin.... Mathematica supports a permutation data type already in disjoint cycle notation: this pure function takes as input any number of arguments in the form `Cycles[{{1, 5}, {2, 4}}]` and outputs the product permutation, again in `Cycles[]` form. It uses the opposite ordering convention as the OP, so for example, ``` ##⊙Cycles@{}&[Cycles[{{1, 2, 4, 3}}], Cycles[{{1, 5}, {2, 4}}]] ``` returns `Cycles[{{1, 4, 3, 5}}]`. The `⊙` symbol I used above should really be the 3-byte private-use Unicode symbol U+F3DE to work in Mathematica. Note that Mathematica has a named builtin for this operation, `PermutationProduct`, but that's three bytes longer. [Answer] # [Haskell](https://www.haskell.org/), ~~157~~ 148 bytes EDIT: * -9 bytes: That could indeed be golfed more. Removed redundant parentheses around `p++q`. Swapped argument order of `g`. Got rid of `d` by starting `iterate` with `p x`, after which `takeWhile` no longer tied with `fst` + `span`. Made `iterate` infix. Doing this while I'm late... probably can golf some more. It was simpler, and seemed to be allowed, so the output includes single-element cycles. ``` q#p=g(p++q>>=id)$f q.f p f p a=last$a:[y|c<-p,(x,y)<-zip(0:c)(c++c),x==a] g(x:l)p|c<-x:fst(span(/=x)$p`iterate`p x)=c:g[x|x<-l,x`notElem`c]p g[]p=[] ``` [Try it online!](https://tio.run/nexus/haskell#RY5NboMwEIX3nMJSWNhiQjGQpkU4u57CsoTlAEUijvlTTZW7UztR0oWtmfe9NzMX2WnW6bkepZrDRfedrqf4Ig2evq8/8aLVMo4r3pF4rOWZxHe@DTvDWmyiaDidWHcmYYOGuEEmcA9J1stpDmXB15sq9wawhZWU@9/O4KRQBKsoUgQsY1IELbZFT4w32qKZZjwZqfEbsyQ0VefPmuvKIEuYKlpub7bc92ArfZ2/@vpSKWGClgvDuNg2zDkFdBCAeAooF77wim8AZUKQ4Gl5oaeY3G3ZA7zUR5v9m1LIgLoNLnt0/wHefZ1DDtQBCjR9RByAI3wCzR1P4cPHknuMUj/tDw "Haskell – TIO Nexus") **How it works:** * `#` is the main function. `q#p` takes two lists of lists of numbers, and returns a similar list. The tests seem to have Q before P so I used the same order. * `f p` converts the permutation `p` from disjoint cycle form to a function, after which `f q` and `f p` can be composed with the usual composition operator `.`. + The list comprehension iterates through the cycles `c`, searching for `a` and finding its successor. If the comprehension finds nothing, `a` is just returned. + `zip(0:c)(c++c)` is a list of pairs of elements of `c` and their successors. Since the question lets us "start at one" we can use `0` as a dummy value; it's cheaper to prepend that to `zip`'s first argument than to use `tail` on the second. * `g l p` takes a list `l` of elements, and a permutation function `p`, and returns the list of cycles touching the elements. + Here `c` is the cycle containing the first element `x` of the list, the other elements of `c` are found by iterating from `p x` until `x` is found again. When recursing to find the remaining cycles, all elements of `c` are first removed with a list comprehension. [Answer] # [J](http://jsoftware.com/), 7 bytes ``` C.@C.@, ``` [Try it online!](https://tio.run/##ZY3LCsJADEX38xUHFxahlEkfVqcPBD9FHMSNM3Ttt4@ZbrQISQjn3ps8k1@YHBbtdK0uWmU6mF1F4SdXUPJ2@MWYkG2j21czI0JNS2PiFwodQ8bmfnu8mFcY8MRNtuNIzxlpV/eJBrG6CiKbc1ZV1bpV63Xm5JBzLaKCBur/Vz8gKgjpAw "J – Try It Online") [Answer] # Python, 220 bytes ``` a,b=eval(input()) p,o=a+b,[] for i in range(1,1+max(map(max,p))): if not any(i in t for t in o): u,m=(i,),i while 1: for t in p[::-1]: if m in t:m=t[(t.index(m)+1)%len(t)] if m==i:o+=[u];break u+=(m,) o ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 187 bytes ``` q,p=eval(input()) g=lambda p,i:[*(c[c.index(i)-1]for c in p if i in c),i][0] h=lambda*c:(x:=g(p,g(q,c[0])))in c and(*c[(m:=c.index(min(c))):],*c[:m])or h(x,*c) exit({*map(h,sum(p|q,()))}) ``` [Try it online!](https://tio.run/##NY7NDoJADITvPEWPLanG38RswpOQPawLQhN3LYoGozw7LkZvM/P1Z/TZt5e4Peh1mjrWon64M0rUe49EWVOcXThWDpTFlDn60i8lVvWAQou1PV2u4EEiKMgJZFaeWGy5sln7W829wcEUDSo32LFPjIjmSXCxwtyXGEzxPxskok/cWE7EBEvpRYtDcpTVg/T4yoNTbPl2D6jvjlNNGmmaXrhm2BMDbhh2NDJ8k9kwbGn8AA "Python 3.8 (pre-release) – Try It Online") or [Check all test cases!](https://tio.run/##jVJNbxoxEL37V4zoxSYmzfIRYCV6S6@99LZaVRtjwCq7a2xv2Kjtb6czNqFfISpCMPab9@bNjO1z2LXNZGHd6R346klD2Gmwrt26qgbfdk5pUO1aM4RbOOKhakD3WnVBgwlQd/tg7B55ptaeUSqsYDAYnA7SrvRTteemsV3gQrDtal/Vj@sKrDR5MeSqULemWeueGzHKyk3rQIFpwILZgKFICWnK4q5kuzN1qHLe56stt3LLD1IhJoSgTKiaNR@qgtf56kW2Ng1XiOelRCSvS4EldrzHk2C6N4F/G9aV5Tvpu5rb7weJNsUPcUL/tz44Y7lgzOlq/yU2gZ3FfxyGM1uICgI2XaOCaRsILU7ONCHOsGr8UTvM90FXa2g3MZ2tdQo44iJnkBjxxNhxZ3CSn12nCcEixIwV3@veahU0CnWBHAAE90xZAB5t/fLIxcU5gfot8HcAL3SvtA3w8Onjg3OtS@qPmPQ1usH91FVIfqDyMAavg6fOQocvwGMS7hzrxa17UjzgCZM4DTkmSTgIAuy/gI0ANYMW@UHcDCQMbii2Ik0DR342@8fMfWft/jkOPVmkMaU9AbzsLT2fHPxl5B7lR6MPg7N410SF@NYhvnBOcULTWi87SLu9KMWkFIpTUWQSZqWEYixhWlJAN3SQMClLFo8UU1rJRn9/2Fnhwowc5M8kZNcId7HCJJESA/Xj9TVKyk2OrsuO5URm2A46mePvTN5TPJVTmSGQyWycdBCQc7mU2RTxsVwQ7S7Ssiw1jf6QB/fUBTIW@D9LFifkEq8ysowdzyUs4@xeNfV2pTi0/7ONWsvkCb@xdjSBhhbRE9mLvubJFnXw6sZ@Ag) **Input**: `q` and `p` in that order, each is a set of tuples, from `STDIN`. **Output**: The product permutation `Q·P` as a set of tuples, to `STDERR`. ### Explanation The function `g` finds which number maps to the number `i` in the permutation `p` (aka `g` is the inverse permutation of `p`). ``` g=lambda p,i: [ # creates a list *( # containing the following c[c.index(i)-1] # the number before i in cycle c for c in p # for all cycles in permutation if i in c # if i is in that cycle ) # ,i # adds i to the end of that list # (in case i is not in any cycle) ][0] # returns the first element of the list ``` The function `h` takes in a number, and returns the cycle in `Q·P` that contains that number. The returned cycle will be a tuple, formatted in a way such that the smallest element is at index 0. ``` h=lambda*c: # input: an incomplete cycle c, as a list (x:=g(p,g(q,c[0]))) # finds the number x before the first number in c in c # if x is also in c (aka the cycle is complete) and # then returns the following: ( # c as a tuple with min element at index 0 *c[(m:=c.index(min(c))):], # (c, from the min element to the end) *c[:m] # (c, from start to the min element) ) or # else (cycle is incomplete) returns the following h(x,*c) # recursive result when after prepending x to c ``` By applying `h` to all numbers, we can get all cycles in `Q·P`. To prevent duplicate cycles in our result, we simply put all cycles in a set. This works since similar cycles returned by `h` will be formatted to the same tuple (with the smallest element at index 0). We only needs to consider the numbers appearing in `P` or `Q`, as all other numbers will map to themselves. ``` exit( # returns through STDERR { # create a set from the followings *map(h, # map function h to sum(p|q,()) # all numbers in P or Q ) } ) ``` ]
[Question] [ **Introduction:** Like Twitter and Instagram and others, I wanted to display numbers like `1.2K` and `3.8 M` instead of `1,222` or `3,823,456`. But that's not all! As we all know, there might be some *human beings* which undoubtely won't like these abbreviations and will try to reverse them. So, `1.2k` will become `1,200` and `3.8 M` will become `3,800,000`. **The task:** * your task is to write a program or a function that converts a list of numbers (**which are given as strings**) into their abbreviate pairs and vice-versa. For example, if the input list (or any `STDIN`) was `['1.4k', '1,234,567', '7.99M']`, then you should output: ``` ['1,400', '1.2M', '7,990,000'] ``` *You can follow the next schema for abbreviations:* * 103 -> one kilo -> K * 106 -> one million -> M * 109 -> one billion -> B Your code may assume all lowercase, all uppercase, mixed case or undefined case for input and use any of these for output, but should be consistent. **Rules and restrictions:** * you may write a program or function, taking input via `STDIN` (or closest alternative), command-line argument or function argument and outputting the result via `STDOUT` (or closest alternative), function return value or function (out) parameter. * input may be in any convenient list or string format. You may assume that the `ai` are less than `231` each and that the list contains at least one element. * each abbreviated number will contain **only one** `.` while a normal number will contain **as many** `,` **as necessary** (you may assume that this numbers won't be altered). * you **MAY NOT** enter a number as `'123456'` but rather `123,456` * standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. **Test cases:** ``` Input: ['1.5M', '77.6k', '123,456,789'] Output: ['1,500,000', '77,600', '123.4M'] Input: ['3,000,000,000', '581k', '2b'] Output: ['3B', '581,000', '2,000,000,000'] Input: ['0.1k'] Output: ['100'] Input: ['888', '33'] Output: ['0.888k', '0.033k'] ``` **Clarifications:** * for numbers < 1000 after the decimal point in abbreviation output you should have as many digits as required to get the correct result. (e.g: `2` -> will become `0.002k`) - *that means 3 decimals at most*; for numbers > 1000 you can have *a maximum of 1 decimal*. * the abbreviation may be in both lower or upper case * **I removed the built-ins restriction as suggested in the comments** The shortest code in bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 67 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …KMBU3L3*°Vε',Ku¤©ai¨®XY‡*ïR3ô',ýRëY/ʒ1@N_~}ε4°z+N_·Ì.ò¨0Ü'.ÜXNè«}θ ``` What a mess.. :/ [Try it online.](https://tio.run/##yy9OTMpM/f//UcMyb1@nUGMfY61DG8LObVXX8S49tOTQysTMQysOrYuIfNSwUOvw@iDjw1vUdQ7vDTq8OlL/1CRDB7/4utpzW00ObajS9os/tP1wj97hTYdWGByeo653eE6E3@EVh1bXntvx/3@0kqGeqa@SjoKSubmeWTaIYWhkrGNiaqZjbmEJ4hrrGBgYwDBIwNTC0BtEGyWBSAM9Q7AuCwsLsGpjsBFAlbEA) **Explanation:** ``` …KMB # Push string "KMB" U # Pop and store it in variable `X` 3L # Push list [1,2,3] 3* # Multiply each by 3: [3,6,9] ° # Take 10 to the power each: [1000,1000000,1000000000] V # Pop and store it in variable `Y` ε # Map over the (implicit) input-list: ',K '# Remove all "," u # Convert it to uppercase ¤ # Get the last character (without popping) © # Store this in variable `®` (without popping) ai # If it's a letter: ¨ # Remove it from the string ® # Push the letter from variable `®` XY‡ # Transliterate it to the correct value in `Y` based on `X` * # Multiply the two numbers together ï # Cast it to an integer R # Reverse it 3ô # Split it into parts of size 3 ',ý '# Join it with "," delimiter R # Reverse it back ë # Else: Y/ # Divide it by each value in list `Y` ʒ # Filter this triplet by: 1@ # Check if it's >= 1 ~ # OR N_ # The 0-based filter-index is 0 # (so we'll still have a result left if <1000) }ε # After the filter: map over the remaining values: 4°z+ # Add 0.0001 to the number: 4° # Push 10 to the power 4 z # Divide 1 by this + # Add this 1/10000 to the number N # Push the 0-based map-index _ # Check if it's 0 (1 if 0; 0 otherwise) · # Double it (2 if 0; 0 otherwise) Ì # Increase by 2 (4 if 0; 2 otherwise) .ò # Round to that many decimals ¨ # Remove the last digit 0Ü # First trim potential trailing "0" '.Ü '# And then also trim a potential trailing "." XNè« # Append the `N`'th letter of string `X` }θ # After the inner map: pop and leave the last item # (after which the mapped list is output implicitly as result) ``` [Answer] # PHP, ~~234~~ ~~224~~ ~~213~~ ~~201~~ 205 bytes ``` for(;$x=$argv[++$n];){$y=str_replace(",","",$x)/1e3;for($i=0;$y>999;$i++)$y=($y|0)/1e3;echo(A<$c=substr($x,strlen($x)-1))?number_format($x*[k=>1e3,m=>1e6,b=>1e9][$c]):($i?($y*10|0)/10:$y).kmb[$i]," ";} ``` 6 bytes saved by insertusernamehere, 4 bytes inspired by that. --- * takes input from command line arguments, prints results space-separated with a trailing separator * expects lower case abbreviation * run with `-r` -2 bytes if underscore as separator is ok: Replace `" "` with `_`. -1 byte if correct rounding is ok: Replace `($y*10|0)/10` with `round($y,1)`. -17 bytes for PHP 7.1: Replace `substr($x,strlen($x)-1)` with `$x[-1]`. --- 80 (63) bytes for expanding one argument only: ``` <?=number_format(($x=$argv[1])*[K=>1e3,M=>1e6,B=>1e9][substr($x,strlen($x)-1)]); ``` save to file, then execute (or replace `<?=` with `echo` +space and run with `-r`. [Answer] # JavaScript, ~~545~~ ~~524~~ ~~522~~ ~~518~~ ~~514~~ ~~508~~ ~~504~~ ~~498~~ ~~494~~ 214 bytes Thanks to @ETHproductions for saving 180 bytes! ``` d=F=>F.map(f=>1/f.slice(-1)?f=(f=f.replace(/,/g,""))[9]?(f/1e8|0)/10+"B":f[6]?(f/1e5|0)/10+"M":f/1e3+"k":R(R(f.slice(0,-1)+"e"+' kMB'.indexOf(f.substr(-1))*3-0+"").match(/.{1,3}/g)+""),R=x=>[...x].reverse().join``) ``` To call the function: ``` d(["1.5M","1,500,000"]) //["1,500,500","1.5M"] ``` Outputs as `alert`, where each `alert` contains a different element of the input Readable version: ``` d = F => F.map(f => 1 / f.slice(-1) ? f = (f = f.replace(/,/g, ""))[9] ? (f / 1e8 | 0) / 10 + "B" : f[6] ? (f / 1e5 | 0) / 10 + "M" : f / 1e3 + "k" : R(R(f.slice(0, -1) + "e" + ' kMB'.indexOf(f.substr(-1)) * 3 - 0 + "").match(/.{1,3}/g) + ""), R = x => [...x].reverse().join ``) ``` **Summary of edits:** converted function to an arrow function * removed semi-colons ';' * removed `var` * converted to an arrow function * used map to iterate through the individual elements of the array * used `|0` instead of floor * used regex for testing * used ternary operators instead of if-else statements * included a separate function for `.reverse().join''` [Answer] # [Python](https://www.python.org), ~~322 321~~ 318 bytes ``` import math def f(l,r=[]): for s in l: if(c:=s[-1])in(p:=' kMB'):r+=[f'{int(float(s[:-1])*10**(p.index(c)*3)):,}'] elif(i:=int(s.replace(',','')))>999: if(l:=math.log10(i))<4.5:r+=[f'{round(i/1e3,1)}k'] elif l<7.5:r+=[f'{round(i/1e6,1)}M'] else:r+=[f'{round(i/1e9,1)}B'] else:r+=[f'{i/1e3}k'] return r ``` -3 thanks to jezza\_99 [Attempt This Online!](https://ato.pxeger.com/run?1=bZExbsMgFIbVNadgg-cSGuLYiVGcIVuHnMDyYCXQIBNsYSK1qnKSLlnaO7WnqXGaVlUrhseTPr7_AS9v7ZPfN_Z8fj16NV583Kz0oW2cR4fK70c7qZAihrq8KEGMkGoc6pC2yPQN0opsRd4VY16CtqQVOUb1Zo1BuNu8UPhZW0-UaSpPukIEKuKTKCIt03YnH8kWohhA0BMue5s0vU-LPBzqmJOtqbaSYNovDACrLMtCaEg1Ig_jMdM88AnRAMsZS66hrjnaHdF3XMaUw6ke5IMdmeX8Py4N3ObKdfIvkQVi_TXmDzCEXBKc9Ednkbs84_t964bLkwJzNl1jinDMZptQE5bWoXI6jWffG5qk818NXWQTXAJchNf_-QQ) [Answer] # [Python](https://www.python.org), ~~207~~ 203 bytes ``` lambda L:[s[-1]in'kMB'and f'{int(float(s[:-1])*10**(" kMB".index(s[-1])*3)):,}'or((i:=int(s.replace(',','')))>999>(j:=(i>1e6)+(i>1e9))and f'{(i/10**(j*3+2)+.5)//1/10}{"kMB"[j]}'or f'{i/1e3}k')for s in L] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9LboMwEIb3OQViMx7iGBuXp5Qssk5OQFmQBlSHFFCgUqsoJ-kmUtUepZueoLepDUSVKsua1z_zzbx9tq_9Y1Nf38vl_cdzXy6in-9j_rTb59YmSbt0ITJVQ7VdQ17vrRLOqu5JeWzynnRpoqvoCO44xLa0xmaq3hcvZGhDRyIm9ALNiRCVLE1jx05Fe8wfCgJUP0DEVRzHK3JIlkStRBHgfLAx4sQjyh0AB0fOPZwzH11X6NTlbBtiesgMYdjMFYW8VICljjtL1dYmm076ak_D3iQFwfwtUAvCkAWVcYQn6Z0f0DCK9UqScs5v35T9SAwyb62rnJkAoigyKSkhQ5zNxuG2nk39v8YwpMHoacIElYyvp6E3mfcfKEbDmaZUo8elrCCzcbzmeh3tLw) Similar to @TheThonnu's [answer](https://codegolf.stackexchange.com/a/253716/110555) , but in a single line lambda and with sufficient differences that I feel it deserves a seperate answer -4 bytes thanks to @97.100.97.109 ]
[Question] [ A [right-truncatable prime](https://oeis.org/A024770) is a prime where every prefix is a prime (in base 10). A [left-truncatable prime](https://oeis.org/A024785) is exactly the opposite, where every postfix is a prime (primes that start with 0 aren't allowed). Both of these sequences are finite (There are only 83 Right-truncatables, while there are 4260 Left-truncatables). You need to write a program that accepts a single number as input, and produces the *n*th right-truncatable prime. However, when the program is read **arranged backwards**, it should produce the *n*th left-truncatable prime. To arrange a program backwards, we split the program into words, then reverse the order of the words. A word can consist of any number of characters. For example, if the following was your program: ``` hello world 1234567890 ``` The following would all be allowed as possible backwards arrangements: Splitting on each character: ``` 0987654321 dlrow olleh ``` Splitting on whitespace: ``` 1234567890 world hello ``` Splitting arbitrarily (pipes added for clarity): ``` hel|lo w|orld 1|23456|7|8|90 908723456orld 1lo whel ``` When arranging your program backwards, all whitespace must be considered and reversed, just like any other character. ## Forward test inputs: ``` 1: 2 2: 3 21: 379 60: 239933 83: 73939133 ``` ## Backward test inputs: ``` 1: 2 2: 3 39: 647 187: 29173 4260: 357686312646216567629137 ``` Programs should be able to run in a reasonable amount of time (less than a minute) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the fewest bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ## Forward ``` Ѷp9¶7ÆR2ĿV€$ÆPÐf$ÐĿFị@ ``` [Try it online!](http://jelly.tryitonline.net/#code=w5HCtnA5wrY3w4ZSMsS_VuKCrCTDhlDDkGYkw5DEv0bhu4tA&input=&args=ODM) ### Words `Ñ` `¶` `p` `9` `¶` `7ÆR2ĿV€$ÆPÐf$ÐĿFị@` ## Backward ``` 7ÆR2ĿV€$ÆPÐf$ÐĿFị@¶9p¶Ñ ``` [Try it online!](http://jelly.tryitonline.net/#code=N8OGUjLEv1bigqwkw4ZQw5BmJMOQxL9G4buLQMK2OXDCtsOR&input=&args=NDI2MA) ### Words `7ÆR2ĿV€$ÆPÐf$ÐĿFị@` `¶` `9` `p` `¶` `Ñ` ## How it works All Jelly programs consist of links (Jelly's take on functions), which are separated by linefeeds or pilcrows (`¶`). The last of them is the *main link*; it is called automatically when the program is run. The forward program works as follows. ``` Ñ Helper link. Unused. p9 Helper link. Take the Cartesian product with [1, ..., 9]. 7ÆR2ĿV€$ÆPÐf$ÐĿFị@ Main link. Argument: n 7ÆR Yield all primes up to 7. ÐĿ $ÐĿ Combine the two quicklinks to the left into a monadic chain, and call it repeatedly until the results are no longer unique. Return the array of all intermediate results. $ Combine the two links to the left into a monadic chain. 2Ŀ Call the helper link on line 2. Ṿ€ Eval each array in the product. This casts to string before evaluating, thus concatenating both numbers. ÆPÐf Filter by primality; keep only primes. F Flatten the resulting array. ị@ Retrieve the element at index n. ``` The backward program does almost exactly the same; there are only two differences. * The main link is now `Ñ`, which simply calls the link below it (wrapping around), i.e., the main link of the forward program. * `9p` instead of `p9` return the reversed Cartesian product. [Answer] # Python 2, ~~143~~ 139 bytes ``` I=1 a={2} def f(s): for d in'123456789':u=d[I:]+s+d*I;z=int(u);z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u) f('') lambda n:sorted(a)[~-n] I=0 ``` Consists of five parts: 1. `I=1` 2. A newline 3. `a={2}…[~-n]` 4. A newline 5. `I=0` So reversal is just flipping the value of `I`. ## Explanation The function `f` performs a recursive search for either left-truncatable primes (LTPs) or right-truncatable primes (RTPs), depending on the value of the global `I`. These values get added to the set `a`. Then, `lambda n:sorted(a)[~-n]` returns the `n`-th one. Let’s define a **leaf** as either an LTP, an RTP, some non-zero digit + an LTP, or an RTP + some non-zero digit. These are all the values that `f` could ever want to check for primality. I designed a Fermat pseudoprime test that works for all leaves: > >       ![](https://i.stack.imgur.com/YCliI.gif) > > > (63973 is a [Carmichael number](https://en.wikipedia.org/wiki/Carmichael_number).) If this test returns true, then `z` should be added to the set `a` and we should recurse on `str(z)`. The responsible bit of code is: > > > ``` > z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u) > > ``` > > First, we wish to deal with the case `z == 2`. We do so by simply dodging it here and hard-coding `2` when we initially define `a`! (EDIT: And nothing harmful happens if we also catch `z == 1`.) So we can assume that `z ≥ 3` now. I’ve translated some “and”s into a short-circuiting chained comparison: the first three comparisons have to succeed before `a.add(z)` and `f(u)` are ever evaluated. Here are all their roles: > > 1. `z%91>0` encodes our first condition. (63973 is divisible by 91, which is not a leaf itself, so that’s how we recognize it.) > 2. `0<2` is always true, but chaining is shorter than `and`. > 3. `2==pow(2,z,z)` encodes our second condition. > 4. `pow(2,z,z)>a.add(z)` triggers the addition, and is always true, since `set.add` returns `None`, and integers are always greater than `None`. > 5. `a.add(z)<f(u)` triggers the recursion. Its truth value is unimportant. > > > ## Acknowledgements * Dennis saved four bytes (`u=[d+s,s+d][I]` → `u=d[I:]+s+d*I`; `z==2` → `z<3` and the **mod 91** trick). Thanks! ]
[Question] [ **GolfScript** automatically coerces values, according to the following ‘priority’ sequence: > > integer → array → string → block > > > (listed from lowest to highest.) This means that `"1"7+` leaves the string `"17"` on the stack (and not `8`), because strings have a higher priority than integers. [*To those GolfScript veterans – apologies for insulting your respective intelligences.*] How would it be possible to do this the other way? That is, to **coerce a string into an integer**? [Answer] There's an operator `~` in golfscript, which does the following: `bitwise not, dump, eval`. Therefore, `"1"` will give the string `"1"` while `"1"~` will evaluate that string (into the integer `1`). Then, all you need to do is `"1"~7+`. [Try it online!](http://golfscript.tryitonline.net/#code=IjEifjcr&input=) ]
[Question] [ This is a follow-up question to my [Puzzling.SE question](https://puzzling.stackexchange.com/questions/28363/half-reverse-operation-on-binary-strings): I asked if there’s a function **f** mapping Boolean strings to Boolean strings, so that **f(f(b)) = reverse(b)** for all input strings **b**. (By **reverse**, I mean the function that reverses the order of bits.) The above link contains a positive answer, with proof, by the great *f''*, but you might want to ponder the question for yourself before looking. Implement such a function **f** in as few bytes as possible. * You may either read input from STDIN, or take a function argument; and either write the result string to STDOUT, or return it. * Either way, you may work with actual strings of two distinct bytes or characters of your choice (say `0` and `1`, or `\x00` and `\x01`), or with arrays/lists of [truthy and falsy values](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey). Pick two values and stick with those, though. * The result of a single application of **f** *must* be a binary string itself: no silly answers like `b -> if b starts with 'x' then reverse(b[1:]) else 'x' + b`... * Your function should be *total*; in particular, the input may be the empty string, or one bit long, etc. There’s no upper bound for the string’s length. * It should also be *pure*: don’t keep any global state between function calls; the input string must completely determine the output string. [Answer] # Python 2, 64 ~~69~~ bytes ``` def f(s):p=(s+s).find(s,1);return[s[~p::-1],s+s[:p]][len(s)/p%2] ``` Ungolfed: ``` def f(s): p = (s+s).find(s,1) n = len(s)/p return s[:p][::1|n%-2] * -~(n-1^1) ``` This finds the string's period, i.e. the minimal `p` such that `s` is a string of length `p` repeated `n` times (I found a [golfy method](https://stackoverflow.com/a/29489919) on SO). Then if `n` is odd, it adds one more repetition of the period. If `n` is even, it removes one repeat of the period and reverses it. ~~Thanks to @Sp3000 for helping to implement the function mapping between 1<->2, 3<->4, etc.~~ [Answer] # Perl, ~~49~~ 47 bytes Includes +2 for `-lp` Based on @feersum's very nice algorithm Run with input on STDIN, e.g. ``` perl -lp halfreverse.pl <<< "101001" ``` `halfreverse.pl`: ``` /^(.+?)((\1\1?)*)$/;$_=$3eq$1?reverse$2:$_.$1 ``` ## Explanation ``` /^ $/ Match the complete input string (.+?) Non-greedy match. Try only one digit at the start, if that doesn't work try 2, then 3 etc. The string being tried is remembered in backreference \1 ((\1\1?)*) Try to repeat \1 as many times as possible but prefer in groups of 2. Fall back to only 1 at the end of the string if the trailing part has an odd number of \1 (so the total count is even) $3eq$1 So the last match $3 equals the first match $1 ? if and only if the total count is even reverse$2 If total count is even drop the first instance of : \1 and reverse $_.$1 If total count is odd extend $_ by one instance $_= Assign result ``` [Answer] # CJam, 32 bytes ``` 1q1]s:~__W%.&_,2/0t0#2%{2>W%2>}| ``` [Try it online.](http://cjam.aditsu.net/#code=1q1%5Ds%3A%7E__W%25.%26_%2C2%2F0t0%232%25%7B2%3EW%252%3E%7D%7C) Too long... ]
[Question] [ The other day my chemistry teacher was explaining to us about [scientific notation](https://en.wikipedia.org/wiki/Scientific_notation) (using a small number and multiplying it by powers of ten to express large numbers more easily), which brought me back a few years to when I first learnt it. After learning the basics, we had done a bunch of typical maths questions, some of which were like the following: > > Represent the following in scientific notation: > > a) 50000000 > > b) 120000000000000 > > c) 90000000000000000000000000000000000000 > > d) pi^e^i^j^k^std::vector > > ... > > z) **200** > > ... > > > And I thought, "What? We were told that scientific notation was used to make writing large numbers more efficient, but some cases aren't more efficient at all!" Consider the number ``` 300 ``` and its representation in scientific notation: ``` 3x10^2 ``` What, the scientifically notated version actually takes up more space? We can't have that now can we? (Screen space is precious.) We could determine ourselves if it's more space efficient to write a number in scientific notation or not, or... # Task Your program or function should take as input a single positive number `n` of arbitrary size (up to what your language supports) and output the scientifically notated version of the number. However, if the original number `n`, after removal of trailing zeroes and trailing decimal place, takes less or the same amount of characters to display than its scientifically notated version, you must output that original number `n` instead. Your code needs to be as short as possible because the output also has to be as short as possible. # Specifications Efficient Scientific Notation is defined as follows: ``` bx10^e ``` `b` is the input number appropriately divided by powers of 10 such that `1 <= b < 10`. This number must have all trailing zeroes (and decimal point if required) removed, but must have the precision of the original number (up to the decimal point limit in your language, of course). Ie `90000` becomes `9`, `13.500` becomes `1.35`, `0.000675` becomes `6.75` etc. If this number ends up containing more decimal places than your language can handle, it should be rounded to that maximum number of decimal places. `e` is the exponent to which ten is raised such that `n = b x 10^e` (remember that this number needs to be negative if `n` is smaller than 1). This number should not have any trailing zeros or a decimal place (mainly because if it's not an integer something is wrong...). The characters `x10^` *must* remain as is in the string between `b` and `e`. # Test cases ``` Input -> output 1 -> 1 20 -> 20 3000000 -> 3x10^6 400000 -> 400000 0.008093 -> 0.008093 0.007835000000000 -> 0.007835 0.000003000000 -> 3x10^-6 0.00000065 -> 6.5x10^-7 0 -> 0 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. # Other rules and clarification * Trailing zeros (and/or trailing decimal place) are not counted towards the character count of the original input number `n`. Keep that in mind for cases such as test case 6 * You may assume that if the input number is less than 1, it will always start with a 0 in place for the ones digit (as in test cases 5-8). * Input number will never be negative * Built-ins that make this challenge trivial and standard loopholes are disallowed * A trailing newline in the output is OK **EDIT** Thanks to user81655 for pointing out test cases 7 and 8 had incorrect powers of ten. I have now fixed those so make sure your code evaluates them correctly. [Answer] ## ES6, ~~83~~ 81 bytes ``` x=>(e=s=>s.replace(/e\+?/,'x10^'),z=e(x.toExponential()),y=e(''+x))[z.length]?z:y ``` Probably fails for some edge cases where `toString` insists on exponential format. Edit: Saved 2 bytes thanks to @user81655. [Answer] # Python 3, 346 342 319 302 bytes ``` L=len;N=str(float(input())) if N.endswith('.0'):N=N[:-2] if'e'in N:C,P=N.split('e');N=N.replace('e','x10^') else: C=N.strip('.0').replace('.','');F=N.find('.') if L(C)>1:C=C[0]+'.'+C[1:] P=((L(N) if F==-1 else F)-1-N.lstrip('0').find(C[0])) print(min([N,'{0}x10^{1}'.format(C,int(P))],key=L)) ``` Probably horribly golfed, but hey, this is my first try at something like this. It's hard to read, so it must be good. As far as I'm aware, it should work on every case, even with Python's tendency to automatically convert numbers past whatever threshold into scientific notation (except with that cool and fancy 'e'). I don't remember exactly how I made that be able to return standard form numbers, but it does that. [Answer] # Perl 6, ~~96~~ 90 bytes I feel like this could be shorter, but this is my best for now ``` {my \s=($_,*×(1>$_??10!!.1)…10>*>=1);min(s[*-1]~"x10^"~(1>$_??1-s!!s-1),$_,by=>&chars)} ``` **usage**: Assign this to a variable Here it is ungolfed a bit with some bad commentary: ``` my &f = -> $n { my $a = 1 > $n ?? 10 !! .1; # If $n < 1, we will multiply by 10 # in the sequence below, else by 0.1 my @seq = ($n, * × $a ... 10 > * >= 1); # Sequence starting at $n, # multiply the previous value by $a # until we reach a number 1 <= x < 10 # Join the last element in @seq, "x10^", and the length of @seq, # with an extra subtraction for numbers less than 1. # this gets us our scientific notation. my $science = @seq[*-1] ~ "x10^" ~ @seq - (1 > $n ?? @seq*2 !! 1); min($science, $n, by => &chars) # Uses the &chars function to # choose a min value and return it. } ``` [Answer] ## TI BASIC (nspire): 112 bytes ``` Define f(x)= Prgm string(x)➝a If x≥1 Then format(x,"s")➝a EndIf instring(a,"ᴇ")➝b left(a,b-1)&"x10^"&mid(a,b+1)➝a If dim(a)<dim(string(n)) or x<1 Then Disp a Else Disp x Endif EndPrgm ``` **Explanation** ``` If x≥1 Then format(x,"s")➝a EndIf ``` Converts the input to scientific notation with the format function if it already isn't in that format- as small decimals are automatically converted. ``` instring(a,"ᴇ")➝b left(a,b-1)&"x10^"&mid(a,b+1)➝a ``` Finds the position of the fancy E that denotates exponents and replaces it with "x10^". ``` If dim(a)<dim(string(x)) or x<1 Then Disp a Else Disp x Endif ``` Checks which output is larger and returns the optimal one. Unless it is a small decimal, which are smaller by default. [Answer] ## Python (3.5) 177 bytes A solution using regular expression ``` import re g=lambda s:re.sub(r"e\+?(-?)0?","x10^\\1",s) def f(i): t=g(re.sub(r"\.[0]*e","e","%e"%i)) u=g(re.sub(r"(\..*)[0]*$","\\1",str(i))) return t if len(u)>len(t) else u ``` ## Explanation Importation of regexp module ``` import re ``` Définition of the lambda function to replace `e` by `x10^` ``` g=lambda s:re.sub("e\+?(-?)0?","x10^\\1",s) def f(i): ``` Convertion of the string in scientific notation ``` t=g(re.sub(r"\.[0]*e","e","%e"%i)) ``` Remove 0 padding in the orginal string ``` u=g(re.sub(r"(\..*)[0]*$","\\1",str(i))) ``` compare length ``` return t if len(u)>len(t) else u ``` ## Results ``` >>> [f(i) for i in [1, 20, 3000000, 400000, 0.008093, 0.007835000000000, 0.000003000000, 0.00000065, 0]] ['1', '20', '3x10^6', '400000', '0.008093', '0.007835', '3x10^-6', '6.5x10^-7', '0'] ``` ]
[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 7 years ago. [Improve this question](/posts/57572/edit) # The Situation Suppose I allow "Shady Sam" admin access on my workstation to perform an important administrative task on my Mac Pro for me by giving them a temporary root login password. (Assume they *were* trustworthy, perhaps a systems admin for my company.) From a remote location (e.g. home), I use my MacBook Pro laptop to observe Sam's activities and learn how to do the task myself via Remote Desktop (VNC). Without warning, Shady Sam does something dastardly! Perhaps I see him trying to delete data from my hard drive or prying into restricted folders, etc. Whatever the dastardly deed, I want to lock Shady Sam out immediately, and secure the computer as best as possible from my remote location. Since we share the mouse and keyboard, I couldn't reliably perform an action from within Remote Desktop (besides, they could close the connection). I'd have to write a script and run it remotely. # The Challenge **What's the best script (e.g. `panicScript.sh` or `panicScript.py`) I could run remotely to stop Shady Sam from performing his dastardly deed *and* prevent him from attempting it again?** I envision myself running it in the following way: ``` scp panicScript.sh remoteMachine:~/panicScript.sh ssh remoteMachine . ~/panicScript.sh ``` ### Possible Features: Other ideas are expressly encouraged! * Change passwords of any/all accounts on remoteMachine * Disable the keyboard or mouse * Disable the monitor * Reboot the machine ## Assumptions Shady Sam will not damage the Mac Pro in any way or remove any of its components (e.g. physically remove a hard drive or wired network connection), but he *will* attempt to re-login and continue his dastardly deed as quickly as possible. Sam has (otherwise) unrestricted physical access to the computer and a root login password. Assume the Mac Pro has a monitor, keyboard, mouse, external hard drive, and an ethernet connection for internet. Let's suppose it can print to a network printer in a common area. For fun, let's suppose I have a standard user account on several coworker's workstations, which are identical to mine (so I can connect to their machines via `ssh`). Assume there are a dozen open-air cubicles clustered together so that coworkers can stand up and talk to each other. My coworkers, however, will generally *not* suspect that Shady Sam is doing something dastardly if they see him at my computer because he has helped several of them in the past and didn't do dastardly things to their computers. ## Constraints The panic script is initially on my laptop at home. You can `scp` it to my machine and run it there, or run it directly from my laptop at home. **(Specify in your response!)** All actions taken by the script must be non-damaging and/or reversible from my remote location so that I can regain access at a later point from my remote location, and must be standard features/commands on a Mac Pro. **The script may call other scripts/programs as long as they come standard with the machine.** Command-line scripting tools (e.g. `awk`) are okay as long as their commands is contained in the main script (e.g. `history | awk '{print $2}'`). This admittedly limits the scripting languages that could be used. Calling a custom script or program you wrote (e.g. `. ~/myOtherScriptOfKungFoo.sh`) isn't okay, unless you generate it from within your script and the generated script is under 32 characters: ``` echo -e "#"'!'"/bin/bash\necho \"Hello, World\"" >> test.sh chmod +x test.sh . test.sh ``` I shouldn't have to interact with the script more than once (e.g. to type a password). # Criteria The script should be short (cap of 30 lines), yet readable. Primary criteria is thoroughness, creative features and style, which is better than simplicity. Ultimately, the most votes wins! [Answer] The panic script should be sent to remote machine (Mac Pro) using scp, and then run (no sudo or any input required): Here is the script: (this assumes that you are John Smith) ``` #!/bin/bash -m f() { while true do pmset displaysleepnow sleep 0.1 done } f& while true do osascript -e "set Volume 10" say -v Ralph "Stop Shady Sam now. He is trying to do something he is not allowed to." for n in {1..10}; do afplay /System/Library/PrivateFrameworks/ScreenReader.framework/Versions/A/Resources/Sounds/Hit.aiff sleep 0.05 done sleep 0.1 say -v Ralph "This is John Smith speaking." done ``` For maximum effiency, you should run this on every single machine in room to ensure that everybody will notice the problem and stop him. ]
[Question] [ # Introduction In this challenge, your task is to find generalized subsequences of strings. The subsequences are not necessarily contiguous, and they can also "wrap around" the string, going past its end and starting again from the beginning. You'll want to minimize the number of wraps, though. More formally, let `u` and `v` be any two strings, and `k ≥ 0` an integer. We say that `u` is a *`k`-wrapping subsequence* of `v`, if there are distinct indices `i1, i2, ..., ilen(u)` such that `u == v[i1] v[i2] ... v[ilen(u)]`, and at most `k` of the indices `ij` satisfy `ij > ij+1`. This means that `u` can be found inside `v` by going from left to right, choosing some of its characters on the way, and wrapping around at most `k` times (equivalently, doing at most `k+1` sweeps across `v`). Note that no character can be chosen more than once, even after a wrap-around, and that `0`-wrapping subsequences are exactly the ordinary subsequences that we are all familiar with. # The Task Your inputs are two non-empty alphanumeric strings `u` and `v`, and your output is the smallest integer `k` such that `u` is a `k`-wrapping subsequence of `v`. If no such `k` exists, the output shall be `-1`. # Example Consider the inputs `u := xyzyxzzxyx` and `v := yxzzazzyxxxyz`. If we start looking for the characters of `u` in `v` in a greedy fashion, we will wrap around 3 times: ``` yxzzazzyxxxyz >─x─────y────z┐ ┌─────────────┘ └y───────x────┐ ┌─────────────┘ └──zz─────x─y─┐ ┌─────────────┘ └──────────x──> ``` Thus the correct output is at most 3. Note how the left-most character `x` is selected once, and then ignored on the second sweep, since it cannot be re-used. However, there exists a shorter method with only 2 wrap-arounds: ``` yxzzazzyxxxyz >──────────xyz┐ ┌─────────────┘ └yxzz────x────┐ ┌─────────────┘ └───────y─x───> ``` It turns out that one wrap-around (that is, two sweeps) is not enough, so the correct output is `2`. # Rules and Bonuses You can write either a function or a full program, and you can also change the order of the inputs if needed. The lowest byte count wins, and standard loopholes are disallowed. There is a **bonus of -10%** for computing all of the test cases in under 10 seconds total. I will test unclear cases on my machine; my reference implementation in Python takes about 0.6 seconds. I have a 7-year old laptop with 1.86 GHz dual core CPU, which you may want to take into account. # Test Cases ``` "me" "moe" -> 0 "meet" "metro" -> -1 "ababa" "abaab" -> 1 "abaab" "baabaa" -> 1 "1c1C1C2B" "1111CCCcB2" -> 3 "reverse" "reserved" -> 2 "abcdefg" "gfedcba" -> 6 "xyzyxzzxyx" "yxzzazzyxxxyz" -> 2 "aasdffdaasdf" "asdfddasdfsdaafsds" -> 2 ``` [Answer] # Pyth, 34 bytes ``` Mh+Smssm>.ukC,[[email protected]](/cdn-cgi/l/email-protection)_1 ``` This defines a function `g`, which takes two strings as parameter. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=Mh%2BSmssm%3E.ukC%2CdtdfqGsm%40HkT.PUHlG_1%0Ag%22me%22%22moe%22%0Ag%22meet%22%22metro%22%0Ag%22ababa%22%22abaab%22%0Ag%22abaab%22%22baabaa%22%0Ag%22reverse%22%22reserved%22%0Ag%22abcdefg%22%22gfedcba%22&debug=0) This code is very inefficient. It has a time and memory complexity of `len(v)!/(len(v)-len(u))!`. It is not able to solve the longer test cases in under 10 seconds. (It also will crash very likely, since it will run out of memory.) ``` M define g(G, H): return _ .PUHlG all permutations of [0, 1, ..., len(H)-1] of length len(G) fqGsm@HkT filter the permutations which form the string G mssm>.ukC,dtd compute the number of wraps for each of the remaining permutations +S _1 sort the numbers and append -1 h return the first element ``` [Answer] # Haskell, 160 \* 0.9 = 144 bytes ``` a#(-1)=a a#b=min a b f y=w(y++" ")0$length y w _ n _[]=n w(c:d)n o g@(a:b)|n>o=(-1)|a==c=z#w y n z g|c==' '=w y(n+1)o g|1<2=w y n o g where z=w d n o b;y=d++[c] ``` Timing for all test cases (note: arguments are flipped): ``` *Main> map (uncurry f) [ ("moe", "me"), ("metro", "meet"), ("abaab", "ababa"), ("baabaa", "abaab"), ("1111CCCcB2", "1c1C1C2B"), ("reserved", "reverse"), ("gfedcba", "abcdefg"), ("yxzzazzyxxxyz", "xyzyxzzxyx"), ("asdfddasdfsdaafsds", "aasdffdaasdf")] [0,-1,1,1,3,2,6,2,2] (0.08 secs, 25794240 bytes) ``` How it works (short version): simple brute force that takes the minimum of using a matching character and skipping it. I stop the search when either finished (returning the number of cycles) or when cycled more than the minimum so far (returning -1). Saved a lot of bytes compared to my first version, mainly because I switched from a full program to a function. With some comments and proper spacing golfed Haskell is quite readable: ``` -- a minimum function that ignores a -1 in the right argument to prevent -- "not solvable" cases in parts of the recursive search to dominate low numbers -- of solvable parts. If the case isn't solvabale at all, both arguments are -- -1 and are carried on. a # (-1) = a a # b = min a b -- the main function f calls the worker funktion w with arguments -- * the string to search in (STSI), appended by a space to detect cycles -- * the number of cycles so far -- * the minimum of cycles needed so far, starting with the length of STSI -- * the string to search for (STSF) (partial applied away and therefore invisible) f y = w (y++" ") 0 (length y) -- the worker function w _ n _ [] = n -- base case: if STSF is empty the work is done and the -- number of cycles is returned w (c:d) n o g@(a:b) -- "c" is first char of STSI, "d" the rest -- "n" number of cycles, "o" minimum of cycles so far -- "g" is the whole STSF, "a" the 1st char, "b" the rest | n>o = (-1) -- if current cycle is more than a previous result, -- indicate failure | a==c = z # w y n z g -- if there's a character match, take the min of -- using it and skipping it | c==' ' = w y (n+1) o g -- cycle detected, repeat and adjust n | 1<2 = w y n o g -- otherwise try next char in STSI where -- just some golfing: short names for common subexpressions z = w d n o b; -- number of cycles if a matching char is used y = d ++ [c] -- rotated STSI ``` For reference: old version, full program, 187 bytes ``` main=interact$show.f.lines a#(-1)=a a#b=min a b f[x,y]=w x(y++" ")0 0 w[]_ n _=n w g@(a:b)(c:d)n m|a==c=w b d n 1#y|c==' '&&m==1=w g(d++" ")(n+1)0|c==' '=(-1)|1<2=y where y=w g(d++[c])n m ``` [Answer] # JavaScript (ES6) 174 (193 - 10%) Recursive search, like the @nimi's answer, keeping the min of wraps. The solutions space is big (above all for the last example) but cutting the search at the min currently found keeps the time low. **Edit 1** Add a missing test case, shortened a bit **Edit 2** No need to pass param w around, it's fixed ``` K=(w,s,x)=> ~-(R=(r,l,p=0,q=1,z=w[p],i=0)=> { if(z&&!(q>x)){ if(~(r+l).indexOf(z)) for(t=l?R(l+r,'',p,q+1):x;x<t?0:x=t,i=~r.indexOf(z,-i);) t=R(r.slice(-i),l+r.slice(0,~i),p+1,q); q=x } return q })(s,'') ``` **Ungolfed** ``` K=(word, astring)=> { var minWraps // undefined at first. All numeric comparison with undefined give false var R=(right, left, pos, wraps)=> { var cur = word[pos] var i,t; if (! cur) // when all chars of word are managed return wraps; if (wraps > minWraps) // over the minimum wrap count already found, stop search return wraps; if ( (right+left).indexOf(cur) < 0 ) // if the current char is not found in the remaining part of the string return minWraps; // return the current min, could still be undefined (that means 'no way') if ( left ) // if there is a left part, try a wrapping search with the current char { t = R(left+right, '', pos, wraps+1) if ( !(minWraps < t)) minWraps = t; // set current min if t is less than current min or current min is still undefined } // find all occurrences of current char in the remaining part // for each occurrence, start a recursive search for the next char for(i = 0; (i = right.indexOf(cur, i)) >= 0; i++) { var passed = right.slice(0,i) // the passed chars go in the left part var rest = right.slice(i+1) t = R(rest, left+passed, pos+1, wraps) // try next char in the remaining part, no wrap if ( !(minWraps < t)) minWraps = t; // set current min if t is less than current min or current min is still undefined } return minWraps } var result = R(astring, '', 0, 1) // start with right=string and left empty return ~-result; // decrement. convert undefined to -1 } ``` **Test** In Firefox/FireBug console ``` time=~new Date; [['me','moe'] ,['meet','metro'] ,['ababa','abaab'] ,['abaab','baabaa'] ,['1c1C1C2B','1111CCCcB2'] ,['reverse','reserved'] ,['abcdefg','gfedcba'] ,['xyzyxzzxyx','yxzzazzyxxxyz'] ,['aasdffdaasdf','asdfddasdfsdaafsds']] .forEach(s=>console.log(s,r=K(...s))) time-=~new Date ``` *Output* (last line is the execution time in ms) > > ["me", "moe"] 0 > > ["meet", "metro"] -1 > > ["ababa", "abaab"] 1 > > ["abaab", "baabaa"] 1 > > ["1c1C1C2B", "1111CCCcB2"] 3 > > ["reverse", "reserved"] 2 > > ["abcdefg", "gfedcba"] 6 > > ["xyzyxzzxyx", "yxzzazzyxxxyz"] 2 > > ["aasdffdaasdf", "asdfddasdfsdaafsds"] 2 > > 116 > > > ]
[Question] [ # Background Most (halfway decent) text editors allow you to navigate text using the arrow keys. Up and down allow you to navigate lines, while left and right move across a line but also wrap around. Furthermore, if the line is shorter than your cursor's X position, the cursor appears at the end of the line but returns to the same X position if you keep moving up or down. Perhaps the following visual explanation will help: ## Examples Of Motion A simple sample of text could look like this. The cursor will be inserted between two characters in this text, or at an end. ``` ----- --- ------ let's put the cursor here: X----- --- ------ move down (v): ----- X--- ------ move left (<): -----X --- ------ v ----- ---X ------ v (notice how the X position of the cursor has been maintained) ----- --- -----X- ^ ----- ---X ------ > (more line wrapping) ----- --- X------ < ----- ---X ------ ^ (the X-position from earlier is no longer maintained due to the left-right motion) ---X-- --- ------ ``` # The Challenge Given several lines of ASCII test, find the shortest path from the start location to the end location. The start location is represented by `^` and the end location is represented by `$`, and there will only be one of each. These aren't considered part of the text and don't contribute to that line's "length." The input will consist of several non-blank lines of text. Output will be a series of `^v<>` characters that show one of the shortest paths. You may optionally assume an additional newline at the end of each, but that is not included as part of the navigable text. You can write a program or named function. The winner will be the shortest submission, measured in bytes. ## Example I/O ``` ^Squares are fun$ny vv<v (which is better than the naive vv>>>) Squares ^are funny$ <vv Alp$habet^ Song v<^ Mary had a little lamb, His fleece was white as snow, And$ everywhere that ^Mary went, The lamb was sure to go. ^^>>>>v>>> $^degenerate case (no output) ``` [Answer] # CJam, 139 bytes Well this took many hours to come to something that feels done. It feels like the time it takes to aggressively optimize CJam code is something larger than *O(n)* with respect to the size of the code... You can [try it online](http://cjam.aditsu.net/#code=q_'%24-_'%5E-%3AT%3B'%5E%23%5C'%5E-'%24%23W%7B)2%245Y%245b%2B%7B%3AD%5BL%22_T%3CW%25_N%23)_%40%3EN%2BN%23X-Ue%3E%2B-%22_%22W%25-U%22--2'%3Ct2'%3Et'%2B%2B'(')%5D%3D~0e%3ET%2Ce%3CD3%2F1%24T%3CN%5C%2BW%25N%23X%3F%3AX%3B%7D%2F2%24-%7Dg5b%7B%22%20%5Ev%3C%3E%22%3D%7D%25%5DW%3D&input=%5ESquares%0Aare%0Afun%24ny), but for any input for which the best path is at least 6 operations or so, you should probably [try it offline](https://sourceforge.net/projects/cjam/) with a faster interpreter. Squished: ``` q_'$-_'^-:T;'^#\'^-'$#W{)2$5Y$5b+{:D[L"_T<W%_N#)_@>N+N#X-Ue>+-"_"W%-U"--2'<t2'>t'++'(')]=~0e>T,e<D3/1$T<N\+W%N#X?:X;}/2$-}g5b{" ^v<>"=}%]W= ``` Expanded and commented: ``` q "Read the input"; _'$- "Remove the end marker"; _'^-:T; "Remove the start marker and save the text"; '^# "With only the end marker removed, locate the start marker"; \'^-'$# "With only the start marker removed, locate the end marker"; W "Initialize the path number to -1"; { "Do..."; ) "Increment the path number"; 2$ "Initialize the cursor position to that of the start marker"; 5Y$5b+ "Convert the path number to base 5, then add a leading 5 (the leading 5 will act to initialize the column memory)"; {:D "For each digit in the path digit string:"; [ "Begin cases:"; L "0: Do nothing"; "_T<W%_N#)_@>N+N#X-Ue>+-" "REFS: [ 1 ][ 2 ][ 3 ]45 1: [1] Calculate the distance to the end of the previous line (0 if no such line) [2] Calculate the length of the previous line (0 if no such line) [3] Calculate the distance to move backwards in the previous line as the maximum of the length of the previous line minus the column memory and 0 [4] Calculate the total distance to move as the sum of [1] and [3] [5] Subtract [4] from the cursor position"; _"W%-U"- "2: Start with a base of the logic of case 1, but with a few operations adjusted."; -2'<t2'>t " [1] Calculate the distance to the *start* of the *next* line (0 if no such line) [2] Calculate the length of the *next* line (0 if no such line) [3] Calculate the distance to move *forwards* in the *next* line as the *minimum* of the length of the *next line* and *the column memory* [4] Calculate the total distance to move as the sum of [1] and [3]"; '++ " [5] *Add* [4] *to* the cursor position"; '( "3: Decrement the cursor position"; ') "4: Increment the cursor position"; ]=~ "Execute the case corresponding to the path digit mod 5"; 0e>T,e< "Clamp the cursor position to [0, text length]"; D3/ "Check if the path digit is not 0, 1, or 2..."; 1$T<N\+W%N# "Calculate the current column"; X?:X; "If the above check succeeded, update the column memory"; }/ "End for each"; 2$- "Subtract the end marker position from the cursor position"; }g "... While the above subtraction is nonzero"; 5b "Convert the path number to base 5"; {" ^v<>"=}% "Map each digit in the path string to its operation symbol"; ]W= "Clean up"; ``` Overall, this is a pretty straightforward solution. It "executes" the digits of the base-5 representation of a path number that is incremented every iteration, starting with 0, until a path works. The digits `1`-`4` map to the operations up, down, left, and right, and `0` does nothing. The first iteration using a path of just `0` catches the degenerate case. All other paths that contain a `0` are never selected because they're just versions of already-tested paths with added no-ops. The state is modeled in as minimalistic of a way as possible: the text with start and end markers removed, the cursor position in the text, and the "column memory." Newlines are mostly treated like any other character, so there's no concept of a row, and the cursor position is just an index. This makes moving left and right dead simple, which are just implemented as decrement and increment (with clamping to the size of the text). Moving up and down is a bit trickier, but still manageable. Code reuse was a pretty vital optimization tactic. Examples of this include: * Writing the code for moving up in a way such that it's smaller to generate the code for moving down at runtime than to write its own code. This is done by copying the code for moving up and removing/replacing a few characters. * Updating the "column memory" is done conditionally based on the path digit divided by 3 instead of it being coded into the logic of the operation. This also allows initialization of the column memory by adding a dummy `5` operation to the start of the path string, which also just so happens to use the `0` no-op logic due to circular array indexing and there being only 5 defined operations. Overall, I'm very happy with how this came out. This is definitely the most work I've put into a code golf answer to date (for something that fits into a tweet!?). The run time is pretty abysmal, though. CJam isn't exactly the fastest language to begin with and this algorithm has a complexity of something like *O(m\*5n)*, where *m* is the size of the input and *n* is the size of the output. Good thing speed doesn't count! [Answer] # Python 2: 446 ``` Q=input().split('\n'); def g(c):l=[l for l in Q if c in l][0];return Q.index(l),l.index(c) a,b=g('^');c,d=g('$');Q=map(len,Q);Q[a]-=1;Q[c]-=1 if a==c:d-=b<d;b-=d<b t=-1 while Q: l=[];T=t=t+1;x,y,z=a,b,b while T:l+=[T%5]*(T%5>0);T/=5 for T in l:A=":x+=T+T-3;y=min(Q[x],z)";B="x<len(Q)-1";exec"if "+["","x"+A,B+A,"y:y=z=y-1\nelif x:x-=1;y=z=Q[x]","y<Q[x]:y=z=y+1\nelif "+B+":x+=1;y=z=0"][T] if(x,y)==(c,d):print''.join(' ^v<>'[x]for x in l);Q=0 ``` Straightforward solution. I'm performing a breadth-first search. `t` iterates over all different paths. I convert `t` into base `5`, but only use the entries, which are nonzero. `1` is up, `2` is down, `3` is left and `4` is right. I keep the current position of the cursor in 3 variables `x`, `y` and `z`. `x` is the line, `y` the column position, and `z` the 'hidden' column position, if you go up or down and the line is too short. Lots of ifs decide, how the variable change during a move. Preprocessing is really lengthy, the first 4 lines perform only this task. The long testcase takes a really long time. The algorithm has a complexity of O(N\*5^N), where N is the length of the shortest solution. Usage: Input the lines as a single string (lines seperated by `\n`) like `"Alp$habet^\nSong"` [Answer] # CJam - 274 No answer yet? Ok, here's one :) ``` qN/_{0:V;{_'^={[UVV]:B;;}{'$={[UV]:E;}{V):V;}?}?}/U):U;}/"^$"f-:,:A;{:X0=[X0=(_A=X2=_@e<\]X?}:U;{:X0=A,(=X[X0=)_A=X2=_@e<\]?}:D;{:X1=[X~;(_]{X0=[X0=(_A=_]X?}?}:L;{:X1=X0=A=={X0=A,(=X[X0=)0_]?}[X~;)_]?}:R;[[BM]]{_{0=2<E=},_{0=1=o0}{;[{"U^DvL<R>"2/\f{[~@1/~@\+@@~\]}~}/]1}?}g; ``` Try it at <http://cjam.aditsu.net/> ... except for the Mary example or something of that size, you'll probably want the [java interpreter](https://sourceforge.net/projects/cjam/). ]
[Question] [ This is based on a game one of my math teachers used to play in middle school. He would write 5 random one-digit numbers on the board, and then a random two-digit number. We would try to create an equation that used all 5 of the one-digit numbers to yield the two-digit number. Here are some examples with solutions to explain this better: ``` Input: Solution: 7 5 4 8 4 34 5*8-7+4/4 = 34 3 1 5 7 6 54 (7+3)*6-5-1 = 54 3 9 2 1 6 87 9*(2+1)*3+6 = 87 2 1 6 9 7 16 (9-7+6*1)*2 = 16 2 4 5 8 6 96 8*(5+6)+2*4 = 96 3 8 4 5 4 49 8*(4+4)-3*5 = 49 ``` This challenge is to write a program that can generate such equations for a given input. The input can be provided either via the command line or via a prompt. The 5 one-digit numbers will always be entered first (in no particular order), followed by the two-digit number. The program will then print out a solution equation it finds; you do not have to handle situations where there is no solution. The function must be capable of using the following operations in the equation: addition, subtraction, multiplication, and division. If you would like to allow additional basic operations, that's fine as long as they remain in the spirit of the challenge (negation, exponentiation, and modulus would be nice additions). Order of operations follows the standard math rules, so parenthesis will be needed for grouping. The program must take less than a minute to run on a modern computer. Programs will be scored based on code length (including required whitespace). Note: division must be exact, not rounded or truncated to nearest integer. [Answer] ## Python 2.7 (284), Python 3.x (253) ``` from __future__ import division #(Remove for Python 3.x) from itertools import * a=raw_input().split() for i in permutations(a[:-1],5): for j in product('+-*/',repeat=5): for k,l in combinations(range(1,12,2),2): d=''.join(sum(zip(i,j),()))[:-1];d='('+d[:l]+')'+d[l:] if eval(d)==int(a[-1]):print d;b ``` It gives an error (calling unknown function `b`) on solution. Basically, it's a gigantic brute force. It takes in the input, splits it by its spaces (`1 2 -> [1,2]`), and then permutes through that list. With every permutation, it will iterate through all possible strings of length 5 using the characters `+-*/`. With each of those iterations, it will generate the combinations of length 2 of the list `[1,3,5,7,9,11]`, interweave the permutation and the string together (`12345 *-/+- -> 1*2-3/4+5-`), and put in the parentheses. Finally, it will evaluate it, and if the answer and equation are true, then it prints the equation and stops. This is horribly inefficient, about `O(n!/(n-5)!)=O(n^5)`, but it runs in a reasonable time for the test inputs. [Answer] ### Scala 368: The 2nd g=-Line is more easy to test, the first is flexible to take command arguments, and both are of equal length, so I only count from the second one - remove it to do args passing: ``` val g=(args.map(_.toDouble)) val g=Array(3,9,2, 1, 6, 87) val k="+*/-DQ" val i=(0 to 5) val f:Seq[(Double,Double)=>Double]=Seq(_+_,_*_,_/_,_-_,(a,b)=>b-a,(a,b)=>b/a) val h=g.init.permutations; for(j<-h;o<-i;p<-i;q<-i;r<-i;z=try{f(r)(f(q)(f(p)(f(o)(j(0),j(1)),j(2)),j(3)),j(4))}catch{case _ => 0} if(z==g(5)))printf("(((%d%c%d)%c%d)%c%d)%c%d=%d\n",j(0),k(o),j(1),k(p),j(2),k(q),j(3),k(r),j(4),g(5)) ``` Sample output (you might have a question right now - just a moment): ``` (((5+7)/1)+6)*3=54 (((5-7)D1)*6)*3=54 (((5D7)+1)*6)*3=54 (((5+7)+6)Q1)Q3=54 ``` What about this 5D7 thing? D1? Is it hex? There is Q1, Q3 - what's that. Sir\_Lagsalot allowed new basic operations in the spirit of the challenge, and yes, these are basic operations, Delta and Quotient. They are different from a/b and a-b in that aQb means b/a and aDb means b-a. Let's call it the Ukrainian notation. So ``` (((5-7)D1)*6)*3=54 ``` means ``` ((1-(5-7))*6)*3=54 (1-(-2))*6*3 3*6*3 = 18*3=54 ``` To the more interesting question of the how and why: In the beginning I got mad about the possibilities to place the parentheses, and whether (a+b)-c = a+b-c = (a+b-c) = ((a+b)-c) = (b+a)-c and so on. You can get mad over this question, but if you write down the possible parenthesis combinations, you sometimes throw away the scratch sheet and face the fact: You always perform 4 operations between 5 values, and you always start with one of them. If the pattern is always `(((_x_)x_)x_)x_ ?= _` (x being one of the 4 operators) and allow the opposite direction ( x b) and (b x a), you addressed every possibility. Now for a+b and a\*b we don't need no opposite direction, they are commutative. So I invented the D and Q operator, which just switch the direction. I now have 2 operators more, but don't need to switch direction. Well - it is done in the function Sequence: ``` (a,b)=>b-a,(a,b)=>b/a ``` My for-comprehension takes the values from the Array g, and distributes them on a to e, then I pick 4 indexes to pick the function and later the (only by index) associated operator symbol. I have to catch div/0 errors, since subtraction can lead to zeros, while the sample input data doesn't contain a 0. ]
[Question] [ ## Introduction: I'm old-fashioned and still read a physical newspaper in the morning while eating my breakfast. Although I don't like Sudoku that much, I do solve the Light-complexity ones, which are extremely easy. With these, I always try to solve all the numbers using only the Hidden Single technique†, in increasing order from 1 to 9. If I can fill in the current digit in all nine of it cells, I write it down at the top. Thus far, I've only been able to complete the entire Sudoku in increasing order once††. Usually, a digit has two paired cells where they can go in either combination, so I'll skip them, and fill them in at the end. † Naked Single and Hidden Single solving techniques are the basic Sudoku solving strategies that won't require any hint numbers to be used. When I solve the Light-complexity Sudoku in my newspaper, and therefore also in this challenge, I only use the Hidden Single solving technique. Here the relevant quote from [my Puzzling SE post](https://puzzling.stackexchange.com/a/30540/13190): > > **2. Hidden Single** > > > Again, a pretty easy one that everyone knows: When there is only one place in a particular row, column or block for a specific number to go, we can just fill it in. For example: > > > [![enter image description here](https://i.stack.imgur.com/gXZs1.png)](https://i.stack.imgur.com/gXZs1.png) > > > Here there is only one place for the 2 to go in the center 3x3 box, and that is the marked cell. > > > ## Challenge: Given a Sudoku, output the set of digits which you were able to fill in all nine occurrences of while solving the Sudoku with only Hidden Single techniques, when going in increasing order from 1 to 9. **Example:** Input: ``` [[3,7,0, 0,0,0, 1,0,4], [0,1,8, 2,4,0, 0,0,3], [0,0,0, 1,7,0, 8,0,0], [0,6,2, 0,0,7, 4,0,5], [9,0,7, 5,0,0, 0,6,1], [0,0,0, 0,1,9, 0,0,0], [8,0,4, 0,0,2, 0,0,0], [0,0,0, 0,8,0, 2,0,9], [0,3,1, 0,9,6, 5,4,0]] ``` We first try to fill in all the 1s using Hidden Single techniques: ``` [[3,7,0, 0,0,0, 1,0,4], [0,1,8, 2,4,0, 0,0,3], [0,0,0, 1,7,0, 8,0,0], [1,6,2, 0,0,7, 4,0,5], [9,0,7, 5,0,0, 0,6,1], [0,0,0, 0,1,9, 0,0,0], [8,0,4, 0,0,2, 0,1,0], [0,0,0, 0,8,1, 2,0,9], [0,3,1, 0,9,6, 5,4,0]] ``` Since we were able to fill in all 1s, we add the `1` to the result-set. Next up are the 2s: ``` [[3,7,0, 0,0,0, 1,2,4], [0,1,8, 2,4,0, 0,0,3], [0,2,0, 1,7,0, 8,0,0], [1,6,2, 0,0,7, 4,0,5], [9,0,7, 5,2,0, 0,6,1], [0,0,0, 0,1,9, 0,0,2], [8,0,4, 0,0,2, 0,1,0], [0,0,0, 0,8,1, 2,0,9], [2,3,1, 0,9,6, 5,4,0]] ``` We were again able to fill in all digits, so we add the `2` to the result-set. Next up are the 3s: ``` [[3,7,0, 0,0,0, 1,2,4], [0,1,8, 2,4,0, 0,0,3], [0,2,0, 1,7,3, 8,0,0], [1,6,2, 0,0,7, 4,0,5], [9,0,7, 5,2,0, 0,6,1], [0,0,3, 0,1,9, 0,0,2], [8,0,4, 0,0,2, 0,1,0], [0,0,0, 0,8,1, 2,0,9], [2,3,1, 0,9,6, 5,4,0]] ``` We were only able to fill in two 3s, with four 3s still left to fill in. So we won't add it to the result-set, and continue with the 4s: ``` [[3,7,0, 0,0,0, 1,2,4], [0,1,8, 2,4,0, 0,0,3], [4,2,0, 1,7,3, 8,0,0], [1,6,2, 0,0,7, 4,0,5], [9,0,7, 5,2,4, 0,6,1], [0,4,3, 0,1,9, 0,0,2], [8,0,4, 0,0,2, 0,1,0], [0,0,0, 4,8,1, 2,0,9], [2,3,1, 0,9,6, 5,4,0]] ``` These we were able to fill all in, so `4` will be added to the result-set. Next up are the 5s: ``` [[3,7,0, 0,0,0, 1,2,4], [0,1,8, 2,4,0, 0,0,3], [4,2,0, 1,7,3, 8,0,0], [1,6,2, 0,0,7, 4,0,5], [9,0,7, 5,2,4, 0,6,1], [5,4,3, 0,1,9, 0,0,2], [8,0,4, 0,5,2, 0,1,0], [0,0,0, 4,8,1, 2,0,9], [2,3,1, 0,9,6, 5,4,0]] ``` We were able to fill in two 5s, with four 5s still left to fill in. So we won't add it to the result-set, and continue again. Etc. for 6s (not added); 7s (not added); 8s (added); and 9s (added). The Sudoku after all the digits looks like this: ``` [[3,7,0, 9,6,8, 1,2,4], [0,1,8, 2,4,0, 9,0,3], [4,2,9, 1,7,3, 8,0,0], [1,6,2, 8,0,7, 4,9,5], [9,8,7, 5,2,4, 0,6,1], [5,4,3, 6,1,9, 0,8,2], [8,9,4, 0,5,2, 0,1,0], [7,0,0, 4,8,1, 2,0,9], [2,3,1, 0,9,6, 5,4,8]] ``` You don't have to solve the Sudoku any further. You can simply output the final result-set, which is `[1,2,4,8,9]` for this Sudoku. ## Challenge Rules: * Although we solve the Sudoku from 1 to 9, the result-set doesn't necessarily have to be ordered. * The input-Sudoku can be in any reasonable format. Can be a matrix of integers with `0` or `-1` for empty cells; a flattened list of integers; a string with spaces for empty cells; or even an image file for all I care. Please specify your input-format in your answer. * Likewise, the output can be in any reasonable format as well. Can be a list of digits; a string of digits; printed on separated lines to STDOUT; a 1-based indexed binary-list of size 9 for which digits were truthy; etc. ## General Rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test Cases: (Using a matrix input and list output.) ``` Input: [[3,7,0, 0,0,0, 1,0,4], [0,1,8, 2,4,0, 0,0,3], [0,0,0, 1,7,0, 8,0,0], [0,6,2, 0,0,7, 4,0,5], [9,0,7, 5,0,0, 0,6,1], [0,0,0, 0,1,9, 0,0,0], [8,0,4, 0,0,2, 0,0,0], [0,0,0, 0,8,0, 2,0,9], [0,3,1, 0,9,6, 5,4,0]] Output: [1,2,4,8,9] ††Input: [[0,0,0, 0,6,0, 0,7,0], [4,8,0, 7,0,0, 0,0,6], [2,7,0, 4,5,0, 1,0,3], [8,0,0, 1,0,0, 6,3,0], [0,0,2, 0,0,5, 9,1,0], [0,6,9, 0,8,2, 0,0,0], [7,0,0, 0,0,0, 0,2,1], [0,0,4, 9,0,8, 0,5,0], [0,3,1, 0,4,7, 8,0,0]] Output: [1,2,3,4,5,6,7,8,9] Input: [[0,0,9, 4,0,0, 7,1,0], [0,1,2, 0,7,0, 0,0,9], [0,4,0, 2,1,0, 5,0,0], [0,2,6, 0,0,0, 0,5,4], [0,0,0, 1,8,0, 6,0,7], [7,0,8, 6,5,0, 0,0,0], [9,0,0, 0,0,3, 0,6,0], [6,0,4, 0,2,8, 1,0,0], [0,8,0, 7,0,0, 0,9,5]] Output: [1,4,6,7,8,9] Input (actually a High-complexity Sudoku from my newspaper): [[0,0,0, 2,4,0, 5,0,0], [9,0,0, 0,0,8, 0,0,0], [0,0,0, 0,0,0, 0,0,8], [0,0,0, 0,2,0, 7,0,4], [0,0,7, 0,0,0, 3,0,0], [0,4,9, 5,0,0, 1,6,0], [3,9,0, 0,8,5, 0,2,0], [1,0,8, 0,3,0, 4,0,0], [0,0,0, 1,0,0, 0,0,0]] Output: [] ``` [Answer] # JavaScript (ES6), 239 bytes Returns a string of digits, or *undefined* if no set at all was completed. ``` m=>(i=1,g=o=>i>9?o:g([u=M=0,1,2,n=9].map(N=p=>m.map((r,y)=>r.map((v,x)=>(A=[x,y+9,b=x/3-~(y/3+5)*3|0],k=v==i,q=1<<x|1<<y+9|1<<b,M|=k*q,v|=M&q,p^9?p^2?p*v&&A.map(j=>N[j]=-~N[j]):v|A.every(j=>N[j]^8)?0:r[x]=u=i:n-=k))))|n|u?o:[o]+i,i+=!u))() ``` [Try it online!](https://tio.run/##hVLbbuIwEH3nK9gXlMBAkzg3s50gPoD@QBQk2qUoUJKQLhFIUX@dtR3bMVS7mwdP7DOXM2dmv2k2n291Xv2eFuWv7e0db0dMrBxd2GGJSZ7QRTnfWekZV@iACx4USLPZcVNZL1hhchS/Vg1XG5O6uzRwYRdriekFrhMKr3h5ItMv6/pEJoE9Jq2TwQEbxBxO6D4/X1p2MEduXmHV4mF8gqbF1egE1ZouqrW3qMbNaLQU@feYvKT7DKdf3Njzpl3Ots22vipkHdsLZ16nlwzPmM@LKR5s9rVFe2bNpGU2ySGf4I@zbVv27a0sPsuP7eyj3FnvVjoYpgQicGA4dMAR1mWnnwFDuAIxe/HA1x5EIsq3i435nSMCC5lunXfELI8NRBSVL4GM5p7uXT5ekSouMh/P7cs3z8SMqFhYj51UIoRl4ghlNXhFxiIbZLb9c/BdAcfg09lIVvBl5kh7MB@BeLJzHwKtGjEYqzduQ8amZ6x6CJiljKVCQtl5fN8lw8zqnfUM3XyRxxGT4lmdBwV8oXk3oX8pQOWsun57Xq7k02@J0tiXqrvCBnc74Ande8aB3imlTSy1YZkFEskeQqmoqQA1FCBqUiIq1NvhiWjX2I7H2VG2h//bAbXrupu72vFf9s/w0Ar0s1IsegUiI4oY@XwxhUBrFGoFCFC964HKK6JczYvIjXzk55o8OwVufwA "JavaScript (Node.js) – Try It Online") ### How? We use a recursive function \$g\$ starting with \$i=1\$ and making its way to \$i=10\$, at which point it immediately stops. The value of \$i\$ is the digit that we're currently processing in the grid. Each iteration is divided into 4 passes. During each pass, we walk through each cell of value \$v\$ at position \$(x,y)\$. The following variables are always computed, no matter which pass is processed: ``` k = v == i // is the current cell set to i? b = x / 3 - ~(y / 3 + 5) * 3 | 0 // box number in [18 .. 26] A = [x, y + 9, b] // [ column, row, box ] q = 1 << x | 1 << y + 9 | 1 << b // column/row/box bit mask ``` 1. We set up a 27-bit mask \$M\$ telling in which columns, rows and boxes \$i\$ appears. ``` M |= k * q ``` 2. For each column, row and box, we figure out the number of cells \$N[j],\:j\in\{x,y+9,b\}\$ where \$i\$ can't possibly appear. ``` v |= M & q v && A.map(j => N[j] = -~N[j]) ``` 3. If a column, row or box has exactly 8 cells where \$i\$ cannot appear, we set the remaining cell to \$i\$ and set the flag \$u\$. This is the actual implementation of the *hidden single* rule. ``` v | A.every(j => N[j] ^ 8) ? 0 : r[x] = u = i ``` 4. During the last pass, we decrement \$n\$ (which is initialized to 9) whenever a cell of value \$i\$ is found in the updated grid. ``` n -= k ``` If \$u\$ was set, it means that the grid was updated and we do a recursive call with \$i\$ unchanged. Otherwise, we do a recursive call with \$i+1\$ and append \$i\$ to the final output string if \$n=0\$. ``` g(n | u ? o : [o] + i, i += !u) ``` [Answer] # Python3, 677 bytes: ``` R=range E=enumerate r=R(0,9,3) K=lambda b:[(B:=[[(x,y)for y,k in E(j)]for x,j in E(b)]),[*zip(*B)],[[t for X in B[x:x+3]for t in X[y:y+3]]for x in r for y in r]] S=lambda x:type(x)==int Q=R(1,10) def U(b,I): b=eval(str(b)) for x,j in E(b): for y,k in E(j): if k==0:b[x][y]={*Q}-{b[X][Y]for i in K(b)for T in i for X,Y in T if((x,y)in T)&S(b[X][Y])} for x,j in E(b): for y,k in E(j): if 1-S(k)and{I}==k-{L for X,Y in{*[i for i in K(b)[-1]if(x,y)in i][0]}-{(x,y)}for L in[b[X][Y],[]][S(b[X][Y])]}:b[x][y]=I return[[[0,i][S(i)]for i in J]for J in b] def f(b): for i in Q: while b!=(b:=U(b,i)):1 if all(any(i==b[x][y]for x,y in T)for O in K(b)for T in O):yield i ``` [Try it online!](https://tio.run/##lVXJbtswEL3rK9hLQbo0oN2SAF4C5JAFCLIUSEDwIMFyo9hRDFVppRr@dmdIURTtpodeNJr9vZmxvO3b57c6SLbN4XDHmrz@UTrnrKzfX8smb0unYXfYpSkNiHPFNvlrscxRkXF8ljHOcUd7snprUE/XqKrROX4hQuodfRn0gghC@exPtcWzMyIo5y2SAY/Sfca7rPsWqIxWGh55n/VgGGpIS6Oie/UqhHM/Quiytt@WuCOMVXXr3AJKj3oucZblCn3HBb0gmYMKVv7KN/hn2wAQ4qATaBCBTtBLE6pWaM2YmxW8E7wXbDe73c93BX8U/ElBq2T4FVSQyoNUqoEVfZIKWFZYzUYq5Os91rlk/z8YvPk9XpO8Xu4u9oyt57trq8luxoeeBgufewL66raV4K4A1Erfy8BrCOQaCOVC8AmW2BuuFw5qyva9qTnnLq1kVEUm0pfq9VK@FkINezWQMBG3Ev7v52pTouILw0XG5DoqQjLPUbTyzQbndY8rxnTTYSRqyQ9qpDd/zfeGZH1VbpaoOhRvebP0EEOcB3RBXYqQS10lPXiGgjoIoHs0AYtPQxMRaM8YO@QmUpce5Yupr6MXIGVupLJSbYl0toz0jurJjumIRdeTtUNt822flZUo6cMz1Z4AKklPCj1kR0ABp69o@4xbqbGWC1001MUWJgJilMfXZEMamUEFFsjRJmUMACaQI@wIZArARk@sySbHxMBndx@kb40qVHVctRxZ1T0hHaoxD0vRpAOkWad6JQPHCYunMUzHMI4y1MP1lIyOVu2r8U4oI3M64zwSPQ@orDwLjTvWU7RZpxbrYNyOyorNEfgq27OO4HRfKZybZh1aqx6v2BA4apf847KsCEN6WsnYeCK9sLICq16oBh@ZscSGdEBTc8XRWFdleQZXoA/vFJ9n4wTS2wY@5JjP4HuifuDwx3Fq8z@xBZ/YQrAdPgA) ]
[Question] [ You've arrived on an alien planet. The writing system, the culture and the language there are completely foreign to any language you know. But somehow they are all playing wordle already. So as a method to learn their language and culture you start playing their version of wordle. Their wordle works a little bit differently than ours. Just like ours it's a guesssing game. There's a secret hidden word which you must guess. The secret word is made of 5 glyphs, and at each step of the game you guess 5 glyphs. The game then highlights each of them either * \$\mathrm{Black}\$: if that glyph doesn't appear in the word at all. * \$\color{orange}{\overline{\mathrm{Yellow}}}\$: if that glyph appears in the target word but in a different place. * \$\color{green}{\underline{\mathrm{Green}}}\$: if that glyph appears in the target word at the same place. Unlike our wordle there are no special rules for double letters. Now because you don't know the language all you can do is guess random sequences of glyphs to eventually brute force some information out of the game. If we look at this example game where I've replaced the alien glyphs with positive numbers for convenience: $$ \begin{matrix} 1 & 2 & \color{green}{\underline 3} & 4 & 5 \\ 6 & \color{green}{\underline7} & \color{orange}{\overline 8} & \color{green}{\underline 9} & 4 \\ \color{orange}{\overline 0} & 10 &\color{orange}{\overline 7} & \color{green}{\underline9} & 4 \\ \end{matrix} $$ In the first guess we found out \$3\$ was the middle letter and that \$1, 2, 4, 5\$ don't appear in the solution. In the second guess we learned that \$7\$ and \$9\$ are the second and fourth positions respectively. We also learned that \$8\$ appears somewhere, and that \$6\$ doesn't appear anywhere. In the third guess we learned that \$0\$ appears but not in the first position. At this point since we know that the second, third and fourth positions are occupied \$0\$ must be in the last position. This leaves one position, the first, open for \$8\$. So from this board we know the solution is \$8\,\,7\,\,3\,\,9\,\,0\$. You don't know how many glyphs are present in the alien language, so you cannot do process of elimination to determine a glyph is in the solution without having a guess containing that glyph. # Task Given a list of guesses and a list of color responses, determine if the solution can be uniquely determined from the board. Glyphs should be represented by integers, and you may assume they are strictly positive. Other than that you may take input in any reasonable format. For example the colors could be `0 1 2` or `B Y G`. You may take the list of guesses and color responses separately or zipped together as a single structure. You may assume that each guess is 5 glyphs long and each response as well. You should output one of two fixed values if the solution is uniquely determined and the other of the two values if it is not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code as scored in bytes. # Test cases Test cases are presented as alternating guesses and responses. The guesses are (mostly) single digit numbers for the convenience of formatting, but this should not be assumed. Responses are in the form of `B Y G` for black yellow green respectively. Ones ## Unique solution ``` 5 4 3 2 1 G G G G G ``` ``` 1 2 3 4 5 Y Y G G G ``` ``` 1 2 3 4 5 Y B G B B 6 7 8 9 0 B B Y G G ``` ``` 1 2 3 4 5 B B G G G 6 7 8 9 0 G G B B B ``` ``` 9 3 3 8 4 G G Y Y G 1 2 3 5 6 B Y Y B B ``` ``` 2 2 3 2 1 Y Y G Y Y 4 1 3 1 5 Y Y G Y Y 6 5 3 4 10 B Y G Y B ``` ## No unique solution ``` 1 1 1 1 1 1 2 2 2 2 ``` The first value isn't 1, but it could be anything else. Example solutions: `0 1 1 1 1`, `2 1 1 1 1` ``` 1 2 3 4 5 B G G G G 1 6 8 7 9 B B B B B ``` There is one value missing which could be anything. Example solutions: `0 2 3 4 5`, `10 2 3 4 5` ``` 1 2 3 4 5 Y Y Y Y Y ``` You know the glyphs in the solution but cannot determine the order. Example solutions: `5 3 4 2 1`, `5 4 2 3 1` ``` 1 2 2 3 4 G G Y Y G ``` Unlike earth wordle you don't know whether there are 1 or two 2s based on this. Example solutions: `1 2 3 2 4`, `1 2 3 5 4` --- This puzzle was inspired by the [kilordle](https://jonesnxt.github.io/kilordle/) wordle variant. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 28 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Takes glyphs as positive integers and the colors as `012` for `BYG`. ``` {1=+´𝕨≡⎉1⍉𝕩(∊+=)⌜⥊↕5⥊2+⌈´∾𝕩} ``` [Run a few cases online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgezE9K8K08J2VqOKJoeKOiTHijYnwnZWpKOKIiis9KeKMnOKliuKGlTXipYoyK+KMiMK04oi+8J2VqX0KCuKfqAoiVHJ1dGh5OiIK4p+o4p+oMiwyLDIsMiwy4p+p4p+pIEYg4p+o4p+oNSw0LDMsMiwx4p+p4p+pCuKfqOKfqDEsMSwyLDIsMuKfqeKfqSBGIOKfqOKfqDEsMiwzLDQsNeKfqeKfqQoj4p+o4p+oMSwwLDIsMCww4p+pLOKfqDAsMCwxLDIsMuKfqeKfqSBGIOKfqOKfqDEsMiwzLDQsNeKfqSzin6g2LDcsOCw5LDEw4p+p4p+pCiPin6jin6gwLDAsMiwyLDLin6ks4p+oMiwyLDAsMCww4p+p4p+pIEYg4p+o4p+oMSwyLDMsNCw14p+pLOKfqDYsNyw4LDksMTDin6nin6kKI+KfqOKfqDIsMiwxLDEsMuKfqSzin6gwLDEsMSwwLDDin6nin6kgRiDin6jin6g5LDMsMyw4LDTin6ks4p+oMSwyLDMsNSw24p+p4p+pCiPin6jin6gxLDEsMiwxLDHin6ks4p+oMSwxLDIsMSwx4p+pLOKfqDAsMSwyLDEsMOKfqeKfqSBGIOKfqOKfqDIsMiwzLDIsMeKfqSzin6g0LDEsMywxLDXin6ks4p+oNiw1LDMsNCwxMOKfqeKfqQoiRmFsc3k6Igoj4p+o4p+oMCwyLDIsMiwy4p+pLOKfqDAsMCwwLDAsMOKfqeKfqSBGIOKfqOKfqDEsMiwzLDQsNeKfqSzin6gxLDYsOCw3LDnin6nin6kK4p+o4p+oMSwxLDEsMSwx4p+p4p+pIEYg4p+o4p+oMSwyLDMsNCw14p+p4p+pCuKfqOKfqDIsMiwxLDEsMuKfqeKfqSBGIOKfqOKfqDEsMiwyLDMsNOKfqeKfqQrin6jin6gxLDIsMiwyLDLin6nin6kgRiDin6jin6gxLDEsMSwxLDHin6nin6kK4p+p) or [All cases on ATO!](https://ato.pxeger.com/run?1=m704qTBvwaq0R20THnVNfDR_xdLSkjRdi5vW1Ya22oe2fJg7dcWjzoWP-joNH_V2AnkrNR51dGnbaj7qmfNoadejtqmmQMpI-1FPx6Etjzr2gVTUQoy4xbTt0fyVXI8aFvmXlhxaoQA0m0sppKi0JKPSSokLyAMiIx0oBKoEIgU3BYi4qY6JjjFQ3BAiDlVtqGOIVTVI1BiowxRNtQFQ3EDHACikA-QDWRD9eHSD1JnpmOtY6FjqGBqgGGcANg6iXQfqdAOo8WQYB9IO9g_cdSAepnGWQMOMgQaYQNVBjDfVMcMSMobg8NLBwjeA8tFNNwKbZgRXZwJUYwzECMebgj0Dd7ySW2JOMSL-DJDiDxbGxASKoY4Z0E_mOpYYvjCEuppw_CKHILpqsHo0s7GnNDQ7gapXQpLvggUQGgA). Brute-force approach. Generates all words with glyphs in \$\{0,1, \cdots ,\operatorname{max}(\text{guesses}) + 1\}\$ and checks if there is exactly one word that produces the same colors for the given guesses. Takes a list of guesses as the right argument `𝕩` and the response colors as `𝕨` on the left. `∾𝕩` Flatten the guesses to get a list of all glyphs used in the guesses. `⌈´` Get the maximum of that (call this \$m\$). `5⥊2+` a vector of 5 copies of \$m+2\$. `⥊↕` All indices of an array of these dimensions. This is a list of all 5-glyph word with glyphs up to \$m+2\$: \$\{0, 1, \cdots,m,m+1\}^5\$. Note that the two glyphs \$0\$ and \$m+1\$ did not appear in the guesses. This makes sure that there are at least two distinct possible secrets if a not-yet-guessed glyph can be in the solution. `𝕩(∊+=)⌜` For each of these words as a secret, and each guess in `𝕩`, judge the guess. The judge function `∊+=` reads: (implicit: for each glyph in the guess) does it occur the secret? (`∊`) + does it appear at the same index? (`=`). (This is much simpler than [highlighting a guess in the human variant](https://codegolf.stackexchange.com/a/241726/64121)) Now we have a wide table table with the colors for one possible secret per column. This gets transposed (`⍉`) such that each secret gets its own row. `𝕨≡⎉1` For each row, do the colors equal the input colors? `+´` Sum the values, count how many times the previous was truthy. `1=` Did this only happen once? [Answer] # Python 3, 432 428 401 348 335 330 319 295 bytes Takes input as an array, `[ [ [glyphs1],[colors1] ], [ [glyphs2],[colors2] ], ...]`, where the glyphs are integers `> 0`, yellow is `-1`, black is `0`, and green is `1`. Returns `True` and `False` for solvable/unsolvable. ``` def w(a): G,v,y=[0]*5,{0,1,2,3,4},{} for j in a: for i,g,c in zip(range(5),*j): if c>0and{i}&v:G[i]=g;v-={i} elif c<0:y[g]=y.get(g,{i})|{i} while 1: n=dict(y) for i in y: if x:=len(d:=v-y[i])<1:del n[i] elif x<2>1+G.count(i):j,*_=d;v-={j};G[j]=i if y==n:return not v y=n ``` [TIO link with extra code to run all test cases](https://tio.run/##jVRdj6IwFH3nV9x1MhvQq6EizsjYedns@L47b6TZEKhMjUED@MHO@tvdtnyICWNMTAXuOfec3tvebZF/bBLnfI74Eg5mYHkGLHCPBfVt1nfx00aCY3RwcsLPkwHLTQorEAkEEqjfBMYYqi9/xdZMgyTmpmthf6UyAYglhK92kESf4vR97y18wWj8sh9S@a7ifK0Qc9sr/JjRYhTz3IxRBq1/GnH4EGsOROVKaCTC3CysWliJFrXK0aNrnpiRR/fDQqpYc@JFfA2JfG6EjvPxKxksRuFml@SmsLwV9v/QSPtZnV4W/opRYeh8BaWJl/J8lyaQbHLYy88FTQwj51meAQVfZa1W/eS7CBMEB2GMQBj6QLD1Ywzg4QF@BJncj2ZJSItNNM/ROVwZGhIcdrPH97HB1lS52oxhw3ZarCnCE8IzwgyJrRwrcCPL2B1CJeVi8yI0uSVEGm/aHnQozbSMo2mThlOXpa3k3vZXUUqlDqFxTan61lReP7SFpi3WRO/A0avbxbrevluZquvcYL8wdX12yoZ2H4enO7tEOrv0fM2a6nLLXs0uvbVv1K771A6bKlxszr5kVwk6Wty6MXZJN5jBj1se5jxSd/A93XGE2@tbsM66/5iR7cKQZ@o6K6zRjJVyjqmBoq@7VQ4z2KZCzo2edvQovB48mmJALKsV1Hg1f9qEn7XllGe7de5Bb5DlqVnvRMFLfBmXdg7diX5d8Ut0RZUzq2J/o9DK7DX1vmxW794wqqTveqL9VlEe8WjUU7lqMJdIqCBvgRzGMm41KY3z@T8) @ovs' brute force attempt is probably the optimal way to solve this problem, and Python is needless to say not going to compete with that Unicode soup, but I still felt like trying my hand at writing a more elegant solution than the brute-force approach, and this is what I came up with. If this inspires anyone to try a similar solution in another language, please go ahead, I'd love to see how short this approach can really get in the right language, and if it can compete much with the brute-force solution. Edit -4 bytes: Just realized I can declare the empty dict at the start with `{}` instead of `dict()`, knew I missed *something* golfing this down last night. Edit -27 bytes: golfed down conditionals, also function returns `True`/`False` instead of `1`/`0` now. Edit -53 bytes: I can't believe I forgot you can still use `;` to put multiple lines on one line and save whitespace, also the amount of bytes you can squeeze out of logical expressions in this language is insane, so remember that if your expressions are readable, you haven't golfed them enough. Edit -13 bytes: Golfed the `.remove()`s down to `-={}`s, and golfed off another 2 by removing the l=len from the top, as it wasn't saving bytes anymore, and golfed another 1 byte by changing it from accepting glyphs starting with `0` to glyphs starting with `1`, turning `G=[-1]*5` into `G=[0]*5`. I'm pretty sure this is as golfed down as I can get this program, but I could well have missed something. Edit -5 bytes: I think I've wrapped my head around that dang walrus operator now. Edit -11 bytes all thanks to @MarcMush's idea to use a `zip()`. Edit -24 bytes: Wow I didn't think I'd get this thing under 300! Shaved off a few with a better `return`, and finally found a better solution to having to check if a glyph is already in the yellow dict before adding its index. ## Ungolfed code and explanation ``` def wordle(guesses): green = [0,0,0,0,0] ## list tracking what we know of the solution vacant = {0,1,2,3,4} ## set of the slots we havent found yet yellow = dict() ## dict mapping each yellow glyph to the set of locations it was yellow at for guess in guesses: ## iterate through each guess made for i in range(5): ## for each glyph: glyph = guess[0][i] color = guess[1][i] if color==1 and i in vacant: ## if its green, set green and mark as found green[i] = glyph vacant.remove(i) elif color==-1: ## if its yellow, add it to the dict if glyph not in yellow: yellow[glyph]={i} ## add the set if not already there else: yellow[glyph].add(i) ## or add it to the set while True: ## loop until we get a solution newyellow=dict(yellow) ## copy yellow so we can modify it for i in yellow: ## loop over each yellow glyph difference=vacant-yellow[i] ## find the vacant slots it could fit in length=len(difference) if length==0: ## no vacant slots, this yellow has been placed somewhere already del newyellow[i] elif length==1 and green.count(i)==0: ## one slot and hasnt been placed in a slot yet j=difference.pop() vacant.remove(j) ## no longer vacant green[j]=i ## add it to green if yellow==newyellow: ## we did nothing this loop, we have a result return len(vacant) == 0 ## if vacant is empty, we've solved it, otherwise its unsolvable yellow=newyellow ``` [Answer] # Python3, 362 bytes: ``` R=range F=lambda t:{x for y in t for x in t[y]} def f(b): d={},{},{} for x,y in b: for i in R(5):d[y[i]][x[i]]=d[y[i]].get(x[i],[])+[i] [d[1].pop(i,0)for i in d[0]] while 1: if not(Y:=d[1]):return F(G:=d[0])&F(B:=d[2])==F(B)and len(F(G))==5 if not(k:=[(i,g)for i in Y if len(g:=({*R(5)}-F(G:=d[0])-{*Y[i]}))==1]):return 0 for x,y in k:G[x]=y;del Y[x] ``` [Try it online!](https://tio.run/##bVNNb6MwED2vf8Uoh8VOaMRHIAkrXzg0tz30hly0IgJSVALIISpRlN@eHRsatl1khMfvzbyZscbNpX2rK3fTyPv9hcukOmTkmZfJcZ8m0AbXDvJawgWKClptdtoUl/hG0iyHnO5ZQCDl15upP9J7mTpkj5Q@F@r0Qj0WpOIiijgWnfrz4bQ8ZC1ViClitsCdgEiFHS@buqGFabGHRiqsGNmPt6LMwFbyRQ5V3dIo4CqCBTJrz7KCZ7pTiBWzn880VKYTM87RZkmVQplVFF0YQt4o8h5wgfkOY75IUcr5EHB6nasWbk@j9tN1HmG5N6XzT3JraHu4hvdgJ7qYX36lWQkRmvfi2NSyBZmRE5/NZsSDFbjggE12MCyi8JOtaBsZFz08EmFBmtWk850MkQohJD6sYQNbrANPfYgOcL8GhDpA5RoDdr0EhDpgpavbor@L/EqzugbSq3jgk1AjKq0O8VSIo1nVT18x/skKbMTsRxcK81FB1WJbJBzAPrGvE9swLBJ@vZb190Y@WRt8LHQNW93c2Mjm/3vUS5PbT1LTY5OKVEPe1n/2dSJTmuKs/5DAQczzomwzSX/XVWZCujw1ZdFS47UyGIvRp58DIcT8mOAIV60JEgdl8EMfc2Rktjyd9xj8sTBMGN5eF1yNnREYlmEaEe427iHujnET3fIg63NDUUWpLnDyRuF4fHD6OVPL1AMsmQkO1kYaiUlpTh9dnRhjE6g9DTvTsDsNr6Zhbxr2p@H1NLyZhrcI3/8C) ]
[Question] [ More advanced version of [this](https://codegolf.stackexchange.com/questions/67646/chain-reaction-of-bombs) The aim of this puzzle is to simulate the impact of the shock wave of bombs on a square grid. The grid initially contains cells labelled `0` along with several bombs of type `A`, `H`, or `B`. Display the greatest intensity of shockwaves felt at each cell after the bombs explode. The three bombs have different explosion patterns. Consider the following generic configuration, where the `X` will be replaced by the different types of bombs. Note that for each bomb, the bomb's location is not replaced by a number. ``` 000000000 000000000 000000000 000000000 0000X0000 000000000 000000000 000000000 000000000 ``` For the `A`-bomb: ``` 000000000 011111110 012222210 012333210 0123A3210 012333210 012222210 011111110 000000000 ``` For the `H`-bomb: ``` 000000000 055555550 055555550 055555550 0555H5550 055555550 055555550 055555550 000000000 ``` For the `B`-bomb: ``` 000000000 000010000 000020000 000030000 0123B3210 000030000 000020000 000010000 000000000 ``` Unlike the other bombs, the `B`-bomb will not explode unless it is within the shockwave of another exploding bomb ## Input & Output * You are given an integer `n`, representing the grid size of `n*n` * You are then given the grid of `n*n` * You may take in the input as a list of `n` lines * Output the shock waves of all bombs * You may output as a matrix/list/array ## Test cases ``` 1 H -> H 15 000000000000000 A00A0000000000A 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 0000000A0000000 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 A000000000000AA -> 333332100001233 A33A3210000123A 333332100001233 222222100001222 111111100001111 000011111110000 000012222210000 000012333210000 0000123A3210000 000012333210000 000012222210000 111111111111111 222100000012222 332100000012333 A321000000123AA 18 000000000000000000 0AAAA00000000AAAA0 000000000000000000 000000000000000000 000000000000000000 000000000000000000 AA0000000000000000 000000000000000000 000000000000000000 000000000000000000 00000000000000A000 000000000000000000 000000000000000000 00000A000000000000 000000000000000000 000000000000000000 00000000000000000A A00A000A0000A00000 -> 333333210012333333 3AAAA32100123AAAA3 333333210012333333 222222210012222222 222211110011111111 333210000000000000 AA3210000000000000 333210000001111111 222210000001222221 111110000001233321 00111111100123A321 001222221001233321 001233321001222221 00123A321001111111 111233321111111222 222222222222222233 33333233322333223A A33A323A3223A32233 18 H00000000000000000 000000000000000H00 000000000000000000 00000000H000000000 000000000000000000 000000000000000000 000000000000000000 000000HH0000000000 000000000000000000 000000000000000000 000000000000000H00 000000000000000000 000000000000000000 000000000000000000 HHH00000000H000000 000000000000000000 000000000000000000 000000000000000000 -> H55505555555555555 555505555555555H55 555505555555555555 55550555H555555555 000555555555555555 000555555555000000 000555555555000000 000555HH5550555555 000555555550555555 000555555550555555 000555555550555H55 555555005555555555 555555005555555555 555555005555555555 HHH55500555H555000 555555005555555000 555555005555555000 555555005555555000 22 000000000000000000000A 00000B0000000000000000 0000000000000000000000 0B0000000000000000000B 000000000000000000B000 0000000000000000000000 000000000000000000000B 0000000000000000000000 000000B00000000A000000 000000000000000000000B 0000000000000000000000 000000B000000000000000 000000000000000000000B 0000000000000000000000 000000000H000000000000 000000000000000000000B 0000000000000000000000 A000000000000000000000 A00000000000B000000000 A000000000000000000000 HHHH00000000000000A00H 00000000A0000000000000 -> 000000000000000000123A 00000B0000000000001233 0000000000000000001223 0B0000000000000000123B 000000000000000000B003 0000001000001111111003 000000200000122222123B 0000003000001233321003 000123B32100123A321003 000000300000123332123B 0000003000001222221003 000123B555555111111003 000000555555500000123B 0000005555555000000003 111100555H555000000003 222100555555500000123B 3321005555555000000003 A555555555555001115555 A55555511111B001225555 A555555222210001235555 HHHH55533321000123A55H 55555553A3210001235555 10 0000000000 0A00000000 0000000000 000B00B000 0000000000 000B00B00B 0000000000 0B00B00000 0000000000 0000000000 -> 3332101000 3A32102000 3333103001 223B33B322 1113103003 123B33B33B 0003003003 0B02B02002 0001001001 0000000000 ``` ## Others ¤ The place may already have felt the effect of other bombs before the grid bombs exploded. In this case the number of the cell will be different from `0` as soon as the grid is given ¤ There are only three types of bomb: `A`, `B`, `H` ¤ There may be no explosion ¤ For overlapping of bomb explosions, please note that the highest intensity will outshine the lower intensity shock waves. E.g. a shockwave of `3` emitted by the `A`-bomb, will be replaced by a `5` if there is a `H`-bomb nearby ¤ For the order of checking the bombs, you can do a left to right, top to bottom checking system for easy checking (the 4th rule ensures overlapping will not cause any problems) ## Scoring This is code-golf, you know the rules ;) ## Credits Credits to [this puzzle](https://www.codingame.com/ide/puzzle/sweet-spot) [Answer] # Java 10, ~~312~~ ~~310~~ ~~308~~ 307 bytes ``` n->m->{for(int i=n*n,b;i-->0;)if((b=m[i/n][i%n])>57)e(m,i/n,i%n,b);}int e(char[][]m,int x,int y,int b){for(int j=-4,k,u,r,X,Y;++j<4;m[x][y]*=b/~-b)for(k=-4;++k<4;)try{u=m[X=x-j][Y=y-k];r=b>67?53:52-Math.max(j<0?-j:j,k<0?-k:k);m[X][Y]+=b==j*k|b%7==2?u>r?u==66?e(m,X,Y,0):0:r-u:0;}finally{continue;}return 0;} ``` -2 bytes thanks to *@Neil*. -1 byte thanks to *@ceilingcat*. Input as a matrix of characters, and it modifies it directly. Also takes the dimension `n` as additional input, since it's shorter. [Try it online.](https://tio.run/##7Vhbb5swFH7vr7AiVcINUNQ1rRRiIlNpog/VJvWlFeIBUtKai4Mc0wVl2V/PTEqWVM2AJahNqvnBcXw@n/Odi43lwH12leAhnA8idzwGNy6h0yMAAjGtppxE6jClA05GVP1aDHrXlPuPPpM3ga5GdJzGPusNnlxmO7ZjGGAI0JwqRqwY0@GISYRyQBA9obKnE0UxNB2SoSR5KLbJKXVsckwdaHQuoS/FspiRxYTsQX2m5yt9aalZCMX/yaLPFr0H/xgIkHIuh3IqM/lOvtfb7aB3rsf2xLEz5wR5p78UD@bYUOCENBRSyFk2TQWLOzRRAse@R5kSOjpDnnFx2e986XbOlBuXP6mxO5GCntZXgm4gh/kg7IZQaL8Ti5w28hAKTsKf3vElQmf91GD9FKGLi37ujyAja7CrdZmSdjV9NiTUjaJsOhhRTmjq6zPm85RRIGRzAJLUi8gAjLnLxc/ziDyAWGRIuuWM0EfbcWGeLAC4P@YS9X@AZXBepgFoacvWUvnoSkgxY24mQfmdAXgPOGwCLOQzqB9IGK3/YWwCYH6SMJZbwcW2e2m4kkxNzgcPw5/fU7wOwriRMitjhUVbmRPjmvzre/rOSIwPg@drFP4I63hvooQrTkK8orvdjrC25WY16a91EDVpWXtRFda@RslaBcjaw2xu/Y2ovGqY23MsRZsbwGZ93WZzTLTdmFTrNrXXV5k9YPLhMXl1MH4QE7w12mxYt2VZ1pu7gVXlJW70RPj7bbF@jkoQZt09W6nD3EGHuczdTjx2inie67I6aEhWlw0uqcoymflPsvrVWBL2@qI1c7Mj0a0/yS2sLy2DuHiTu83G3I/VUcrVhBHKIyq1rmmS8i5oFbQT5nOefc@lUlzM5V7kr7ASVIeqmyRRJsVq5NNH/gRVdzDwkxV2k4lvKa@0sWHdZs/WF79xcPWYq@mA9JYsxbjdhkUkN1jKHXx5v5RimziwsDyb/wY) **Explanation:** ``` n->m->{ // Method with integer & character-matrix parameters for(int i=n*n,b;i-->0;)// Loop `i` over all cells in the range (n²,0]: if((b=m[i/n][i%n]) // Save the current cell's value in `b` >57) // If `b` is a bomb: e(m,i/n,i%n,b);} // Explode it with the method below // Separated recursive method to explode a bomb // Takes the matrix, current x,y, and `b` as parameters (and always returns 0) int e(char[][]m,int x,int y,int b){ for(int j=-4,k,u,r,X,Y;++j<4; // Loop `j` in the range (-4,4): m[x][y]*=b/~-b) // If the current cell is an exploding B-bomb: // Remove the B-bomb so we know it's exploded // Else: // Keep the cell's value unchanged for(k=-4;++k<4;) // Inner loop `k` in the range (-4,4) as well: try{u=m[X=x-j] // Set `X` to x-j [Y=y-k] // Set `Y` to y-k ; // Set `u` to the value at cell X,Y r=b>67? // If we're exploding an H-bomb: 53 // Set `r` to 53 (unicode value for 5) : // Else: 52- // Set `r` to 52, subtracted by: Math.max( // The max of: j<0?-j:j, // The absolute value of `j` k<0?-k:k); // and the absolute value of `k` m[X][Y]+= // Change the value at cell X,Y to: b==j*k // If we're exploding a B-bomb // and either `j` or `k` is 0 // (which means X,Y shares a row/column with x,y) | // OR b%7==2? // We're exploding an A- or H-bomb: u>r? // If the current value `u` is larger than `r`: u==66? // If `u` is a B-bomb that has yet to explode: e(m,X,Y,0) // Do a recursive call with `b`=0 to explode it :0 // And keep the current cell's value unchanged : // Else (`u` is smaller than `r`): r-u // Change the current cell's value to `r` : // Else (it's an already exploded B-bomb or digit): 0; // Keep the current cell's value unchanged }finally{continue;}// Catch and ignore ArrayIndexOutOfBoundsExceptions // (which is shorter than manual in-bounds checks) return 0;} // Always return 0 ``` [Answer] # JavaScript (ES7), 180 bytes Modifies the input matrix. ``` f=(m,X,Y,t)=>m.map((r,y)=>r.map((c,x)=>t?(d=4-((h=(x-X)**2)>(v=(y-Y)**2)?h:v)**.5)>0?(n=t==b?h*v?0:d:t<b?d:5)?r[c==b&&f(m,x,y,c,r[x]=f),x]=c<n?n:c:0:0:1/c||c==b||f(m,x,y,c)),b='B') ``` [Try it online!](https://tio.run/##tVNPU@MgHL3zKRgPBipF1tFLlGZgZh3uXnRaDylJbJyEdEm20471s3dpdDfGZqxuKswA7/F4/H78eQwXYaltOq@GpojizSbhKCe35I5UmI9ymodzhCxZOWBfgCZLB6oARfx8iNCMo@XwFg8GZ3iEFhythnc1CGb@wg3oBR6xABlecT4NZoNFwPzIr66mQeRf4MCOteOPjxO36ZKsiCZ2vLznCSau1VcmML72mas/TvV6vdWu1/@0GJMp96SHNzb@9Tu1MfKS0sPUxmF0nWbxzcpoxDCtipvKpuYBYVrOs7RCRxMzMUeYJoX9GeoZKiEfwScAYRZXMIcclo3QybZp15IxpbS8r7HeYtdw6DEPBpBBH7qALp2Ji6/udWHKIotpVjygvDEp6WORGuR5GL@OJsbD8ATW/SV4xhsFAGsXIBgTDRQ789@ExXf5i7dIiJ2E6zXClUbjxp2q/6WEOJxXG4ovLhSHCEL8fSOisQRA7V2pPvZXBzsdpfomqfoEoZr9Vd@EOrjmV8pPOLzQsoOVHWr5kQn7pMkbtWTt793PpE8krQf2dROxn5Z71UoptfN/FXh3Rh1XD5o50E5B7txZw0rw7gnILofX8gc "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 118 bytes ``` WS«FAHF⌕Aικ⊞υ⟦ⅉλκ⟧⟦ι⟧»Fυ«≔§ι⁰ζ≔§ι¹ε≔§ι²δF⁷F⁷¿¬∧∧⁻κ³⁻λ³⁼Bδ«J⁺ε⁻λ³⁺ζ⁻κ³¿⁼BKKF¬№υ⟦ⅉⅈB⟧⊞υ⟦ⅉⅈB⟧¿⁼KKIΣKK⎇⁼Hδ5⌈⟦KKI⁻⁴⌈↔⁻⟦κλ⟧³ ``` [Try it online!](https://tio.run/##rZFdT4MwFIav4Vc0XLUJJvMrXnhVFg0zmSHZLjSECxx1a9aVSanOmf12PC37khFnMptA6Xnf8/Scw2iSFqM8FVX1MeGCIdyTc10OyoLLMSYEfbnOa14g7NHQI8h@3nOZUSEw99EUHJFWE6x9FD9j4iMBwYTcuk4EhBLH3BxWrk3UFkeV4mOJadmTGVsYSgfylibnUDoHibVLFyBlRrLsm3VxsPNXhB/zElOZ2afPpVZ46qNLyKgPwhzgdPemU6GwF3iGRep@nQc9mw9zHAlwsmaKjS43UUslpgrHXLvPixibYoO0dZmCurmGkWxH9WReYE3IwRR3kiEzoRjaw9dkH3VTVeKBnuHNVYZjxz5khUyLz209oe0PkNfw0U8XfAZZ8Q9O3c/VTqYvKhe6ZGslhlZFUrdLSFI3vXJXVdVpW9S1W9CMu61uCAct0aDFHfwG6fwRsufe3kv/A3JKJbDCEyD0eDg46g5hNX4kVOU2ZrRxV2fv4hs "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: ``` WS« ``` Loop over the rows of the grid. ``` FAHF⌕Aικ⊞υ⟦ⅉλκ⟧ ``` Collect the positions of the `A`s and `H`s. ``` ⟦ι⟧ ``` Print the row to the canvas on its own line. ``` »Fυ« ``` Loop over the positions of the letters. ``` ≔§ι⁰ζ≔§ι¹ε≔§ι²δ ``` Extract the current position and letter. ``` F⁷F⁷ ``` Process a square of size `7` centred on the current position. ``` ¿¬∧∧⁻κ³⁻λ³⁼Bδ« ``` Skip this cell if the current letter is `B` and the cell isn't orthogonal to the current position. ``` J⁺ε⁻λ³⁺ζ⁻κ³ ``` Jump to the cell. ``` ¿⁼BKKF¬№υ⟦ⅉⅈB⟧⊞υ⟦ⅉⅈB⟧ ``` If this cell is a `B` that hasn't been seen before then add it to the list of letter positions. ``` ¿⁼KKIΣKK⎇⁼Hδ5⌈⟦KKI⁻⁴⌈↔⁻⟦κλ⟧³ ``` If this cell is a digit then calculate the shock wave and update the cell if it is greater than its current value. [Answer] # Python3, 747 bytes: ``` from math import* R=range L=len p={'A':(k:=[3,2,1],1),'H':([5]*3,1),'B':(k,0)} g=lambda x,i:[j[i] for j in x] m=lambda x,y,X,Y:max(map(abs,[X-x,Y-y])) def u(b,x,y,l,r,o,Q,i=0,H=0): if i and(j:=b[x][y])not in p and int(j)<l[(P:=m(*o[0],x,y)-1)]:b[x][y]=l[P] if i and j=='B' and m(*o[0],x,y)-1 < 3:Q.append((x,y)) for q,w in[(0,1),(1,0),(0,-1),(-1,0)]: if(X:=x+q)>=0 and(Y:=y+w)>=0 and (X,Y)not in o and(r or 1 in[L(set(g(O:=o+[(X,Y)],0))),L(set(g(O,1)))]): try: if(K:=dist(o[0],(X,Y)))>=H:u(b,X,Y,l,r,o+[(X,Y)],Q,1,K) except:1 def f(b): Q,S=[],[] for x in R(L(b)): for y in R(L(b[0])): if(E:=b[x][y])in['A','H']:u(b,x,y,*p[E],[(x,y)],Q) while Q: S+=Q;q=[] for i in Q:u(b,*i,*p['B'],[i],q) Q=[j for j in q if j not in S] ``` [Try it online!](https://tio.run/##tVfrb@M2DP98@iuEfomcqoUfCDB4pwEycICAK7bL9UsLzxicxWmdJbHr@NAEw/72jpQfkpOs7a09IQ@RIn@kSOpV7uv7YhP8VFZPT4uqWNN1Wt/TfF0WVT0mX0WVbu4yciVW2YaU4u@RHIXsr1DEAfe5l3DP4SMFrHiSjANNRSjAXecfcidW6Xo2T@mO52G8jPOELoqKLmm@obuErM3wnt/w23Cd7tg6LVk62/L45mLHby/2ieOQebag39iMo9yKV7zgU54LlyvhOiGh@YLmNN3M2TIUs3iXxKC0KWq0UiIfOjVbOh9XMfsSijUbF7GbIJhz4TlJ2KqIVfwlMWB0KQRMRXeHKvQjDcLpZVqWGdhkyHSIntgDfwRbMXMxDsyDGHDoXyBxgVQCzoIBdhOK3fmD84twtdu3odifP3YkZRCKzv9CC1QUwD2EvmLbrGZ37LdQFOexlkwA2HF4PwK2HSfBuFBaV3v9j0Y/h2Keb2umZ6I1HTCpQgwsUE1ge8wp9/hnB3Wz3Z9ZWYeezsKCzRB5yq9FnPA4aea9Q1e/sisY1HaRt@95YK9hoxefTIpgOlBMWD1J2GV3XMafAFcHFZwABx7v81VGp6h/fS6mPz8ItKpN5GhiqnXHOapCvkA5T/gDej4V8dLU2wNmdknbuF4nT3W2rbdU0Dg@OztT8OUUXeEEaXfYiHRdaUhJDsd/EC1/FL60KSlx9vANsPke8jw/CIgMAmloSQ7Hfd1a2veJ1zRNQyNdp@WRTrDVIR1QMKRl8Oy40feGjXQDrRTpFFsUIm1az/p0urUtCc1ECPrklNT/ZUn5flhDUn6nonwPJ2S3QqSBtItKB14nAfMQYDw7lu6TE1J@X15e29Wsppr6nAcmySa2RyxLyiqWQbX4HukrtS87YhVwW5nEqkFLyu/db7CsSu4swreRalo3IbsFbSS0XPsj23WI3/YnMKWrXsyOej6H6t0qUKm3FpJ6ixPK2FdvnFBbumoymbgTu5HJkKWOWbaUMixAnQzbgGVcOc1Sli@21OtZnasIfODqyyzV2O/mhH4dSL2a9dyua87W6BVZatjRCW50Qjp6DsR9JYglHbnDQ/ptIG/xZLCIvx9EvsyOXpRWSqmjc0iRgxgNl9cxjL5lHAdGXzZOSfvBifyD9H/kvwPx3MHNpGP79mFgQAJ3cA/R0jjcH2CGfSh9DNIeHD1IsywOPbF3AAtksDGgdKNlFmXLbmwcgTT@H4FIe1PSYdFLXlquRdp1m92dngDcbRDoQ3fOYljAq3b5T7orXSutt4DhDkBMiZBhJUdHS9dwI3KwE0SnEIZV17jo6VuBdstvLwiBh1nCiwHkFtOrL7QNF0LdcptkBM0HbfoRIvikqSv8DG0miX451cUfsyKt5mwOb6EPVVZ/qzY0XuGLLHf618wiX9VZxX4tNhmfX27LVV6z0e@bEbzoCEGplNMZCurXCwBpTHjF9PCpQz7AKw370Eu326yqKau8UCDO5bLIN2zU/uNbe1tXPHeMB42mQ4Wgs6d/AQ) [Answer] # Python 3.8, 457 bytes ``` import itertools as t g={} b={} R=range(int(input())) for i in R: for j,v in enumerate(input()): g[i,j]=v if v in"AH":b[i,j]=v def d(i,j,v): g[i,j]=v.lower() for x,y in t.product(range(-3,4),repeat=2): if x==y==0 or v=="B"and x*y!=0:continue if(o:=(i+x,j+y))in g: if"B"==g[o]:d(*o,"B") if g[o].isdigit():g[o]=max("5"if v=="H"else str(4-max(abs(x),abs(y))),g[o]) for i,j in b:d(i,j,b[i,j]) for i in R:print("".join(g[i,j].upper()for j in R)) ``` [Try it online!](https://tio.run/##bVCxboMwEN35CteTnTiINqlUId2QTJmzRhkgONQosS1jKKjqt1MfJGmj1sLm3t07P9@zvX83evlm3TCoizXOE@Wl88aca5LVxEclfH5FOR47cJkuJVPah20bzzjn0ck4oojSZJdGBEElWoRSNxfpMi/v3FAn5V6J6gBtCNWJIJGutzTNb@lCnkjBAhAt8m/0@Gw@pGN8UuhEjwo@ts4UzdGz6V2LpVhx4aSVmYeXUS5odAA9QEJCXwtANzTTBelm/RMk6dFor3QjRyYzKTA170Q17zkP95d4QyiEHoBybw5pwWZGBMinAsFkrOpClSoMmCKES9Yx@kpxuiC3pfJcS1J7x1YLLGV5zTou8BdUuMCeq4miwqnydJp/suTBX@vQekrjyijNJm/ixlp0ZnR@pHE@DM9JlNxXlKx/wuR3uBm//7Obh@yV@Yd7Xd8) ]
[Question] [ I'm not sure if this kind of golf is allowed, but here it is. Your objective is to create an image containing one pixel of every possible RGB color. The image with the smallest file size wins. Rules: * The image must be a PNG. * The image must contain *exactly* one of every possible RGB color. * Acceptable image dimensions are: ``` 1x16777216 2x8388608 4x4194304 8x2097152 16x1048576 32x524288 64x262144 128x131072 256x65536 512x32768 1024x16384 2048x8192 4096x4096 8192x2048 16384x1024 32768x512 65536x256 131072x128 262144x64 524288x32 1048576x16 2097152x8 4194304x4 8388608x2 16777216x1 ``` Example Image [![Example image](https://i.stack.imgur.com/etSTK.png)](https://i.stack.imgur.com/etSTK.png) [Answer] # ~~49683~~ ~~49280~~ 49131 bytes [![image](https://i.stack.imgur.com/hPcJr.png)](https://i.stack.imgur.com/hPcJr.png) Generated by this Python code. I designed the PNG scanlines by hand to be encoded using repetitions of short sequences that compress well. I’ve now written enough of a custom DEFLATE encoder to let me decide where to split the compressed blocks (saving 149 bytes compared to zlib). ``` import itertools import struct import zlib def lsb(b, n): assert 0 <= n < 1 << b return f"{n:0{b}b}"[::-1] if b else "" def huffman(lengths, letter): code = sum( 1 << lengths[letter] - length for other_letter, length in lengths.items() if (length, other_letter) < (lengths[letter], letter) ) return f"{code:0{lengths[letter]}b}" def literal(letter): assert 0 <= letter < 256 return huffman(literals, letter) def end(): return huffman(literals, 256) def match(length, distance): assert 3 <= length <= 258 assert 1 <= distance <= 32768 if length == 258: bits = huffman(literals, 285) else: i = max(0, (length - 3).bit_length() - 3) bits = huffman(literals, 4 * i + 257 + (length - 3 >> i)) + lsb( i, length - 3 & ~(~0 << i) ) j = max(0, (distance - 1).bit_length() - 2) bits += huffman(distances, 2 * j + (distance - 1 >> j)) + lsb( j, distance - 1 & ~(~0 << j) ) return bits code_length_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] def encode_lengths(): hlit = max(literals) + 1 - 257 hdist = max(distances) + 1 - 1 hclen = max(map(code_length_order.index, code_lengths)) + 1 - 4 bits = lsb(5, hlit) + lsb(5, hdist) + lsb(4, hclen) for i in code_length_order[: hclen + 4]: bits += lsb(3, code_lengths.get(i, 0)) for length, group in itertools.groupby( [literals.get(i, 0) for i in range(hlit + 257)] + [distances.get(i, 0) for i in range(hdist + 1)], lambda length: length, ): n = len(list(group)) while length == 0 and 18 in code_lengths and n >= 11: bits += huffman(code_lengths, 18) + lsb(7, min(n - 11, 127)) n -= min(n - 11, 127) + 11 while length == 0 and 17 in code_lengths and n >= 3: bits += huffman(code_lengths, 17) + lsb(3, min(n - 3, 7)) n -= min(n - 3, 7) + 3 # not implemented: 16 (copy previous code) bits += huffman(code_lengths, length) * n return bits png_header = struct.pack( "!IIBBBBB", 2 ** 16, # width 2 ** 8, # height 8, # bit depth 2, # color type 0, # compression method 0, # filter method 0, # interlace method ) zlib_header = struct.pack( "!BB", 8 | 7 << 4, # compression method, compression info 26 | 0 << 5 | 3 << 6, # check bits, preset dictionary, compression level ) literals = {1: 2, 2: 4, 256: 4, 268: 4, 284: 4, 285: 1} distances = {2: 1, 18: 1} code_lengths = {0: 3, 1: 2, 2: 3, 4: 2, 18: 2} bits = "0" # start non-final block bits += lsb(2, 2) # compressed with dynamic Huffman codes bits += encode_lengths() bits += literal(1) + literal(1) + literal(1) + literal(2) + literal(1) + literal(2) bits += 2 * match(258, 3) bits += match(248, 3) bits += 5 * ( match(258, 768) + match(258, 3) + 42 * (match(258, 768) + 2 * match(258, 3)) ) bits += match(258, 768) + match(258, 3) + 39 * (match(258, 768) + 2 * match(258, 3)) bits += match(17, 3) bits += end() literals = {1: 3, 256: 3, 264: 3, 279: 3, 285: 1} distances = {0: 1, 2: 1} code_lengths = {0: 3, 1: 2, 3: 2, 17: 3, 18: 2} bits += "1" # start final block bits += lsb(2, 2) # compressed with dynamic Huffman codes bits += encode_lengths() bits += 96780 * match(258, 1) bits += match(105, 1) bits += literal(1) + literal(1) bits += 762 * match(258, 3) bits += match(10, 3) bits += 96780 * match(258, 1) bits += match(102, 1) bits += end() bits += -len(bits) % 8 * "0" compressed = int(bits[::-1], 2).to_bytes((len(bits) + 7) // 8, "little") decompressed = zlib.decompress(compressed, wbits=-15) assert decompressed == bytes( [1, *(2 ** 8) * [1, 1, 2, *(2 ** 8 - 1) * [1, 2, 2]]] + (2 ** 7 - 1) * [2, *2 ** 16 * [2, 2, 2]] + [2, *2 ** 16 * [2, 1, 1]] + (2 ** 7 - 1) * [2, *2 ** 16 * [2, 2, 2]] ) zlib_checksum = struct.pack("!I", zlib.adler32(decompressed)) png_data = zlib_header + compressed + zlib_checksum png = b"\x89PNG\r\n\x1a\n" for type, data in [(b"IHDR", png_header), (b"IDAT", png_data), (b"IEND", b"")]: crc = 0xFFFFFFFF for byte in type + data: crc ^= byte for bit in range(8): crc = 0xEDB88320 * (crc & 1) ^ crc >> 1 crc ^= 0xFFFFFFFF png += struct.pack("!I4s", len(data), type) + data + struct.pack("!I", crc) print(len(png)) with open("rgb.png", "wb") as f: f.write(png) ``` [Try it online!](https://tio.run/##vVhZb9tGEH7nr9iyaLBr0Ywo6rJgBWjgtDFQBEHRN1kxSHEl0SGXBEnFVlznr6cze/CQfCQvNRKTOzvHN8fODp3vq20m/O/f4zTPiorEFS@qLEtKSxPKqtitKrP6msShZVkRX5OkDGnoEMFmFoGfoCxBkvTJ@ZwIck48cn5OQrlV8GpXCLK278Wsfx8@hA/2YjY79ZYkXpOQ8KTkxLa12u1uvU4DQRMuNtW2dEjCK8CkrayyiJM5KXcplWv8kZY0@0JxL8mpptRc66wgWbXlxbVicTQDiYURdsH5tKSslgF4GofTkWXgHz2wWAOV0uzAccQNvh/IYCRMNDHwQUI73rZjqjbA8GA0biuv46UUNAHTirmIqFb3pASoNOxpUK22tdNRXFaBWPEuHl/hkdGDt8Fo2t71kGYE8d0fTMZTy9IB1XJzKTerQx3GVQmJfQTbdKSCiWXS8MfAnAZ3tO@YTEDKfeaCnmu1pkxSXrYwJCegrgd4JvC7pY28eUNixoCItV4rkubr8kG@V@Qb/dbHMowbe0y5fNMCWkfllHhHUAdKVMLsNTiNDIYCgN4gxLYeBHlzDPKmSZ7kaiDemApt1wRahQrAMtWYrrMignqbk4U3dog3gf9Th4AX8BsWZw5BMqxH8PAgivAYOMSHB/yHNw8p8G@0rCuxpb40RbmFROgQmZSgMx5GZDRRLOiJ5qnDYZg8xbICtZolDXJ65Igbi4jfOaQNgRkdQ6tVIBhG8AlxmajiEg2bNXgmDapIYmeJsY0cGV3MNLAeGS4Par2nLPldSO6GVxSKq88a3eYwbopsl6Oduke7khTum7QvTAwbRQ2@IhAbTmXAZbWzZS3XI4s6ss@IykRAzNjSqUWTIA2jQKOcGbSqxhqfMTmwBTkuKyphs@ao3G7jhLc6Q58EIoJ6OwhqKcmCvJlDxc065/Hw1LSlsHJN5qBy01hQgYWDxTmYtGAonKfzIxZ02XsJ7eRptP5PgZ0YsH4DFl6fRSr3QcyvWX4lIoPrPM0TnnJR8WhGvDEBW/me5AX/Eme7UsJl1o/hUi8MepB4pHPkYnO95YFqGWpmcPNg9VmVpv3L5eVb/LFVYUAnOyHYVwDmbRzpa1pSp5K45fFmW0mqIoAZEvHccEraKkugPqt9ziWxr4kpuFeWcSZIymG4iVqb6zjBS/SIHkOAiiSAXqm3oDviqPOsS7U3U/IvmWBrHT6BwOnQYrHOlBdjEJQ9eQQvPr6okKy2fPVZRtbBXJUcfI9XFQgHxb6rLOFfeIJwzcEHrPfeDCM0mCEguNvVczxVz@lQP0dQEQ9WfexREESw5Kdyp1PLsNmfye5udMP7UL4j@@DB0u3T7tvoAiiFWUBk4nQdiyAhYZKtPlvtzodaWDtePIJagCMV7UWQxivyXpWhLNKyFj28RRqdeoLy5PF5cTF4ZqfWiTeumohgWHFwmjA7mjrsUkfAr8qjJQXTD6rv6MEbAZXTY74jm8w6MvuMWv/sh9V2leIV33JFzo1HZeXrgsLneKiekzP1fKyg@rKgBi/Wk68qaaJIrYICJLbXqqj/q5rOxpNpvxsy7yhi/VGH@kTR1fuT8Uv1hPOU/7MgBh2qzptZnuKliwtGfoNGdYLn02rFaI69TzKoTzIMo1tl1@G@4iWljXQPL5jXr7Ed2@BblXCb4VzX0YU9021otNl0yC3qmZ96MM7rL4Wu8Jwom/L4LKBqTqi6EPDKwbUnx0pDlTO03sHkL5dqmoHxWDJMagYU0heOXip@zf7IPhr7eXXmzpDdG75QD24NuANtR0UoiBJe@APaDgCcR7xDo6AKdCDN5dNr13SPdGzIixf4Q/vqbnr28cOfV8WVuLrzgithW2t9O8KnAGqF8WRBQ/vy/cXfAKS5sBl8mQD54vd/NBm5NfHdhwsghrbN9Py6KlZgrn/3h/6pp1RMHppAg4ASdTRTD0p9UgnufJDjrV5Pl1PWHZOMqXcXb6dTf4AHgSLtFSbik9yGbx/Pahk4wIWx6R1lYVjacpqh2k9EzDRkeBznDJRDbvMCTwrKgVrIluwuWQ5ru9iELhCB1b4NbQZfwmStfFm7twU0Aili/sQidinMYMAjcvNnlY@Xf7mXabDhFlDgAX7XJLdroz49ktGFKEIfwNNjQ/ZtK4/vuOzWIneDogj2VPLVUmrfLbdBzhf9JcS0Q/GW8sscy3swlANsZ3sgt31oIDtRaStfeZGVVItAqWE450CHaPlwlSrWBdV6ghL3ab2PQ08NdbFYqA9MbwzHmTEX/84T3MXlHJrSOgmqCiLBlphTT@eDGihz/KQOkoQy9v0/ "Python 3 – Try It Online") (Note: many PNG readers accept an image missing the `IEND` chunk, but it is required by the [PNG specification](https://www.w3.org/TR/PNG/) so I have included it.) [Answer] # 256x65536, 49909 bytes [![enter image description here](https://i.stack.imgur.com/VVnvV.png)](https://i.stack.imgur.com/VVnvV.png) In my experience Google Chrome is the best tool to view this image. The red channel starts at 255 in the first row and decreases by 1 each row. The green channel slowly decreases from 255 to 0 in every row and the blue channel repeatly decreases from 255 to 0. Generated by the following code in [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/doc/stable/) and [imageio](https://imageio.readthedocs.io/en/stable/index.html): ``` import os import imageio import numpy as np FILENAME = 'out.png' DTYPE = np.uint8 values = np.arange(255, -1, -1, dtype=DTYPE) image = np.empty((256, 256**2, 3), dtype=DTYPE) image[..., 0] = values[:, np.newaxis] # r image[..., 1] = np.repeat(values, 256) # g image[..., 2] = np.tile(values, 256) # b # Verify that all colors are present (slow) # assert len(np.unique(image.reshape(256**3, 3), axis=0)) == 256 ** 3 imageio.imwrite(FILENAME, image) os.system('wc ' + FILENAME) ``` I tried to reduce the file size with [zopflipng](https://github.com/google/zopfli/blob/master/README.zopflipng), but even after 50 minutes of running it provided no improvement. ]
[Question] [ In the face of some regrettable rules that turned the [original](https://codegolf.stackexchange.com/q/209666/45613) into a glorified sorting task, I am posting a more challenging variant. Shout out to Luis Mendo for the suggestion of how to improve the original challenge. --- You've inherited a server that runs several apps which all output to the same log. Your task is to de-interleave the lines of the log file by source. Fortunately for you, the person who wrote all the apps was nice enough to leave tags indicating their source. ## Logs Each line will look something like this: ``` [app_name] Something horrible happened! ``` * App tags are always between square brackets and will contain only alphanumeric characters and underscores. * App tags are nonempty * There may be other square brackets later on any given line, but none will form a valid tag. * There will always be at least one non-space character after a tag. * The log as a whole may be empty. * There is no limit to how many unique app tags will be present in the file. In some cases, an app tag may be missing. When this is the case, the log line belongs to the most recently logged app. * The first line of the log will always begin with an app tag * A line beginning with `[` is not necessarily tagged. If there is an invalid character between the initial square brackets or no `]`, then the line is not tagged. * No empty lines appear in the log ## Expected Output You should output several fully-separated logs with the app tags removed from each log line where they were present. You do not need to preserve leading whitespace on any log line. Output logs must be in some sort of key-value mapping or reasonable equivalent. A non-exhaustive list of valid output formats: * A file named after the app tag for each app + You may assume that the output files do not already exist in the output directory in this case. * A dictionary/map/hash/whatever that uses app tags as keys and a newline-separated string of the log lines as values. * A long concatenated string separated by blank lines and preceded by app tags * A list of [key, value] lists * A JSON string with app tags as keys and arrays of log lines as values * A Markdown document with app tags as headers and leading `#`s of any line escaped with backslashes. * A Javascript function that takes a string as input and outputs the associated log as a newline-separated string. Basically, if you can't tell which app the log lines came from, the output is invalid. ## Example An entire log might look like this: ``` [weather] Current temp: 83F [barkeep] Fish enters bar Fish orders beer [stockmarket] PI +3.14 [PI announced merger with E] [barkeep] Fish leaves bar [weather] 40% chance of rain detected [ I have a lovely bunch of coconuts ``` Which should output three different logs: weather: ``` Current temp: 83F 40% chance of rain detected [ I have a lovely bunch of coconuts ``` barkeep: ``` Fish enters bar Fish orders beer Fish leaves bar ``` stockmarket: ``` PI +3.14 [PI announced merger with E] ``` You are not given the names of the app tags ahead of time. You must determine them only by analyzing the log file. ## Rules and Scoring * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. * Standard rules and loopholes apply * Use any convenient IO format, provided that each input line is represented as a string, not a pre-parsed tag + message. *Parsing is part of this challenge*. * Output log lines for each app must appear in the same order that they did in the original log. * You may assume that the input log contains only ASCII characters. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 95 bytes ``` import re lambda x:[((t:=re.match(r'\[(\w*)\]',s)or t)[1],s.split(t[0])[-1].strip())for s in x] ``` [Try it online!](https://tio.run/##DcrBCsIwDADQu1@R2xKZxeFFBn5JmkOnkxXWtaSBza/vfOdXfrbk7fEs2lpMJauBzpc1pOkT4BgZ0caXzi4Fey@onWf0@5W8dH2lrGDEg/TV1bJGQ@O7EN8GcdU0FiT6/k@FuMEhrZ0 "Python 3.8 (pre-release) – Try It Online") [(Expanded TIO example with input)](https://tio.run/##bVA9b8IwEN3zK26pYrc0AtEBITFVRWLrbqzKOJfaIrGt84WPX58aGFg63vu4d/fSlV0My1WiafJDisRAWHWwgd4Mh9bAZa2E4PWGsBkMWyeo3iuxP7/Kva5nWUYClmqhZ7nJqfcsWM21VO8L3WQmn4SUXdFk8AEuuqp8SCP/9D5zyVAV1OqMhh2Shs@RCAMD45DWsFpu69mNPxg6IiYNW58dFAFShgLe2TsWqb1jiA9QZY72ONx8rOF7B2/LZvHxoMpkQohjsNjCgPSLBGfPDr70f3E9mhM@457HfsxfwDpT1kDsgEx5r0VGy9g@lLADV7xgoI8n7K9wKJnuJrbRxjByrksdiXxg0YlnLVJO0x8 "Python 3.8 (pre-release) – Try It Online") ### Explanation: Python 3.8 is required for the `:=` operator. This takes a list of strings as input, and outputs a list of `(tag, body)` tuples. First, it uses a Regex match to get the tag: ``` t:=re.match(r'\[(\w*)\]',s)or t) ``` This matches any initial sequence of word characters (alphanumeric + underscore) enclosed in square brackets, with the words as a capturing group. If the string does match this regex, `t` will be a `match` object with two elements: the full match and the group. For example, if the string is `[tag] body`, the `match` will have the elements `[tag]` and `tag`. If the string does not match this regex, then `re.match()` returns None. The code becomes `t = None or t`, which is just `t = t`, so the tag keeps its value from the previous line. If the first line didn't have a match, this would cause an error, but we don't need to worry about that! The code then constructs the tuple `t[1], s.split(t[0])[-1].strip()`, where `t[1]` is the capturing group (the tag without square brackets) and `t[0]` is the tag *with* square brackets. Splitting the string on the full tag isolates the body, whether or not the tag actually exists in the string. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 95 bytes ``` +m`^(\[\w+] ).*¶(?!\[\w+]) $&$1 O$`(\w+).* $1 ¶ ¶¶ rm`(?<=^\1.*¶)¶(.\w+].) (?<=(^|¶¶).\w+]). ¶ ``` [Try it online!](https://tio.run/##XY5NasMwEIX3OsUU3GLVYGqSRSktWZQGsmr3/sGKPK1MbCmM5ZhCz5UD5GLuyFkUCmLQe/O@mSH0rVXznPR1FRd5MSUlyPT@co43N1cpRXQXZeI9qmOW3BOsLmd@XKiv483zS1VkgZGMpYFJpRDBj6ufEJOLKVNm5jmfUHmDVMLrSITWg8f@@ASPq63I94oOiMcStu1ggJtIA7ApFu2oWTQiiXzwTh/6kPclfOwgWaXZWuT8U9a60WpsoEf6QoKp9Qbeyv/jO1QnvI7/O2r9cAvaKMbBfQKp1kKDHrXHRuSwA8MMKOjcCbtv2PMeE4LaaWdHP/wC "Retina 0.8.2 – Try It Online") Explanation: ``` +m`^(\[\w+] ).*¶(?!\[\w+]) $&$1 ``` Tag all untagged lines. ``` O$`(\w+).* $1 ``` Sort the lines, taken from my answer to the original challenge. ``` ¶ ¶¶ ``` Double-space the lines. ``` rm`(?<=^\1.*¶)¶(.\w+].) ``` Remove duplicate tags and the empty line before them. This means that the only empty lines left are those that delimit the separate tags. ``` (?<=(^|¶¶).\w+]). ¶ ``` Move the tag to its own line. [Answer] # perl -Mfeature=say -n, 47 46 bytes (Saved one byte courtesy of @Dom Hastings) ``` $;=$1 if s/^\[(\w+)\] +//;$;{$;}.=$_}{say for%; ``` [Try it online!](https://tio.run/##XY9Ba8MwDIXv@RXvkMJGabPSDsZCTmOFHga7O9lwHWUOTewgOw2l9K/Pc7vDYDc96b1P0kDcPYaQ5kW6QtvAZR@luCun@X1ZYZ5leZqf0/yyLNLPy9nJExrLsxDERNJr4govIzMZD0/98Iyn9TYRe8kHoqHCtnUacUjsEJvJTVuub5qIE@G8VYf@6vcV3neYr5erTSJiJY2xo1FUoyf@IsbUeo3X6j@@I3mkX/zfUZuHGZSWMQ7bgGVrUJMn5alOBHbQMQOJzh6pO2Ef9@irUVllzehd8m0H31rjwuKticyRqYi/h4X5AQ "Perl 5 – Try It Online") ## How does this work? First, the effect of the `-n` switch. This causes Perl to wrap the program in a loop, which reads the input and executes the body for each line. But it does so in a very unsophisticated way, it wraps the body in the loop before doing any parsing, as follows: ``` perl -ne 'TEXT' ``` gets turned into ``` LINE: while (defined($_ = readline ARGV)) { TEXT; } ``` But that means if your `TEXT` is of the form `LOOP_BODY}{FINAL_STATEMENT`, you end up with the program: ``` LINE: while (defined($_ = readline ARGV)) { LOOP_BODY } { FINAL_STATEMENT; } ``` We're using this trick just to save a few bytes over an `END` block. In the program itself, we're using two variables to do our bookkeeping. `$;` will contain the current tag, and in the hash `%;`, we track the lines for each tag. Now, for each line of the input, we check to see if it starts with a tag, and if so, we strip it off from the line, and remember the tag: ``` $; = $1 if # Remember the tag if, s/^\[(\w+)\] +//; # we can strip of a tag ``` We then concatenate the current line (stripped from a tag, if present) to the set of lines already collected for that tag -- if there are no such lines, we effectively concatenate it with the empty string: ``` $;{$;}.=$_ # Remember the current line ``` Finally, after reading all lines, we print the hash. Perl conveniently flattens a hash to a simple list if you treat it as a list, alternating the keys and values. This gives us output where each section is separated by a newline, and is headed by the tag. ``` say for%; # Print the flattened hash ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` vyD']¡н¦DžjÃÊi‚»]).¡#н ``` Input as a list of lines, output as a list of lists of multi-line strings. [Try it online](https://tio.run/##ZY6xTsMwEIZ3nuIUVCFEVRW1A2IlrdSNPfLgOAc2TezIdlJ1QEKw8QhsXVhgZqnC4Kh7n6EvEuwIhATb3f//93@nDE0Fdl29jk@I2@wb9xrvPu/ap/ZZHB5e3JacHh7f3XbkNsf7prvvF/cRu7e26ZIoWSG1HDWBq0prlBYsFuUlXEzm0TBKUqqXiCWBuTAcvI3agBe91ytKZ72C@FdiXJQmVBir2LIIPZbA9QLOJqPzaTD8TKVUlWSYQYH6FjWshOUwI//ROdIaf9C/T0/HA0@ivgLUDWgqJGRokVnMQg4WwP0dUMhVjfkaUk/jIcoUU7KyJiJH36Av) (pretty-printed; feel free to remove the footer to see the actual output). **Explanation:** ``` v # Loop `y` over each string of the (implicit) input-list: yD # Push line `y` twice ']¡ '# Split the copy on "]" н # Only leave the first part ¦ # Remove the leading character (the potential "[") D # Duplicate it žj # Push builtin string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" Ã # Only keep those characters in the string we duplicated Êi # If it is NOT equal to the string: ‚ # Pair it with the previous line » # And join that pair with a newline delimiter ] # Close both the if-statement and loop ) # Wrap all values on the stack into a list .¡ # Group all strings by: # # Split the string on spaces н # And only leave the first part (the tag) # (after which the result is output implicitly) ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html)`-F]`, ~~122~~ ~~123~~ 113 bytes Added a byte to fix a bug kindly pointed out by [water\_ghosts](https://codegolf.stackexchange.com/users/94694/water-ghosts). Saved 10 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)!!! ``` /^\[\w+\]/{a[l=$1][i++]=$2;next}{a[l][i++]=$0}END{for(k in a){print"\n",substr(k,2);for(j in a[k])print a[k][j]}} ``` [Try it online!](https://tio.run/##ZZBba8JAEIXf8ysGsVCJt6RCS8Unq@BL6e1ts5U1Gc0a3Q27k6Yg@etNN@mFYt@Gc745zBlRZnU9eo1YVPoRH50EO8y6AWfS9/msG04VvlPVqD/SuFrc35222lxmIBWI3ik3UlEnUp2@LTaWnNEPe9OG2LcEy3ivZdqR7XlV1TUrUVCKhsO8MAadSXjMbyG8mXtw1AahTL8Ij1nScXYUJkPisILnx6eXQeCxTaNgzmEpbQouAo0FJ5472iStg/@yHlbgXw2DyfnGAcUbfmf93jkZX0CcChUj6C0Y4aolSBgTJmexCwiH18Gf1eVB6wRKYZRUO4@R2K1LSem6UM1lsWtrOewL2zzBkmM@dE5SK1sPlvwT "AWK – Try It Online") [Answer] # SimpleTemplate, 142 bytes Well, this wasn't too hard. This answer is a slightly modified version of: [De-interleave log lines](https://codegolf.stackexchange.com/questions/209666/de-interleave-log-lines/209797#209797) ``` {@callexplode intoL EOL,argv.0}{@eachL}{@if_ matches"@^(\[\w+\]) ?(.+)$@"M}{@setX"#{M.1} "}{@set_ M.2}{@/}{@setS.[X]S.[X],X,_,EOL}{@/}{@echoS} ``` --- **Ungolfed:** Since this is quite unreadable, below is a readable version: ``` {@call explode into lines EOL, argv.0} {@set storage null} {@each lines as line} {@if line matches "@^(\[\w+\]) ?(.+)$@" match} {@set last "#{match.1} "} {@set line match.2} {@/} {@set storage.[last] storage.[last], last, line, EOL} {@/} {@echo storage} ``` --- **Changes:** Some changes had to be done to work properly, with the new requirements. Below is a copy of the linked answer: ``` {@call explode into lines EOL, argv.0} {@set storage null} {@each lines as line} {@if line matches "@^(\[.*\])@" match} {@set storage.[match.1] storage.[match.1], line, EOL} {@/} {@/} {@echo storage} ``` Below is a full list of the changes: * The regular expression was changed to match the remaining content, without a space, if present. (Quoting: "There will always be at least one non-space character after a tag.") * Stores the "app" with an extra space, for later use and to normalize the lines (which may or may not have a space right after the "tag"). * Stores the remaining content, without the first space, into the `line` (`_` for the golfed version) variable * Adds the "tag" before the `line` variable, which used to be part of the `line` variable. As you can see, the changes aren't that significant. Move code, add extra space, add a variable to an output. --- You can try this on: <http://sandbox.onlinephpfunctions.com/code/eb5380ba1826530087fd92fa71d709c0b2d6de39> [Answer] # Scala, 127 bytes ``` l=>((("",List[(String,String)]())/:l){case((p,m),s"[$t] $b")=>(t,(t,b)::m)case((p,m),b)=>(p,(p,b)::m)})._2.groupMap(_._1)(_._2) ``` [Try it in Scastie](https://scastie.scala-lang.org/zyzn2RddTWGbAvvXg9OnKA) (doesn't work in TIO) Wow, this is long. ]
[Question] [ Input a scientific notation number (base 10), output scientific notation in base 16 (as defined below). ## Details In scientific notation, all non-zero numbers are written in the form $$ m \times 10^n $$ Where \$ n \$ is an integer, and \$ m \$ is a real number, \$ 1 \leq |m| < 10 \$. Consider scientific notation in base 16. $$ m \times 10^n = m' \times 16^{n'} $$ \$ n' \$ is an integer, and \$ m' \$ is a real number where \$ 1 \leq |m'| < 16 \$. ## Input / Output Input a positive real number. You may also choice to input \$m\$, and, \$n\$ separately. For all testcase, -100 < n < 100. Output the number in hexadecimal scientific notation. Could be a single string or two strings. Number \$m\$, and, \$n\$ should also be formatted as hexadecimal strings. Output as `1.2E3E4` is not allowed due to ambiguous. (1.2E3×104, or 1.2×103E4) You have to use other notations. For example, `1.2E3E+4`, `1.2E3, 4`, `1.2E3&4`, `1.2e3E4`, `1.2E3e4`, `1.2E3P4`, `1.2E3⏨4`, `1.2E3*^4` are all acceptable. ## Testcases ``` m, n -> m', n' 1.6, 1 -> 1, 1 6.25, -2 -> 1, -1 1.0, 1 -> A, 0 7.257672195146994, 93 -> d.eadbeef, 4d 1.234567, 89 -> f.83e0c1c37ba7, 49 1, -99 -> 8.bfbea76c619f, -53 ``` You output may be slightly different from given testcase due to floating point errors. But you should keep at least 4 hex digits precision, and \$1 \leq m' < 16\$. ## Rule This is code golf. Shortest codes in each languages win. [Answer] # JavaScript (ES6), ~~134 124~~ 121 bytes Expects a float and returns an array of 2 strings. ``` n=>([x,y]=(+(g=n=>s=n.toString(16))(n).replace(r=/[1-f]/g,1)).toExponential().split`e`,[x.replace(r,_=>r.exec(s)),g(+y)]) ``` [Try it online!](https://tio.run/##dY7NaoQwFIX3fYosEyaJxp/ELDLQRZ@gS5FOjDdikURUivP0VuiijJ3e3YHvO@d@2i@7uHmYVhZiB7s3ezBXXG/03hh8wb054mICX@P7Og@hx0ISggPhM0yjdYBnk9SC@SbpqSDk4N62KQYI62BHTPgyjcN6gxutt1@FfpjrzGEDhxdCaI8vd9KQ3cWwxBH4GHvsseASBHo8QlCSIEGReHmEJc9KYNlzmJ1pwdN/ql8pSk@wOqqVVJnQpSik1gXo/AfuONiuBfAUFd2fiSwvSqmg0qcJz6scUidcrlqrDlWfVWBaP/2u4q1vwSrppNDHKivz/Rs "JavaScript (Node.js) – Try It Online") ### How? We first convert the input to hexadecimal and save the result in the variable `s`. For instance, `7.257672195146994e93` is turned into: ``` "deadbeef0000000000000000000000000000000000000000000000000000000000000000000000" ``` We replace all non-zero hexadecimal digits with `1`'s: ``` "111111110000000000000000000000000000000000000000000000000000000000000000000000" ``` We coerce this back to an integer and invoke the [`.toExponential()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) method: ``` "1.1111111e+77" ``` We split this string into `x = "1.1111111"` and `y = "+77"`. We replace all `1`'s in `x` with the non-zero hexadecimal digits of `s` in order of appearance: ``` "d.eadbeef" ``` Finally, we convert `y` to hexadecimal: ``` "4d" ``` Below is another example with `6e-19`: ``` "0.000000000000000b116b7de48f008" "0.00000000000000011111111111001" "1.1111111111001e-16" [ "1.1111111111001", "-16" ] [ "b.116b7de48f008", "-10" ] ``` ### Commented ``` n => ( // n = input [x, y] = // x = mantissa, y = exponent ( // +( // coerce to integer: g = n => // g is a helper function converting its input ... s = n.toString(16) // ... to a hexadecimal string saved in s )(n) // invoke g with n .replace( // replace: r = /[1-f]/g, // r = regular expression to match the non-zero // hexa digits 1 // replace all of them with 1's ) // end of replace() ) // .toExponential() // convert to exponential notation .split`e`, // split into [ x, y ] = [ mantissa, exponent ] [ // output array: x.replace( // replace in x: r, // use r a 2nd time to match the 1's _ => r.exec(s) // use r a 3rd time to get the next hexa digit // from s, this time taking advantage of the // stateful nature of RegExp ), // end of replace() g(+y) // convert y to hexadecimal ] // end of output array ) // ``` [Answer] ## JavaScript (ES6), 217 bytes ``` f= n=>/^-?0\./.test(n=n.toString(16))?n.replace(/^(-?)0(.0*)(.)(.*)/,(_,s,z,d,t)=>s+d+'.'+t+'e-'+z.length.toString(16)):n=n.replace(/(-?.)(\w*).?(.*)/,(_,s,d,t)=>s+'.'+d+t+'e='+d.length.toString(16)).replace(/0*e=/,"e+") ``` ``` <input type=number step=any oninput=o.textContent=f(+this.value)><pre id=o> ``` Output format is `-?[1-f]\.([0-f]*[1-f])?e[+-][1-f][0-f]*`. [Answer] # [Perl 5](https://www.perl.org/), 181 bytes ``` sub f{($e,$x)=(0,10**pop()*pop);$x/=16,$e++while$x>=16;$x*=16,$e--while$x<1;join('',map{sprintf$_?'%x':'%x.',$x%16,$x-=$x%16,$x*=16}0..12)=~s,\.?0*$,,r,sprintf$e<0?'-%x':'%x',abs$e} ``` [Try it online!](https://tio.run/##bVHbbuIwEH33V1jIKAmMnThXQgj0B9infStVlYDTzYpcFKfaVIj9dTopdLe7wg9HnnPmnBnZreqOweWiX3NanEymgA1WajogndmsbVrTGtFK2GCnMgSm5vNfP8qjYsMaa6RnV5rzG72Syc@mrE3DgCprT7rtyrov2PPGmA7GEkEYOGI6mgaeft7GlLMjhHSt9LeGndg4MwbQwadfrZyNwW8RBmS5Zup8edWKfle6Xy63Tadoj1edrsOEkOqNPoxliks82nzzuDtkvNiJp7n9Uj5h7LHs7V1tw2plGAmRIgQq6X@Hr6lEmoTCDYBy957KJZqd@@YMqEMiNEdh5Mo4kH4Yxz7Q2BvVg1DZIVeqAOofMMT1/CCMgC7if0IKsfCUs5d7L8ozlP2YjGPj@M7AhciLXGVRuA9ljLk88Agpms78eAvrRMa@6s1kFbAa2FYNLbBviFb6wJ6TP/L2pelRQLTS4tptXdVSm5Mv8gTo5EsMlrcPm1A65W6gKce16FR/NFZAWf3XQq8eTD5f3gE "Perl 5 – Try It Online") I think using `sprintf('%a',$x)` could make the answer much shorter, just not sure how. Ungolfed: ``` sub f { my($m, $n) = @_; my($e, $x) = (0, $m * 10**$n); $x/=16, $e++ while $x >= 16; $x*=16, $e-- while $x < 1; return ( join('',map{sprintf$_?'%x':'%x.',$x%16,$x-=$x%16,$x*=16}0..12) =~ s,\.?0*$,,r, sprintf($e<0?'-%x':'%x',abs$e) ) } ``` Test: ``` for my $test (map[/-?[\da-f\.]+/gi],split/\n/,<<''){ 1.6, 1 -> 1, 1 6.25, -2 -> 1, -1 1.0, 1 -> a, 0 7.257672195146994, 93 -> d.eadbeef, 4d 1.234567, 89 -> f.83e0c1c37ba7, 49 1, -99 -> 8.bfbea76c619f, -53 my($m,$n,$Mexp,$Nexp)=@$test; my($Mgot,$Ngot)=f($m,$n); my $testname = sprintf" %-25s --> %s", "$m, $n", "$Mexp, $Nexp"; is("$Mgot,$Ngot", "$Mexp,$Nexp", $testname); } ``` Output: ``` ok 1 - 1.6, 1 --> 1, 1 ok 2 - 6.25, -2 --> 1, -1 ok 3 - 1.0, 1 --> a, 0 ok 4 - 7.257672195146994, 93 --> d.eadbeef, 4d ok 5 - 1.234567, 89 --> f.83e0c1c37ba7, 49 ok 6 - 1, -99 --> 8.bfbea76c619f, -53 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62~~ 61 bytes ``` ->x{'%x.%x,%+x'%[m=x/16**n=Math.log(x,16).floor,m%1*16**9,n]} ``` [Try it online!](https://tio.run/##LcpNDoIwFATgPad4mwbFUm2B1rfAG3gCwgJNkQU/BiF5Bjh7lcBu5pvpx8fXlakLbzT5jAQjzk7ks6xJ6Sx1ELTpvRgqUXevA3Gpj6Ksu67nDZPBOiNv88VlHgBIoa3ka9JCJTZUfNPLruavRhslMZGxRowtRvtFRXGijb3i1m2I6OXCFs8KJphphvc4fKDMKIfF/QA "Ruby – Try It Online") Input is a (decimal) float. Output is in the form \$m',n'\$, where \$m'\$ has a maximum precision of 10 hex digits and \$n'\$ is always signed. `'%x.%x,%+x'` is a shorthand form of `sprintf` syntax, which creates formatted strings for numeric output. The format specifier `x` converts its argument to hexadecimal and the `+` guarantees signed output (otherwise negative numbers would be output with two leading dots representing an infinite string of leading `ff`s). We do three conversions to hex: (i) the integral part of \$m'\$, (ii) the fractional part of \$m'\$ (`m%1`; multiplying by `16**9` is necessary because the fractional part is ignored by `sprintf`), and (iii) \$n'\$. The solution makes use of some straightforward mathematical transformations. Let \$m'=16^{m''}\$, so that \$x\equiv m10^n=m'16^{n'}=16^{m''+n'}\equiv 16^y\$. Then \$y=\log\_{16}x\$. We are told that \$n'\$ is an integer, hence we take \$n'=\lfloor y\rfloor\$. This is the only choice of \$n'\$ for which \$0\le m''=y-n'<1\$, and hence the only choice of \$n'\$ for which \$1\le 16^{m''}=m' < 16\$ as required. To support negative inputs, add `.abs` in two places and another `+` in the format string, bringing the code to 70 bytes: ``` ->x{'%+x.%x,%+x'%[m=x/16**n=Math.log(x.abs,16).floor,m.abs%1*16**9,n]} ``` [Answer] # C(GCC), 32 bit float, ~~133~~ ~~129~~ 128 bytes -4 bytes ceilingcat ``` m;e;s(float f){m=*(int*)&f;e=(m>>23)-127;m=(m&-1U>>9|1<<23)>>3-(e&3);printf("%x.%05xE%c%x",m>>20,m&-1U>>12,"+-"[e<0],abs(e/4));} ``` [Try it online!](https://tio.run/##VY5BboMwEEX3nAJZIrJT28UY7FhOkLrgCF21XYAZt5FKGgUWSGnOTg1qmmZjyW/enz@OvTs3TZ0F22P/@VUPsSfnbrfG@8OwJitvYYe7sswkYSLTtgu/FRPPZWm@xXYbcFlKhmEliT2eQsZjlIw8SYuxSlwyIjqHU/obEhlFDwy9wDZ9o3XTY3jMCbGXaYB@uPbT2H3Up3UM4xHcAC2Jz9F1d48TT1iJqCc2CheH9zqKcdKT1wOit6CNLlFX7w94XrFUCK5A0BiJSqAwXpjiWQEsWyi7YcHTRX2q0j@mg6qVzoQpRK6MycHIoLQc6rYB8FXe/stnMi@Uho0JiucbCakTTuqm1lVu7nqYmZ0Nb3wDtVZOCeMrVshZukw/ "C (gcc) – Try It Online") This extracts the exponent and mantissa from a floating point number. Since the maximum exponent is +/-127 in base 2 (approx 38 base 10), this doesn't quite meet the challenge since it fails on larger exponents. So... # C(GCC), 64 bit float, ~~167~~ ~~163~~ 147 bytes -4 bytes ceilingcat ``` long m;e;s(double f){m=*(long*)&f;e=(m>>52)-1023;m=(m&-1UL>>12|1L<<52)>>3-(e&3);printf("%lx.%013lxE%c%x",m>>49,(m&-1UL>>15)*8,"+-"[e<0],abs(e/4));} ``` [Try it online!](https://tio.run/##VY7NboMwEITvPAWyRGRTm2LMn@XEUg/ccu2p7QHMOo0EJApUQkrz7BSQ0rSXlXbmm5017GDMNDWn7uC2ClSP69NX1YBrybXd@XgxfLKxCna41TqJCONhJFQ7rxvGX/da8@ib77fb2dJaMAwbQdT5cuwGi5HXjIEXctGMhWe8EdH5RizpI5sQP6foiaE32IYftKx6DM8xIeo2DdAPv99Q13yWF9@F8QxmgJq4V@de0mPPEqYRtUQ5PV7m3XKx15P3DtFHUDk3py2PHV5OrB08SIFTF/GCo9letTSIEmDRqrKHzINwRV@K8FfLZjRLs4jLhMeplDFIMSN1AGVdAdgirv/kIxEnaQa5nBEb5AJCw43IqjIrYvmvh8mFyYPKVlBmqUm5tAVLxALdph8 "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), 192 bytes ``` function(x,i=function(x,p=F,y=abs(x))`if`(y>0,{d=c(0:9,letters[1:6])[rev(y%/%(16^(0:log(y,16)))%%16+1)] c("-"[x<0],d[1],"."[p],d[-1])},0))cat(i(x*16^(3-(n=log(x^2,16)%/%2)),T)," ",i(n),sep="") ``` [Try it online!](https://tio.run/##TZDNaoRAEITvPoUMCN1Ja6b9GTNLJsc8QW7GZV13DIKoqBFl2Wc3ettbFQVfFTVs12K0rKqmKyazVX9tOdVdCwvV5sn05otWU1xHWBAvdXWB9VPS/WZKkCdNjZ0mO4wZn1SO2WBnWL03D1id97jpfmElVojoeaxeGXOnBOGLbPmQOd0yzkkEIusP7XOOD5KIZTFBDcvLwYh8aM2BWc7hAdrZISJ9IwlXUA0t0mh7IwRuVTfA7NatW@7tJAOpwoRYUhqESarSkHXCsdI6tjoiDsIoTlRq3zWx9bVGdO7O0yEwo3MMET@tQOex/QM "R – Try It Online") Happily handles negative numbers, even if now not required. Commented: ``` base16float==function(x, l=c(0:9,letters[1:6]), # define hexadecimal digits i=function(x,point=FALSE,y=abs(x)) # create function to write hexadecimal integers `if`(x==0,0, # if x is zero, just write zero {d=l[rev(y%/%(16^(0:log(y,16)))%%16+1)] # otherwise get the digits for each power-of-16 c("-"[x<0],d[1],"."[p],d[-1])}) # and paste them together with the sign ) # (and with a "." after the first digit if # specified by point=TRUE in the function call) cat(i(x*16^(3-(n=log(abs(x),16)%/%1)),T), # so: first output the mantissa as a 4-digit integer # with point=TRUE to include the dot, " ", # leave a gap, i(n), # and write the exponent sep="") ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 284 bytes `struct` approach. At least I tried) ``` from struct import* m=lambda s,c,n,k:[s[n:],'-'+s[k:]][c] n=lambda s:m(s,s[0]=='-',2,3) o=lambda s,x:m(s,x<0,0,0) p=lambda x:x[2]+'.'+x[3:] s=lambda x,y,d=2**52:(o(p(hex((x%d+d)*2**((x//d+1)%4)).rstrip('0')),y),n(hex(((x//d)%2048-1023)//4))) f=lambda x:s(unpack('Q',pack('d',x))[0],x) ``` [Try it online!](https://tio.run/##RY/JboMwEIbP9VNwieyBYbHZAioP0bPlQ8qioBRjYSI5T0@tRE01h5l//k@zmMd@XXV@NttxTNu6BHbf7v0ezItZtz0kS/dzWb6HS2CxR423VlqpW4U0ppGVt1Yp2Sui31S7MItWZqrrPIICcyDr/wz39N1nhj6AmD/HtU4KFdGERk7mrSL27eADh06EYSlatjLDrqNjzJ2GaIDQt32dpkPE4VQAJJs/fzaMZhQAH4D6hT8ZOImsOMc8EzmkqaeBTP/7Lbtrc@lvjH5RfBUDRQfgf/HpcJ3kSTVyrBJRjrFAnmRe1V7VVS14U/KiappibHKMeSLyoqzq8dx4McZNo8i0bsEczNrvIh9mm/XOJjYDHL8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~135~~ \$\cdots\$ ~~119~~ 105 bytes ``` def f(x):m,n=x.hex().split('p');m=hex(int('1'+m[4:],16)<<int(n)%4);return m[2]+'.'+m[3:],f'{int(n)//4:x}' ``` [Try it online!](https://tio.run/##dZDdioMwFITv@xRBWGJoTBsTk8bWfZFuL/w5oYVqRS24FJ/dNbpQYdlzlZl8ZxKm/u6uj0qMYwEWWb8ncUmrpGdX6H3C2vp@63xcY3IsE2fdqklyvC3PMr5Qrsjp5KyKfEhybKB7NhUqz@Fli5mDxARZ/FqQ3U7G/YDHDtquRQnyN2ganzMFnCLf42y/Ho8ij3uE0AVTLIwgCP8BgxU5XS@B6V9u/8b0FKiVDrmJuFTGSDDCbRUM0iIDsO8tWazTQyEjpeFgHG3ZQcA@57nQWaoX2qxoCMzMHVhmM0i1yhU3dvlzJGaQbBrXxhN/PUMtc0zRcuQCk419NMgVRhH0NeQdulWzbuP5Adej9Z1BZl03ruupcmcNKPhEr3ZAr@Y8gclvxGXAZPwB "Python 3 – Try It Online") Inputs a float. Returns a tuple of strings \$(m',n')\$. ]
[Question] [ # Context The water buckets riddle or the water jugs riddle is a simple riddle that can be enunciated in a rather general form as: Given \$n > 0\$ positive integers \$a\_1, a\_2, \cdots, a\_n\$ representing the capacities (in units of volume) of \$n\$ buckets and a positive integer \$t \leq \max(a\_1, a\_2, \cdots, a\_n)\$, find a sequence of *"moves"* that places \$t\$ units of volume of water in some bucket \$i\$. To define the valid *"moves"*, let \$c\_1, c\_2, \cdots, c\_n\$ represent the units of volume of water each bucket \$i\$ contains, with \$0 \leq c\_i \leq a\_i\ \forall i\$. Then, at each step you can do any of the following: * fill a bucket \$i\$ entirely, setting \$c\_i = a\_i\$ * empty a bucket \$i\$ entirely, setting \$c\_i = 0\$ * pour a bucket \$i\$ over a bucket \$j\$, setting $$\begin{cases} c\_i = \max(0, c\_i - (a\_j - c\_j)) \\ c\_j = \min(a\_j, c\_j + c\_i) \end{cases}$$ i.e you pour bucket \$i\$ over bucket \$j\$ until bucket \$i\$ becomes empty or bucket \$j\$ becomes full, whatever happens first (or both if both things happen at the same time). # Task Given the bucket capacities and the target measurement, your task is to output a minimal sequence of movements that places \$t\$ units of volume of water in one of the buckets. # Input The capacities of the buckets are positive integers. You can assume these capacities are unique and ordered. You can take them in a number of reasonable formats, including but not limited to: * a list of integers * arguments to a function Additionally, you will take a positive integer `t` that is not larger than the maximum number present in the input capacity list. You can assume the input parameters specify a solvable instance of the water buckets problem. # Output Your program/function/etc should output the shortest sequence of moves that places `t` units of volume of water in one of the buckets. If several such sequences exist you can output any one sequence. Please note that some moves commute and that also introduces multiple solutions to some problems. Your program can print the sequence or return it as a list of moves or any other sensible thing. To identify the moves and the buckets, you can choose any encoding suitable for your needs, as long as it is consistent across test cases and completely unambiguous. A suggestion is, use three letters to identify the three moves, like `"E"` for emptying a bucket, `"F"` for filling and `"P"` for pouring and use numbers to identify the buckets (0-index or 1-indexed or using its total capacity, for example). With this encoding, to identify a move you always need one letter and a number. In case of a *"pouring"* move, a second integer is also needed. It is up to you to consistently use `"P" n m` as `n` was poured over `m` or `m` was poured over `n`. # Test cases We use the encoding above and `"P" n m` means "pour bucket `n` over bucket `m`". ``` [1, 2, 3, 4], 1 -> ['F 1'] [1, 2, 3, 4], 2 -> ['F 2'] [1, 2, 3, 4], 3 -> ['F 3'] [1, 2, 3, 4], 4 -> ['F 4'] [13, 17], 1 -> ['F 13', 'P 13 17', 'F 13', 'P 13 17', 'E 17', 'P 13 17', 'F 13', 'P 13 17', 'E 17', 'P 13 17', 'F 13', 'P 13 17'] [4, 6], 2 -> ['F 6', 'P 6 4'] [1, 4, 6], 2 -> ['F 6', 'P 6 4'] [3, 4, 6], 2 -> ['F 6', 'P 6 4'] [4, 5, 6], 2 -> ['F 6', 'P 6 4'] [4, 6, 7], 2 -> ['F 6', 'P 6 4'] [1, 3, 5], 2 -> ['F 3', 'P 3 1'] [7, 9], 4 -> ['F 9', 'P 9 7', 'E 7', 'P 9 7', 'F 9', 'P 9 7'] [8, 9, 13], 6 -> ['F 9', 'P 9 8', 'P 8 13', 'P 9 8', 'F 13', 'P 13 8'] [8, 9, 13], 7 -> ['F 8', 'P 8 9', 'F 8', 'P 8 9'] [8, 9, 11], 10 -> ['F 8', 'P 8 9', 'F 11', 'P 11 9'] [8, 9, 12], 6 -> ['F 9', 'P 9 12', 'F 9', 'P 9 12'] [8, 9, 12], 5 -> ['F 8', 'P 8 12', 'F 9', 'P 9 12'] [23, 37, 41], 7 -> ['F 41', 'P 41 23', 'P 41 37', 'P 23 41', 'F 41', 'P 41 23', 'P 41 37', 'F 41', 'P 41 37', 'E 37', 'P 41 37', 'E 37', 'P 41 37', 'F 41', 'P 41 37'] [23, 31, 37, 41], 7 -> ['F 23', 'P 23 37', 'F 31', 'P 31 37', 'P 31 41', 'P 37 31', 'P 31 41'] ``` You can check a [vanilla Python reference implementation here](https://tio.run/##xVZNb9swDL37V3DpxcbcIl9ttmDpYcMG9LCtWLFTYASuQ9dyHdmw5bRBkd@ekfK3G2zFhmKnSE8kH/lIS0l2Kojl5HBYow9ZHG1xdZt796gy03OTzAZlzQ0A4YOCDzCEOKXFJWzcR32uDwGSVEhlDq6@Xn@/ubn6@OPnwNJ4iipPJS0x0hEWCxjOWyewdAzanoCQQgFuErWDkp5gL5YKpcpgAcsh@ES9IkNgXkd7RSJT4EYRJHFOGdxB4oqUPfUvu5nChtDSvoJ9U1feoRmhLLIvTsKjJ5SwgDcLCMsUM@UqzMBNEcwqMxs28ZbAdSyRKyYb717zNhZLx2plG/uwFZlQuC4DsheiZKfKZzmfO5r0IRARFkEL1SQ@qlVN4miMK2BPymWbcSUte6b1SQoFKt1xrixSFm9QBdXqIcAUS2Mtk13ooSWsougBkLHSREvhNHjRJSFzNGrME5RdadmAYQWGDSgZqHCquntA7nTGoza0Keip7gy5n3qhZfVMQ20qZGXDDm/JrjY7gU8Bkm5UyANC4G4Rbll3Lp9mKEV3vetUq1NjOcnq9/VKFn7B8ndrIODMTRKUa9MfXMOTTk04@3IVOvuB1abUdJq3zVd@KRytCV3PQUVgymIG2KwlDidfmWgLy6gHg0fCF1HUmYn2JBz7LDoTUTdpAWVtfxDqBe0uA71mK740rfjvDdB33t934MXf5EukH76m6J@Piv7POlaXYROozqF/WRr1O3WDbuoFpD8i4GPg5hndx2fwLeYXMFciliR/LtdnOtP6qTrQda1WnpuhflsMczmyYWzDxIYpXTgjy@5D4@fQ5Dk0LSDajWZ1nKkNF@0Inf2kt6fNeW9/YcOs7U8u5/V@ZsP7mvgdbYh1QsBFH5i1gREnN2wj474PA@caGBPhhHimozqMhkYd2KC26Aes@K/B89aIPK875g/08OxteFJ7OL2Ep@N/VWi0Dr8A) [Answer] # [Python 3](https://docs.python.org/3/), ~~243~~ 239 bytes *-4 bytes thanks to @JonathanFrech!* ``` def f(a,t,k=1): while g(a,t,[0]*len(a),[],k):k+=1 def g(a,t,c,p,k):n=len(a);k,i=k//n,k%n;k,j=k//n,k%n;exec(["c[i]=0","c[i]=a[i]","x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x"][k%3]);p+=k%3,i,j;return g(a,t,c,p,k//3)if k>2else{t}-{*c}or print(p) ``` [Try it online!](https://tio.run/##hZLBbuIwEIbveYpRVlViGKAQSmmRe9uee4@iVRScYpI4VmJ26UZ5dnaMlRbUVXuxxvN/Mx7/tn4zu1pFp9NW5JCHKRos@Jw9evBnJ0sBr@dUfJuMSqHClGGcYMEeizGfe7bE6Rlqm1XcQZsCJS9mM4XFjaLN/mMjjiILYz@LZcJvfXRBSgvFR15JKo/3ySSjBa3GNnad8OPGpsb86CdxcRNRXo85BShxv2mEOTTqcpbZLGIyh@JpIcpWdKafdKOsrxvQjVQm1OwkK103Btq31vMakZa/zgpwR3heTnAplQCpLDRtzVYqsqVFaIiqUh22pqF0IzWeyWmrS2lCf/LkM0bgjvqL1ra0rojfaRk2Vvg4LWwxJ/wd5d0Q9T6BdBsqPhe2zPPgB2S7VL0KNyKYmgJhZP4GZiegPhh9MB7YVxluSfNSlcPTzBzS8h27HEOzC871lGL7X9QHBH@6r@mhcr8Lfj6/BHGV9J3suz2Q4xXnC7CeQxD0PlgXK/tG1sa/UoejWBrR0InJKGLM3cr@ifMVsnorPPcLr31ip3iOsECIEJYJwhzItTh4hnmQeNfSYpAWn6RokKJP0nKQllZaIqwuW60ChOAFVk6lwq@B6DuA1LvvgBXC/Zcz0Cl3l0DkgMh5skZ4IJ8iIu4HYu2INTzY4Gqf/AM "Python 3 – Try It Online") **Input**: a list of bucket capacities `a`, and the target `t`. **Output**: to stdout, a list of integers, where each triplet `m,i,j` denotes a move: `m` is the move type (`0,1,2` corresponds to `empty, fill, pour`), and `i`,`j` are the bucket indices (0-index). For move types `empty` and `fill`, the 2nd bucket is ignored. **How**: Each sequence of moves `p` can be encoded by an integer `k` using modular arithmetic. `g` is a recursive function that checks if the sequence `p` encoded by `k` will result in the target `t`. If so, that sequence is printed to stdout, and a `Falsy` value is returned. ### Old solution using `itertools.product` ### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~279~~ 249 bytes *Whopping -30 thanks to @ovs's double `product` trick!* ``` from itertools import* P=product a,t=eval(input()) for r in count(): for p in P(*tee(P((0,1,2),R:=range(n:=len(a)),R),r)): c=[0]*n;[exec(["c[i]=0","c[i]=a[i]","x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x"][m])for m,i,j in p] if t in c:print(p);exit() ``` [Try it online!](https://tio.run/##hVJNb@IwEL37V4zSQ5KuiwhQyoeyt/a6aK8RWnmDU4zyYdlOASF@OzuTEApqt70E8@a98fi90Xu3rsrhRJvTHWwlbEXpwFVg6hLcWlnQpno1ooCizp3SuQSnCmk52Aoh68CKNwnKgbBgnVHlK8pkCXInU5ZWKwkx@L5/ykxVIE0aV1W5BVXoyrh7toix/6pOHRPcxfJN5IEqde2CMGRZZcCAKiGt6hKRGQOCNEGL4N5JGSyCoM8jPgj571lsRPkqg3IW57IMRIhYyE1IMkjjpL@8L@cJjRUkXpqoZdz3eHsQ@MHzLi4UCpPN8iHFD6daOKfvQ7ybE/Qj3nnLpFiGNEfBFd/QLHqJN6gMXDPrTKMJLtDhXO4UTn3C1zN2B@maxiNzIKvL1KmKTCIG2e3WptqCICiVmoocsZo8rbQ@uwqNn1uFidWuEVNBvkmDIeKRrWR27omPNkJZCc@/Xp6NqUwQMmakyP8042EozS9jbRBg95Y1hueqlPQOBHrWrVSJnTBtg4pC6AAj7lHMmjfMntU5Xuc9/PQwMLBr7CUttacMmjgNFd5vDizPkH6hxofudPRwRPjcqPNOkFO21jrfN@UG7ZaWnf/i1aL4uxIws9ft2mejXhvpVNY2QBtRwoB862Kjdbk700XqapFfaNfP0OEVr@2p5OpTqgccvN6mwuXKvIP//LLwcYeOB3U8bGhvijgegMwxLN8/enC7W2FrCu3tZQUYOLOnOZttJgSHaRfnkvdMC2tvjA9PScRhwGHIYbTkEAHGkPgvEPlLdlsadKXBh9KwKw0/lEZdaUSlEYfxdauxz8FfwLitovBrwvA7AlYfvyOMOTx9OQPe8nhNGLaEYevJhMMUfRoi46ljTFrGBKZ0uPn/rojI3v7/JFHUAlF0IxqgaNxppi1linArugZuNY8f7vlU8w8 "Python 3.8 (pre-release) – Try It Online") Slow, ugly and can probably be golfed more. **Input**: from stdin, `a,t` where `a` is the list of bucket capacities, and `t` is the goal. **Output**: to stdout, the optimal list of moves, each move has the form `(m, i, j)` where: * `m` is the move type `0,1,2` (empty, fill, pour) * `i` and `j` are the target buckets' indices (0-index). * The moves `empty` and `fill` only affects the 1st bucket `i`, and thus the irrelevant 2nd bucket `j` is set to an arbitrary value. * The move `(2,i,j)` pours the water from bucket `i` to bucket `j`. **How**: This program simply tries all possible sequence of move, in order of length. To generate all sequence of `r` moves: * `product((0,1,2), range(n), range(n))` generates a list of all possible moves by performing the Cartesian product between all move types `0,1,2`, all values of `i` and all values of `j`. * `tee(product(...), r)` clones the move list into `r` lists. * `product(*tee(...)) takes the Cartesian product of`r`move lists, which results in all possible sequence of`r` moves. To perform a sequence of move `p`: * `c[i]=0`,`c[i]=a[i]`, and `x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x` respectively handles emptying, filling, and pouring between bucket `i` and `j`. Note that pouring can handle `i==j`, which results in a no-op. * `exec(["handle E", "handle F", "handle P"][m])` selects the correct handler for move type `m`. [Answer] # JavaScript (ES6), ~~197 191~~ 188 bytes Takes input as `(a)(t)`. Returns a string of concatenated operations `Fx`, `Ex` or `Px>y`, with 0-indexed buckets. ``` a=>F=(t,N)=>(g=(b,n,o)=>[...b,0].some((V,i,x)=>(x=a[i])-V^t?n&&b.some((v,j,[...B])=>(s='F',B[j]=i-j?x?(v+=V)-(B[s=`P${i}>`,i]=x<v?x:v):a[s='E',j]:0,g(B,n-1,[o]+s+j))):O=o))(a,N)?O:F(t,-~N) ``` [Try it online!](https://tio.run/##jZNfb5swFMXf@ynuw1TbyoXEkJCEzUGKFB7bPOXFclUnSzJQi6eCENK0ffXMlIj8IeuKBNg@v3Psa0OqS51v3pKfhZOZ79vDThy0mMWCFvjAxIzuBV1jhsa2peu6axwoNzevW0pXmGBVI5XQMlHMWT0VUXZ/vz7qJaZYW@aqhnJBYoJzmSqROGlURbTsiRVz6Fzm4nn55Vfye/aMiRLVtzKqwpKF2gpkQTBV4QD3dI6Zw1Ea1ct7KWMsfBSGMartMqPHMLbrdf48sMNXeQcgJUfwEHyEoULg9u73QZIYOFFd3Tvp3i3dP@n@LX140odHfYgQ1Mnwfp30gCCQJQQtaIPO2A9A/7OgpUafBQOE8f9B/l7pqAP6Dei3uzpGmNb7cV31tAGnMK4bi@bV9i/0Jmhig@y51Rsf3AyaNI2JZS6G4naA@3akkzY@T2tDpo31rH9hrL8fPvjAyPlxTn5t9f5ZAfeuaude1zqyVujMetuq7tydeVvozQ9KpUYoFAMxg43JcvOydV/Mnu6oZrRg7qsuLNWXi3ip5FP97PX3zE1NklECxP5dh78 "JavaScript (Node.js) – Try It Online") The above test link inserts spaces between operations for readability. Some longer test cases have been removed. [Answer] # Javascript, 364 bytes I'm sure this can be golfed much better pretty easily. ``` S=t=>G=>{L=t.length;r=(f,n,a,i,e=0)=>{if(0==n)return f.indexOf(G)>=0&&[];a=(A,B,C,D)=>(X=f.slice(),X[A]=B,X[C]=D,X);for(;e<L;++e){for(K of[0,t[e]])if(F=r(a(e,K),n-1))return[[+!K,e]].concat(F);for(i=0;i<L;++i)if(i!=e&&(O=r(a(e,Math.max(0,f[e]-t[i]+f[i]),i,Math.min(t[i],f[e]+f[i])),n-1)))return[[2,e,i]].concat(O)}};for(T=1;!(E=r(Array(L).fill(0),T));++T);return E} ``` Returns an array of arrays. Each array is in the format `[n, i]` if `n=0` (fill) or `n=1` (empty), or `[2, i, j]` for "pour bucket `i` into bucket `j`". The buckets are always given as indices, starting from 0. Uses the same basic search method as the other answers. Unminified version: ``` var S = (capacities, target) => { let n = capacities.length; var waterBuckets = (levels, maxSteps) => { if (maxSteps == 0) return levels.indexOf(target) >= 0 ? [] : false; let getCopy = () => levels.slice(); for (let i = 0; i < n; ++i) { for (let level of [0, capacities[i]]) { let levelsCopy = getCopy(); levelsCopy[i] = level; let res = waterBuckets(levelsCopy, maxSteps - 1); if (res) return [[+!level, i]].concat(res); } for (let j = 0; j < n; ++j) { if (i === j) continue; let levelsCopy = getCopy(); levelsCopy[i] = Math.max(0, levels[i] - capacities[j] + levels[j]); levelsCopy[j] = Math.min(capacities[j], levels[i] + levels[j]); let res = waterBuckets(levelsCopy, maxSteps - 1); if (res) return [[2, i, j]].concat(res); } } }; for (let s = 1;; ++s) { let r = waterBuckets(Array(n).fill(0), s); if (r) return r; } }; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~112~~ 104 bytes ``` ⊞υEθ⁰Fυ¿¬ⅈ¿№…ιLθη⪫✂ιLθLι¹ «FLθF²⊞υ⁺Eι⎇⁼κν∧λ§θκμ⟦§EFλκ⟧FLθFLθ¿⁻λκ«≔⌊⟦§ιλ⁻§θκ§ικ⟧ε⊞υ⁺Eι⎇⁼κν⁺με⎇⁼λν⁻μεμ⟦Pλκ ``` [Try it online!](https://tio.run/##jVHLSsNAFF0nX3HJ6g6MoAVBcVVKBcVKQBdCyCKk02bIZKZ5jFik3x7vTWpq0YWLedzDmfNg8iJrcpeZvo99W6CXsMp2WEu4FOIu3LgG0AvQG8Bn1@EbCjFOC@dth4t9btSicDvUEp6U3XYF1kJIKIgWN5ooj05bfDE6V2ec6arpekUrgogdlWkVfIbB4HxShGGekegxZWx8ixyVRF9VY7Nmj8vaZ6bFUoIlwbldo6Gje7Br9cGVSk5W8ZZ8o9HyPpJgCCpTtv/b98fM3VfakrkZBDlrMG9bvbWM68pXOKnrUXrknwU55dKDTEqIYv/g/wUHRsXvfjHMyBiNjxQqzs2jmAtPfQ/hoe@T5EbCLf3DLJVwnfYX7@YL "Charcoal – Try It Online") Link is to verbose version of code. Could save 6 bytes by including the final bucket state in the output. The code spends most of its time emptying or pouring empty buckets, so don't try it on the harder problems. Explanation: ``` ⊞υEθ⁰ ``` Start off with all buckets empty and no operations so far. (Each entry comprises `n` buckets plus an unspecified number of operations.) ``` Fυ¿¬ⅈ ``` Perform a breadth-first search until a solution has been printed. (This relies on `t` being positive, as that means that at least one step is necessary.) ``` ¿№…ιLθη⪫✂ιLθLι¹ « ``` If one of the first `n` buckets contains `t` then this is a solution in which case output it, otherwise: ``` FLθF² ``` Loop over each bucket and whether it's being emptied or filled. ``` ⊞υ⁺Eι⎇⁼κν∧λ§θκμ⟦§EFλκ⟧ ``` Calculate the new bucket values and append the result with the additional operation. ``` FLθFLθ¿⁻λκ« ``` Loop over each pair of distinct buckets. ``` ≔⌊⟦§ιλ⁻§θκ§ικ⟧ε ``` Calculate the amount that can be poured from one bucket to the other. ``` ⊞υ⁺Eι⎇⁼κν⁺με⎇⁼λν⁻μεμ⟦Pλκ ``` Calculate the new bucket values and append the result with the additional operation. Adding an extra `¿ε` to the beginning of this block does make the code a bit faster but it wasn't significant enough to be able to solve the harder problems on TIO. ]
[Question] [ Given an addition pyramid \$P\$, determine whether it can be solved. An addition pyramid consists of *layers*, each having one number less than the one below it. Layer \$i\$ is symbolized as \$P\_i\$. \$P\_1\$ is the base layer, and \$P\_{i+1}\$ is the layer atop \$P\_i\$. The \$j\$th number of \$P\_i\$ is denoted as \$P\_{i,j}\$. \$P\_{i,1}\$ is the leftmost number of \$P\_i\$, and \$P\_{i,j+1}\$ is the number to the right of \$P\_{i,j}\$. You may visualize \$P\_{i+1,j}\$ residing on top of \$P\_{i,j}\$ and \$P\_{i,j+1}\$ at the middle, hence the name "addition *pyramid*". * \$\forall P\_{i,j},P\_{i,j}\in\mathbb N^\*\$, that is, every number in the pyramid is a non-zero positive integer. * \$\forall i>1,P\_{i,j}=P\_{i-1,j}+P\_{i-1,j+1}\$, that is, every number not on the base layer of the pyramid is the sum of the two numbers below it. * If \$P\_1\$ has \$n\$ numbers, \$P\_i\$ has \$n-i+1\$ numbers, therefore \$P\_{i,n-i+1}\$ is the rightmost number of \$P\_i\$. In simpler terms, each layer has one number less than the layer below it. An *addition pyramid puzzle* \$Q\$ is an addition pyramid with some numbers removed (replaced with \$?\$). Its solution is an addition pyramid \$P\$, where \$\forall Q\_{i,j}\ne{?},P\_{i,j}=Q\_{i,j}\$, that is, the numbers that were originally present in the puzzle have been left unchanged. Such a puzzle may have more than one solution. Your job is, given an addition pyramid puzzle, to determine if it has exactly one solution. ## Input You can get input in any of the following forms, but be consistent: * Array of layers. * Array of layers, shaped like a pyramid using a consistent non-positive-integer value as a separator between elements (used only once each time) as well as left and right padding. The separator and the padding must be the same. * Array of layers with a consistent valid right or left padding (you must be consistent and not mix right and left padding in this case). Please note that a consistent value that's not a strictly positive integer must be used to represent a missing number; this value can't be used as padding. Also, you can take the layers concatenated (you can still separate them), and the ordering can either be from the base to the top or from the top to the base. ## Output One of two consistent distinct values, where one represents the presence of a unique solution and the other the absence of a solution or the presence of more than one solution. ## Rules * \$Q\_{i+1,j}=Q\_{i,j}+Q\_{i,j+1}\$ will always be true if \$Q\_{i,j},Q\_{i,j+1},Q\_{i+1,j}\in\mathbb N^\*\$, that is, the input is guaranteed to not contain a number on top of two other numbers that isn't their sum if all three numbers are known. * \$\exists Q\_{i,j},Q\_{i,j}\ne{?}\$, that is, the pyramid will contain at least one known number. * Don't do [these things](https://codegolf.meta.stackexchange.com/q/1061/41024). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! However, don't let that discourage you from posting a solution just because your language is "too verbose". ## Test cases An array with the layers from the top to the base is used for these test cases, with `0` representing \$?\$. ``` [[10], [0, 0], [0, 2, 0], [0, 0, 0, 1]] -> True [[32], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] -> True [[0], [1, 1]] -> True [[1], [0, 0]] -> False [[10], [5, 5], [2, 3, 2], [0, 0, 0, 0]] -> False [[5], [0, 0], [0, 0, 0]] -> False ``` ## Worked examples The test cases are worked here. ### Unique solution 1 $$\begin{array}c&&&10\\&&?&&?\\&?&&2&&?\\?&&?&&?&&1\end{array}$$ Step 1: \$x+y=2\leftrightarrow x=y=1\$. $$\begin{array}c&&&10\\&&?&&?\\&?&&2&&?\\?&&\color{red}1&&\color{red}1&&1\end{array}$$ Step 2: \$x=y=1\leftrightarrow x+y=2\$. $$\begin{array}c&&&10\\&&?&&?\\&?&&2&&\color{red}2\\?&&1&&1&&1\end{array}$$ Step 3: \$x=y=2\rightarrow x+y=4\$. $$\begin{array}c&&&10\\&&?&&\color{red}4\\&?&&2&&2\\?&&1&&1&&1\end{array}$$ Step 4: \$x+4=10\leftrightarrow x=6\$. $$\begin{array}c&&&10\\&&\color{red}6&&4\\&?&&2&&2\\?&&1&&1&&1\end{array}$$ Steps 5-6 are similar to 4. $$\begin{array}c&&&10\\&&6&&4\\&\color{red}4&&2&&2\\\color{red}3&&1&&1&&1\end{array}$$ So here we have our unique solution. ### Unique solution 2 $$\begin{array}c&&&&&32\\&&&&?&&?\\&&&?&&?&&?\\&&?&&?&&?&&?\\&?&&?&&?&&?&&?\\?&&?&&?&&?&&?&&?\end{array}$$ Step 1: There's no obvious approach here, so let's try using the minimum possible values. $$\begin{array}c&&&&&32\\&&&&?&&?\\&&&?&&?&&?\\&&?&&?&&?&&?\\&?&&?&&?&&?&&?\\\color{red}1&&\color{red}1&&\color{red}1&&\color{red}1&&\color{red}1&&\color{red}1\end{array}$$ Steps 2-5: It looks like the minimum values result in a solution, therefore this is the only solution and is therefore unique. $$\begin{array}c&&&&&32\\&&&&\color{red}{16}&&\color{red}{16}\\&&&\color{red}8&&\color{red}8&&\color{red}8\\&&\color{red}4&&\color{red}4&&\color{red}4&&\color{red}4\\&\color{red}2&&\color{red}2&&\color{red}2&&\color{red}2&&\color{red}2\\1&&1&&1&&1&&1&&1\end{array}$$ Hint: There's a theorem about addition pyramid puzzles related to this puzzle that you can prove if you think hard enough. ### Unique solution 3 $$\begin{array}c&?\\1&&1\end{array}$$ Step 1: \$x=y=1\rightarrow x+y=2\$. $$\begin{array}c&\color{red}2\\1&&1\end{array}$$ This is an obviously unique solution. ### No solution 1 $$\begin{array}c&1\\?&&?\end{array}$$ \$\min\mathbb N^\*=1\rightarrow x,y\ge1\rightarrow x+y\ge2>1\$, so there is no solution. ### No solution 2 $$\begin{array}c&&&10\\&&5&&5\\&2&&3&&2\\?&&?&&?&&?\end{array}$$ Steps 1-2: \$x+y=2\leftrightarrow x=y=1\$. $$\begin{array}c&&&10\\&&5&&5\\&2&&3&&2\\\color{red}1&&\color{red}1&&\color{red}1&&\color{red}1\end{array}$$ From there, it follows that \$1+1=3\$, which is a contradiction, therefore there's no solution. ### Non-unique solution $$\begin{array}c&&5\\&?&&?\\?&&?&&?\end{array}$$ Two solutions: $$\begin{array}c&&5&&&&&&&5\\&2&&3&&&&&3&&2\\1&&1&&2&&&2&&1&&1\end{array}$$ Since there are at least two solutions, there's no unique solution. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 bytes ``` FṀ‘ṗLSƝƬ€Ṗ€a@ċ⁼1 ``` [Try it online!](https://tio.run/##y0rNyan8/9/t4c6GRw0zHu6c7hN8bO6xNY@a1jzcOQ1IJjoc6X7UuMfw/9FJD3fOsH7UMEdB107hUcNc68PtXIfbgSoi//@Pjo420FGAIMNYHQUQzwjIgzLBtKFBbKwOVzSCj@BCEEgQqMkYqBXENNVRMEXXh2akKUTGEGYpnGsA5cYCAA "Jelly – Try It Online") A monadic link that takes the pyramid in reverse order and returns 1 for true and 0 for false. Generates all possible pyramids with a base up to the max number in the pyramid and checks whether there is one unique match for the input. Thanks to @Arnauld for pointing out that this failed for `[[1,0],[0]]`; now corrected. Thanks to @JonathanAlan for saving 2 bytes! ## Explanation ``` F | Flatten Ṁ | Maximum ‘ | Increase by 1 ṗ | Cartesian power of this with: L | - Length of input € | For each: Ƭ | - Repeat the following until no change SƝ | - Sum of neighbours Ṗ€ | Remove last element from each list a@ | Logical and input with each list ċ | Count times input appears ⁼1 | Check if equal to 1 ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~303~~ 227 bytes ``` n=>{int i=n.Max(x=>x.Max()),j=n.Count,t=0,k,m=0,z;for(;t<Math.Pow(i,j);){k=t++;var s=n.Select(_=>(a:k%i+1,k/=i).a).ToList();if(n.All(x=>(z=0,b:x.All(o=>o==s[z++]|o<1),s=s.Skip(1).Select((a,b)=>a+s[b]).ToList()).b))m++;}m/=m-1;} ``` Throws exception if true, runs normally if false. [Try it online!](https://tio.run/##dVJfa9swEH@OP4VeBhJWnXgjL1VO0LV7a2Gsg0JDGIon06ttOVhq6jrzZ89ke53dZQVz1p3u90fSJfYssXi8SByWZnWN1g0BjZNSpnA0IA8@IQgmulE1rUHW/YIx/uhrl@WTcdzBgme88LERaVlR4VY3yj1EX8tnivyRCXbIwIWh2KuKWA@71blOHP0Bkqrz7AOGMc/mgCxSLPpedhYoE5hSE13keSdKG0@@Pa/7vARZAth1E4abX@UqZtyCjW4z3NGYvXJTxbcMpArtersZWVm0ZazwVtpiDsVZLNqjCObzQSj/c1ov1ltFqEc7XWEH@cQBjg5E7Vvfc4CdAxF0BA0Y/bzeHKYxXrScDMsFJ2@Sj//kwxe3LeHBlGJsiv@3Hb8VONke4UtOln8Tr/7Jezg1cEqxfPcIQ3srAj8YWiUPtJ8BgoY0LJi56oUcgtmsKzoCxL5eXgGymDzaN73XldV0Mh4elVLX/@8qdPoajaapyq3uai1JlPNqV7jHn/rzy72uyi91onfdpBPNetUR56qnAXb8DQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~85~~ 88 bytes ``` Count[l=Length@#;NestList[2#~MovingMedian~2&,#,l-1]&/@Range@Max@#~Tuples~l,#/. 0->_]==1& ``` [Try it online!](https://tio.run/##XYxBC4JAEIXv/YpgwdOY7oqnUBa6ZkR1E4nFVl2wLXKNQHb/uqmZSQzMvDffzLsyVfArUyJlbRa0m1stVVwGWy5zVVC03vFKbUWlYoJMdHsKmUf8Ipg0xAIEpY0Ty6EHJnNOI/aiyJzqe8krUwJyVkvXDs9JEGCr3T9EF4zsMKMoscwx7SKaRdO40BfW0CkC7jD7jl2toeP4wz5mRJOZ3fuz5bAg4AHpAfizuJH/Xv/1V03BHtF6ods3 "Wolfram Language (Mathematica) – Try It Online") +3 fixed. Brute force: for all bases with values `1..*(sum of all numbers)*`, see if the resulting pyramid matches the given form, and check if the total number of matches is 1. Takes input as a list of levels, base first, with `0` representing missing numbers. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ZÌLsgãε©.Γü+}¨®š.S*˜O_}OΘ ``` Takes the pyramid layers in upside down order, base to tip (i.e. `[[0,0,0,1],[0,2,0],[0,0],[10]]`). Also, there seems to be a bug somewhere in 05AB1E with `.Γ` inside a map.. The `©...®š` should just be `...yš` for -1 byte.. [Try it online](https://tio.run/##yy9OTMpM/f8/6nCPT3H64cXnth5aqXdu8uE92rWHVhxad3ShXrDW6Tn@8bX@52b8/x8dbaADgoaxOkCWkY4BmAaRhgaxsQA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9WeXhCqL2SwqO2SQpK9v@jDvf4FKcfXnxu66GVeucmH96jXXtoxaF1RxdG6AVHaJ2e4x9f639uxn@d/9HR0QY6IGgYqwNkGekYgGkQaWgQG6ujEB1tCJGDcKBScI4ORMBIx1jHCEib6pgi6YTJQkhTmHEG6MYBObEA). A minor equal-bytes alternative for `©.ΓüO}®š` could be `[Ðg#üO}\)`: [Try it online.](https://tio.run/##yy9OTMpM/f8/6nCPT3H64cXntkYfnpCufHiPf22Mpl6w1uk5/vG1/udm/P8fHW2gA4KGsTpAlpGOAZgGkYYGsbEA) **Explanation:** ``` Z # Get the flattened maximum of the (implicit) input (without popping) Ì # Increase it by 2 L # Create a list in the range [1, max+2] sg # Swap to get the input again, and get the length (amount of layers) ã # Create a cartesian product of this list repeated that many times ε # Map each inner list to: © # Store it in variable `®` (without popping) .Γ # Collect all results until the following doesn't change anymore: ü # Get the pairwise: + # Sums }®š # After we've collected all, prepend the original list `®` .S # Now compare this potential pyramid with the (implicit) input-pyramid # (-1 if a<b; 0 if a==b; 1 if a>b) * # Multiply that with the (implicit) input-pyramid ˜O # Then take the flattened sum _ # And check that this sum equals 0 (1 if truhy; 0 if falsey) }O # After the map, take the sum to get the amount of truthy values Θ # And trutify it (== 1), since we must output distinct values instead of truthy/falsey # (after which the result is output implicitly) ``` [Answer] ## Haskell, 106 bytes ``` z=zipWith a#b=a*b==a*a f x=[1|t<-mapM(\_->[1..sum(sum<$>x)])x,all and$z(z(#))x$iterate(z(+)=<<tail)t]==[1] ``` Takes an upside down pyramid, e.g. `[[0,0,0,1],[0,2,0],[0,0],[10]]`. [Try it online!](https://tio.run/##dUxLCoMwEN17ioG6MG0UY3FnvEHXXaShjKgYGq1oChJ6dxtru@mHYd6b4X0aHC@V1vNsuVX9UZnGw03BcVtwB@jVMHHB7iYLW@wPwekc5oJF0XhrA7eZn09Ekomi1oBd6dvABhtCJl@ZakBTuXdHeJYZVJoYyV2XnFtUHXAorx4A9IPqDPhQgxAxXYZJ6q6Exk9ekMVSfnrZ6vsWXpGfAl3FhO5p4jil6Z/2t3PFVMr5AQ "Haskell – Try It Online") The brute force approach in Haskell: * create all possible base layers `t` (`mapM(\_->[1..sum(sum<$>x)])x`), where the numbers go from 1 to the sum of all numbers in the input pyramid * create a pyramid from `t` (`iterate(z(+)=<<tail)t`) * compare each layer element-wise with the input (`z(z(#))x`). The comparison function `a # b` returns `True` if both numbers are equal or `a` is zero (`a*b==a*a`). * take a `1` for every pyramid that matches and compare the resulting list to the singleton list `[1]`. ]
[Question] [ Two ambassadors at a UN conference want to speak to each other, but unfortunately each one only speaks one language- and they're not the same language. Fortunately, they have access to several translators, who each understand and speak a few languages. Your task is to determine the shortest chain of translators (since you want as little to be lost in translation as possible) that allows the two ambassadors to speak with each other. ## Coding **Input:** two languages as 2-letter lowercase strings (each ambassador's language) and a list of lists of languages (one list per available translator) You may alternatively take in integers instead of 2-letter codes. **Output:** A sequence of translators either by index or value that is any one of the shortest chains of translators that allows the two ambassadors to communicate. If there is no valid chain of translators, the behavior is undefined. (You may crash, output any arbitrary value, or indicate an error) A valid chain of translators is one where the first translator speaks one ambassador's language, the second and subsequent translators share at least one language with the previous translator, and the last translator speaks the other ambassador's language. ## Examples Using zero-based indexing: ``` es, en, [ [es, en] ] ==> [0] en, en, [] ==> [] en, jp, [ [en, zh, ko, de], [jp, ko] ] ==> [0, 1] es, ru, [ [gu, en, py], [po, py, ru], [po, es] ] ==> [2, 1] fr, gu, [ [it, fr, de, es, po, jp], [en, ru, zh, ko], [jp, th, en], [th, gu] ] ==> [0, 2, 3] fr, ru, [ [fr, en], [en, ko, jp], [en, ru] ] ==> [0, 2] de, jp, [ [en, fr], [ko, jp, zh], [fr, po], [es, ko, zh], [de, en, th], [en, es], [de, fr] ] ==> [4, 5, 3, 1] ``` ## Rules and Assumptions * Standard IO rules (use any convenient I/O format) and banned loopholes apply. * You may assume that speaking and understanding languages is perfectly symmetric and that all possible translations between languages are equally efficient. * There is no concept of "close enough" languages. It is not good enough to use Portuguese on one end where Spanish is required, for instance. * If there are multiple shortest translator chains, any one of them will do. * If the ambassadors happen to speak the same language, the translator list should be empty * Which of the ambassadors is the first one doesn't matter; the translator list can be forward or reverse. * Ambassadors only speak one language for the sake of this challenge * Translators speak at least two languages * The 2-letter language codes do not need to correspond with real languages * You may assume there is a valid sequence of translators * If outputting the sequence by value, include the full set of available languages, not just the relevant ones. Happy Golfing! [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~ ~~126~~ ~~120~~ ~~117~~ 113 bytes ``` F=lambda a,b,T,*U:a!=b and min([[t]+F(l,b,T,t,*U)for t in T if(t in U)<(a in t)for l in t-{a}]+[2*T],key=len)or[] ``` [Try it online!](https://tio.run/##dVG9boMwGJzLU3ylCySu1NJ2iUrHPAGZLA9GmIQGjOWYIa367NQ/BAxJGCzr7ri777M4q0PLk77fpjVt8oICRTnK0Gq3oY9pDpQX0FQ8wliR9TaqLak0HZetBAUVhwyqMrK3XfwZUXNRlq3t9fmX/pE1TlYZQUd2TmvG41Zi0heshDKycfEmeJBMdZLD1iINFdGJKc3EQSBkxZWWhuwUIggZ1ycOQH94gkhAZlI@SW8Q38L3sNDPwZzH1pwFCwkaWCs1uEmAJ0jTL8AvCF7JVTPZea77bmwQivPkJ9oBcT8scG3k5ySLnFIa0d7PqZSBHKF7Ow@T0A6Djgmuiy05TbuYUx0u@7zgDtGRi/l1tbfrarMVOMg3cxWO96stQ/wEN92Np9M5o9Po7YYccddFeAO7NTm9rxyWyId1LDqaB5orTbrX@h3Bh16Nebj@Hw "Python 2 – Try It Online") 3 bytes thx to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) Returns a minimal length list of the translators as `set`s of languages, i.e. 'by value', from `T` that allow `a` to talk to `b`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 bytes ``` ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ ``` [Try it online!](https://tio.run/##y0rNyan8///opICjkxQfNa15uKsvywFIpx2b@3DXApVj7Q93LHq4o@vhzmn/Dy/3BkpE/v8fzaUABNFKmSVKOgpKaUUgMiUVRKYWg8iCfBCZVaAUqwNVmZoHEikqBZFVGSAyOx8hC1QJFCkBiwNVwsUhIumlSrFcsf@jo6NBVsXG6igAWSDB2FgA "Jelly – Try It Online") A dyadic link taking the list of translators as the left argument and list of ambassadors (each double-wrapped in a list) as the right argument. Returns a list of translators, each of which is a list of the languages they speak. Thanks to @KevinCruijssen for saving 2 bytes! ### Explanation ``` ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ | A dyadic link taking a list of translators as left argument and a list of ambassadors (double-wrapped in lists) as right argument ŒP | Power set of translators Œ!€ | Permutations of each Ẏ | Tighten, i.e. create a single list of all permutations of any length j@€ | Join the ambassadors with each set of translators $Ƈ | Filter those where: Ạ | all fƝ | the neighbouring pairs have at least one in common Ḣ | Take the first Ḋ | Drop the first ambassador from the start Ṗ | Drop the second ambassador from the end ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 怜€`ʒ²š³ªüå€àP}н ``` Inspired by [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/185552/52210), so make sure to upvote him! Outputs the lists themselves instead of their indices. [Try it online](https://tio.run/##yy9OTMpM/f//8LJHTWuOTgYSCacmHdp0dOGhzYdWHd5zeClQ5PCCgNoLe///j45WSs1T0lEqKgUSVRlAIjtfKVYnWimzBMhOKwISKalAIrUYSBTkA4msArA8kNJRKgFpAOoHCYDZ6aVKsbFcaUVc6aUA) or [verify all test cases](https://tio.run/##TU87TsQwEO1zimhq90hLkQYhbQUNCBRZImid/YFt@VOARMMR4AJQsMWKmgqajbah4gxcJIxnkpBmNH5v3sfGV9dL1R4cw1TbGCZ57cztJIdienRWwGEeDD/O6eEq7W@qYJxnVMBJDCSDom02v4/v@2ccV99PF/vXy922@Wze8N28nD78fLVi91G0ymdKZ2UJyoMApUHKrMNkmitLpEbyfoFjbXDMFEhRwsoywBIX0@U8so0Ae0dH1vAuwMV/ANNQVbtsHgd/F0ch6XIZcK8dBwpuSGoMHvLDouuNAO3YgK25EOk7nmLWI4c@FwUzNf4rqhLf31KvBJCb5XrUhy46kltqLjXYp6/2ZLKVfw). **Explanation:** ``` æ # Get the powerset of the (implicit) input-list of translators # i.e. [["ef","gh","bc"],["bc","ab"],["ef","cd","de"]] # → [[],[["ef","gh","bc"]],[["bc","ab"]],[["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"]],[["bc","ab"],["ef","cd","de"]],[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]]] €œ # Get the permutations of each # → [[[]],[[["ef","gh","bc"]]],[[["bc","ab"]]],[[["ef","gh","bc"],["bc","ab"]],[["bc","ab"],["ef","gh","bc"]]],[[["ef","cd","de"]]],[[["ef","gh","bc"],["ef","cd","de"]],[["ef","cd","de"],["ef","gh","bc"]]],[[["bc","ab"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"]]],[[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"],["bc","ab"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]],[["bc","ab"],["ef","cd","de"],["ef","gh","bc"]],[["ef","cd","de"],["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"],["bc","ab"],["ef","gh","bc"]]]] €` # Flatten each one level down (4D list becomes 3D list) # → [[],[["ef","gh","bc"]],[["bc","ab"]],[["bc","ab"],["ef","gh","bc"]],[["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"]],[["ef","cd","de"],["ef","gh","bc"]],[["ef","gh","bc"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"]],[["bc","ab"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"],["ef","gh","bc"]],[["ef","cd","de"],["ef","gh","bc"],["bc","ab"]],[["bc","ab"],["ef","cd","de"],["ef","gh","bc"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"],["bc","ab"]],[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]]] ʒ # Filter this 3D list by: ²š # Prepend the second input ambassador # i.e. [["bc","ab"],["ef","gh","bc"]] and "ab" # → ["ab",["bc","ab"],["ef","gh","bc"]] ³ª # Append the third input ambassador # i.e. ["ab",["bc","ab"],["ef","gh","bc"]] and "ef" # → ["ab",["bc","ab"],["ef","gh","bc"],"ef"] ü # For each adjacent pair of translator-lists: å # Check for each item in the second list, if it's in the first list # i.e. ["bc","ab"] and ["ef","gh","bc"] → [0,0,1] €à # Then check if any are truthy by leaving the maximum # → 1 P # And then take the product to check if it's truthy for all pairs # i.e. ["ab",["bc","ab"],["ef","gh","bc"],"ef"] → [1,1,1] → 1 }н # After the filter: only leave the first list of translator-lists # i.e. [[["bc","ab"],["ef","gh","bc"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]]] # → [["bc","ab"],["ef","gh","bc"]] # (which is output implicitly as result) ``` [Answer] # JavaScript (ES6), ~~123~~ 121 bytes Expects integers instead of 2-letter codes. ``` (a,b,l)=>((B=g=(m,s,i)=>m>>b&1?B<i||(o=s,B=i):l.map(a=>a.map(M=c=>M|=1<<c)|M&m&&m^(M|=m)&&g(M,[...s,a],-~i)))(1<<a,[]),o) ``` [Try it online!](https://tio.run/##dVFNb6MwFLznV7wT2KpLmv24ZGMqReoxp90b8koOAeIUMAIStdt0/3r2GVNiSPdiYN54Zt5wkCfZxLWq2vtS75JLyi9Esi3LKQ8JWfOMk4I1TOFnEYZbb/G4XqnzmWjesDVXdJkHhayI5KHsXjY85uHmzBerVUzPG6/wvOI3QaCgnpeRDYuCIGiYFOz@r6KUEiRKFgnKNL20SdMCBwwAWwY5BR7C2wwgsgDezIM0l@3GOJqhpCJIdf0k4z05GUBHJ4EK9sE5HMtdkqoy2cEjqLs7WHYjBgpJDww0Pt7e6Q/0iHXZ6DwJcp0R/6c@1nGy9JERSXE7/yXrLGntfPvZvJZlg0F13RgSydGnL6qL3b2@2MAvAmsIDlqVxIc5@PRGLiUmhfUytdwQEHifzUx7xE8aNPSTEs8IaVjeFRIzQWE@x2ZCiB7EcKV0rjiMCeFQuZod9Gdvzmdtzl3iC9ZPO6rBx44MFmKcsz46mtlxyOFXr1e1SveIvTDBUWjk8sV1SWtDyVwX1RrIDjCzVTD6ul9y0LdJuojXTSc7tvuPbj9wi6DldHcM9nUSbLS@hVwpG@D5/8FuLAZ9u9knvwxdBp1B2S444DZJ5SxrK7J8l9kXWPZVTBKaXzNmGnc38zcG37EW88su/wA "JavaScript (Node.js) – Try It Online") ]
[Question] [ ## Introduction Inspired by the very recent video [The Trapped Knight - Numberphile](https://www.youtube.com/watch?v=RGQe8waGJ4w), I came up with a challenge. The [trapped knight sequence](https://oeis.org/A316667) is a finite integer sequence of length 2016, starting from 1, and has the following construction rules: 1. Write a number spiral in the following manner: ``` 17 16 15 14 13 ... 18 5 4 3 12 ... 19 6 1 2 11 ... 20 7 8 9 10 ... 21 22 23 24 25 ... ``` 2. Place a knight on 1. 3. Move the knight to the grid with the smallest number it can go that has not been visited before, according to the rules of chess (i.e. 2 units vertically and 1 unit horizontally, or vice versa). 4. Repeat until the knight gets stuck. Here is the first three steps: **Step 1** ``` 17 [16] 15 [14] 13 [18] 5 4 3 [12] 19 6 < 1> 2 11 [20] 7 8 9 [10] 21 [22] 23 [24] 25 ``` Possible moves are 10, 12, 14, 16, 18, 20, 22, 24, among which the smallest is 10, so the second term is 10. **Step 2** ``` 4 [ 3] 12 [29] 54 ( 1) 2 11 28 [53] 8 9 <10> 27 52 [23] 24 25 26 [51] 46 [47] 48 [49] 50 ``` Possible moves are ~~1~~, 3, 23, 29, 47, 49, 51, 53, among which the smallest is 3, so the third term is 3. **Step 3** ``` 35 [34] 33 [32] 31 [16] 15 14 13 [30] 5 4 < 3> 12 29 [ 6] ( 1) 2 11 [28] 7 [ 8] 9 (10) 27 ``` Possible moves are 6, 8, ~~10~~, 16, 28, 30, 32, 34, among which the smallest is 6, so the fourth term is 6. The sequence stars with: ``` 1 10 3 6 9 4 7 2 5 8 11 14 ... ``` and ends with ``` ... 2099 2284 2477 2096 2281 2474 2675 2884 3101 2880 2467 2084 ``` ## Challenge Write a shortest program or function, receiving an integer in the range `[1, 2016]` (or `[0, 2015]` if 0-indexed is used) as input, output the number at that index in the trapped knight sequence. You can choose to index the sequence with 0-indexed or 1-indexed, but you must specify which indexing scheme you use. ## Test cases (1-indexed) ``` n | s(n) -----+----- 1 | 1 2 | 10 3 | 3 6 | 4 11 | 11 21 | 23 51 | 95 101 | 65 201 | 235 501 | 761 1001 | 1069 2001 | 1925 2016 | 2084 ``` For all possible outputs, please refer to [this page](https://oeis.org/A316667/b316667.txt). ## Winning Criteria The shortest code of each language wins. Restrictions on standard loopholes apply. [Answer] # JavaScript (ES7), ~~182~~ 181 bytes ``` f=(n,[x,y]=[2,1],a=[...Array(4e3)].map((_,n)=>[1,-1].map(s=>(i&1?-s:s)*(i+s*n-(n>0?n:-n)>>1),i=n**.5|0,n-=i*++i)))=>n--?f(n,a.find(([X,Y],j)=>(i=j,(x-X)*(y-Y))**2==4),a,a[i]=[]):i+1 ``` [Try it online!](https://tio.run/##ZdDfasIwFAbw@z1Fr0ZOehJz0j9bC6nsLZRSRlArEZeKHUNh795VNjMwd4f8yPcdzsF@2XFzdqdP4Yftbpp6wzy2F7x2ptVIHVrTSinfzmd7Zfkug05@2BNj7@jBNC2hoN@X0TTMPdNSjPUInLl05F4w36ilr4WHpiFAZzznsvhW6IVxPE0dwJzihVj2c62VvfNbxtoVrjs8wC3RHJBdxGpOvIo1AOfamBzQom3dvGIHtUtp2gx@HI47eRz2rGdJkhBAslgkt@kpQn1HUjFm4WcWYxkwj5BCJ8WdOqCOY4uAVfGIpAKWEeqAOouwCPhSPi5E6o6kyuoB9T9WuoiQ/o6g1Ws@/QA "JavaScript (Node.js) – Try It Online") ### How? A slightly modified version of my answer to the [The Path Of The Wildebeest](https://codegolf.stackexchange.com/q/179157/58563) is definitely shorter (and faster) than that. But I wanted to try a different approach. Incidentally, I think it might be easier to implement this method in *some* esolangs. Algorithm: 1. Initialization: we build the full list of coordinates for the first 4000 squares of the spiral, which is enough to process all moves of the knight before it gets trapped (the highest reached square being \$3199\$). 2. We look for the first square \$(X,Y)\$ such that: $$((x-X)\times(y-Y))^2=4$$ where \$(x,y)\$ are the current coordinates of the knight. The above condition is true only if \$|x-X|=1\$ and \$|y-Y|=2\$, or \$|x-X|=2\$ and \$|y-Y|=1\$, which covers all possible knight moves. 3. We set \$(x,y)=(X,Y)\$ and invalidate the entry in the list so that it's not picked a second time. 4. We either restart at step 2 or return the last index that was found if we're done. --- # [Node.js](https://nodejs.org), 155 bytes ``` n=>(g=(x,y)=>n--?g(Buffer('QHUbcdWJ').map(m=c=>g[i=4*((x+=c%6-2)*x>(y+=c%7-2)*y?x:y)**2,i-=(x>y||-1)*(i**.5+x+y)]|i>m||(H=x,V=y,m=i))|H,V,g[m]=1):m+1)(1,2) ``` [Try it online!](https://tio.run/##ZdBNa8MwDAbg@35FLqOS46Sx89Gl4BR2CrvtsO5QesjSJHjUSWm3EYP/e7bA6kJ9k3jQK6HP6qe61Gd5@gr64dBMrZh6UUAnYKQaRdEHwaaD5@@2bc6weC3fPurD@8sCQ1WdQIlaFN1OioQAjL6oH7OAIxkL0HOzmhu9GdcaCeFUBn@hhTYmYEhAEhKm/uhr3BtZKGOgFCPdCk2VkIimpFva7dReMFwrnyEwynGqh/4yHJvwOHTQgud5DNFbLr25enCQX5FFLsZ2MnYxs5g4yOxO5u7kFrkbm1rM03tkkcXMQW6Rxw6mFlfZ/UEsuiKLsvwO@Q1znjrI/p/Ao6dk@gU "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Xˆ0UF2D(Ÿ0KãʒÄ1¢}εX+}Dε·nàDtyÆ+yO·<.±*->}D¯KßDˆkèU}¯θ ``` Exact port of [my 05AB1E answer for *The Path of the Wildebeest* challenge](https://codegolf.stackexchange.com/a/179168/52210), except with the `3` replaced with a `2`, and a trailing `θ` is added to output the 0-indexed value instead of the entire sequence of the first \$n+1\$ items. [Try it online](https://tio.run/##AVYAqf9vc2FiaWX//1jLhjBVRjJEKMW4MEvDo8qSw4QxwqJ9zrVYK31EzrXCt27DoER0ecOGK3lPwrc8LsKxKi0@fUTCr0vDn0TLhmvDqFV9wq/OuP/Dr/8yMA) or [verify some more test cases](https://tio.run/##yy9OTMpM/e95bsf/iNNtBqFuRi4aR3cYeB9efGrS4RbDQ4tqz22N0K51Obf10Pa8wwtcSioPt2lX@h/abqN3aKOWrl2ty6H13ofnu5xuyz68IrT20Pr/YWWV9koKj9omKSjZR1YeXnF4vc7/aAMdQx0jHVMdQwMdIwMdUyDXAMQCMQ1iAQ) (times out for the largest test cases). **Explanation:** See the explanation in [my linked *The Path of the Wildebeest* answer](https://codegolf.stackexchange.com/a/179168/52210). The only modified parts are the: ``` 2D(Ÿ # Get a list in the range [-2,2]: [-2,-1,0,1,2] ``` and a trailing: ``` θ # Only leave the last item of the list ``` --- EDIT: A port of [*@Arnauld*'s approach in his JavaScript (ES7) answer](https://codegolf.stackexchange.com/a/179201/52210) is (currently): # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~57~~ 56 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0D‚DˆUF64D(ŸãΣ·nàDtyÆ+yO·<.±*->}©ʒX-Pn4Q}¯¡˜2£DˆU}®J¯Jk>θ ``` [Try it online](https://tio.run/##AVoApf9vc2FiaWX/YP8wROKAmkTLhlVGNjREKMW4w6POo8K3bsOgRHR5w4YreU/CtzwuwrEqLT59wqnKklgtUG40UX3Cr8Khy5wywqNEy4ZVfcKuSsKvSms@zrj//zM) or [verify some more test cases](https://tio.run/##AXsAhP9vc2FiaWX/Sc64w5BE/@KAmiVEy4ZVRjY0RCjFuMOjzqPCt27DoER0ecOGK3lPwrc8LsKxKi0@fcKpypJYLVBuNFF9wq/CocucMsKjRMuGVX3CrkrCr0prPv9Wdnk/IiDihpIgIj9ZecOoLP9bMCwxLDIsNSwxMCwyMF0) (times out for the largest test cases). **Explanation:** ``` ‚% # Create a pair of zeros: [0,0] # (by pairing the (implicit) input with itself, # and then using modulo (implicit) input) DˆU # Set both variable `X` to this, and add it to the global_array F # Loop the (implicit) input amount of times: 64D(Ÿ # Create a list in the range [-64,64] ã # Create each possible pair of `x,y`-coordinates Σ·nàDtyÆ+yO·<.±*->} # Sort this list in a spiral © # Save it in the register (without popping) ʒ } # Filter the list of coordinates by: X- # Subtract the coordinate of variable `X` P # Take the product n # Take the square 4Q # Check if its equal to 4 # Since 05AB1E cannot remove inner lists, we use a workaround: ¯¡ # Split this list on each coordinate in the global_array ˜ # Flatten the entire list 2£ # Only leave the first two integers as `x,y`-coordinate # (if 05AB1E could remove inner lists, this would've been `¯Kн` instead) DˆU # Replace variable `X` with this, and add it to the global_array }® # After the loop: push all coordinates sorted in a spiral from the register J # Join each coordinate together to a string ¯J # Push the global_array, and also join them together to a string # (if 05AB1E could index inner lists, both `J` could have been removed) k # Get the index of each item of the global_array in the spiral list > # Increase the 0-indexed index by 1 to make it 1-based θ # And only leave the last one (which is output implicitly) ``` The sorting part `Σ·nàDtyÆ+yO·<.±*->}` is copied from my other answer. This can most likely be golfed though, since we don't need the values of the spiral, but only need to sort the \$x,y\$-coordinates. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~41~~ 37 bytes ``` 62lYLt1=i:"YYw(t5Mf'<@{}'ot_h+)X<y=]) ``` Input is 0-based. [Try it online!](https://tio.run/##y00syfn/38woJ9KnxNA200opMrJco8TUN03dxqG6Vj2/JD5DWzPCptI2VvP/f0MDAwMA "MATL – Try It Online") ]
[Question] [ In the spirit of [Solve the Halting Problem for Befinge](https://codegolf.stackexchange.com/q/99107/61384), let's define another 2D language called *Modilar SNISP*. Modilar SNISP has the following six instructions: * `\` directs the instruction pointer as follows: + if approached from the top, go right; + if approached from the right, go up; + if approached from the bottom, go left; + if approached from the left, go down. * `/` directs the instruction pointer as follows: + if approached from the top, go left; + if approached from the left, go up; + if approached from the bottom, go right; + if approached from the right, go down. * `!` skips over the next instruction. * `@` pushes the IP location and direction onto the call stack. * `#` pops an IP location and direction from the call stack and restores them, then skips over the next instruction. If the call stack is empty, execution halts. * `.` does nothing. The instruction pointer starts at the top left corner going right. If it ever leaves the playfield, execution halts. Modilar SNISP cannot be more powerful than a [PDA](https://en.wikipedia.org/wiki/Pushdown_automaton), because its only source of unbounded storage is a stack (the call stack) with a finite alphabet (the set of all IP (location, direction) pairs). [The halting problem is decidable for PDAs](https://cs.stackexchange.com/q/60052/67841), so this challenge should always be possible. ## The Challenge Your goal is to write a program that takes a matrix of characters representing a Modilar SNISP program and returns one of two distinct outputs depending on whether it halts or not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid program (measured in **bytes**) wins. ## Specifications * The way you take a matrix of character is flexible: a newline-separated string, array of strings, array of arrays of characters, 2d array of characters, flat array of characters with an integer representing width, etc. are all acceptable. The test cases opt for the first of those choices. * You can assume that the input matrix will be rectangular (so you don't have to pad short rows) and will be of nonzero length and width. * You can choose any two distinct outputs, not just truthy/falsy. * You can assume that the input matrix will consist only of valid commands (`\`, `/`, `!`, `@`, `#`, and `.`). * When a command is said to "skip the next instruction," you can assume that there will be a next instruction to skip. In particular, it will never be encountered in circumstances where (1) it lies on the playfield's edge and (2) the IP is moving perpendicular to that edge, such that the "next instruction" after it would lie outside the playfield. ## Test Cases The following snippet can be used to test programs in the language. Note that it is slightly more permissive than the actual specification given here (e.g. it permits characters other than `.` as no-ops). ``` function htmlEscape(t){let i=document.createElement("span");return i.innerText=t,i.innerHTML}function tick(){snisp.tick(),snisp.update()}function run(){runButton.style.display="none",stopButton.style.display="",code.style.display="none",executionArea.style.display="",snisp.initialize(),intervalId=setInterval(tick,INTERVAL_MS)}function stop(){runButton.style.display="",stopButton.style.display="none",code.style.display="",executionArea.style.display="none",clearInterval(intervalId)}let TICKS_PER_SECOND=5,INTERVAL_MS=1e3/TICKS_PER_SECOND,runButton=document.getElementById("run-button"),stopButton=document.getElementById("stop-button"),code=document.getElementById("code"),executionArea=document.getElementById("execution-display"),intervalId,snisp={x:null,y:null,direction:null,callStack:null,stopped:null,playfield:null,padRows:function(){let t=Math.max(...this.playfield.map(t=>t.length));for(let i=0;i<this.playfield.length;i++)this.playfield[i]=this.playfield[i].padEnd(t,".")},initialize:function(){this.x=0,this.y=0,this.direction="right",this.callStack=[],this.stopped=!1,this.playfield=code.value.split("\n"),this.padRows(),this.update()},getCurrentChar:function(){let t=this.playfield[this.y];if(void 0!=t)return t[this.x]},backslashMirror:function(){let t={up:"left",right:"down",down:"right",left:"up"};this.direction=t[this.direction]},slashMirror:function(){let t={up:"right",right:"up",down:"left",left:"down"};this.direction=t[this.direction]},forward:function(){switch(this.direction){case"up":this.y-=1;break;case"down":this.y+=1;break;case"left":this.x-=1;break;case"right":this.x+=1;break;default:throw"direction is invalid"}},pushState:function(){this.callStack.push({x:this.x,y:this.y,direction:this.direction})},restoreState:function(){let t=this.callStack.pop();void 0!=t?(this.x=t.x,this.y=t.y,this.direction=t.direction):this.stopped=!0},tick:function(){if(this.stopped)return;let t=this.getCurrentChar();if(void 0!=t){switch(t){case"\\":this.backslashMirror();break;case"/":this.slashMirror();break;case"!":this.forward();break;case"@":this.pushState();break;case"#":this.restoreState(),this.forward()}this.forward()}else this.stopped=!0},generatePlayfieldHTML:function(t,i){let e=[];for(let n=0;n<this.playfield.length;n++){let s=[],l=this.playfield[n];for(let e=0;e<l.length;e++){let a=htmlEscape(l[e]);e==t&&n==i&&(a='<span class="highlight">'+a+"</span>"),s.push(a)}e.push(s.join(""))}return e.join("<br>")},update:function(){let t=[];for(let i=0;i<this.callStack.length;i++){let e=this.callStack[i];t.push(this.generatePlayfieldHTML(e.x,e.y))}t.push(this.generatePlayfieldHTML(this.x,this.y));let i=t.join("<br><br>");executionArea.innerHTML=i}}; ``` ``` #code{font-family:monospace;}#execution-display{font-family:monospace;white-space:pre;}.highlight{background-color:yellow;} ``` ``` <b>Code:</b><br/><textarea id="code" width="300" height="300"></textarea><br/><button id="run-button" onclick="run()">Run</button><button id="stop-button" onclick="stop()" style="display: none;">Stop</button><br/><div id="execution-display"></div> ``` The ungolfed form can be found [here](https://gist.github.com/Reconcyl/e2cbe9cc55a7cd075f2a1f00b0ae2cba). ### Halting ``` . ``` The smallest program possible. Goes out the right. --- ``` \\ \/ ``` Winds around the program and goes out the top. --- ``` .\./.\ .\!/./ ``` Goes in a loop. Winds through part of the track in two different directions. --- ``` @\!/# .\@/# ``` Uses all six commands. --- ``` @.@.@.@.@.@.@.@.@.# ``` This program's execution time is exponential in the number of repetitions of `@.`, but it still halts. --- ### Non-Halting ``` !/\ .\/ ``` I believe this is the shortest infinite loop. --- ``` @!\\#/@\!\ //@//.#./. .\#.!\./\. #.\!@!\@// /..@.@\/#! \.@.#.\/@. ``` --- This winds around the track, spawning stack frames occasionally, before eventually getting caught in a cycle infinitely generating stack frames. Not all commands are actually used. ``` .!/@.@.@.@.@.\ /.@.@.@.@.@.@/ \@.@.@.@.@.@.\ /.@.@.@.@.@.@/ .@\@.@.@.@.@.\ \.@.@.@.@.@.@/ ``` Keeps creating stack frames, but none of them ever return. [Answer] # [Python 3](https://docs.python.org/3/), ~~639 bytes~~ ~~630 bytes~~ 593 bytes ``` def e(I): m=[(0,-1),(0,1),(1,1),(1,-1)];a=lambda i:(tuple(i[0]),i[1]);b=lambda s,q:s.s==q.s and s.S&q.S==q.S class O():i=[[0,0],2];S=[];A={} def z():d=m[O.i[1]];O.i[0][d[0]]+=d[1] def y():O.i=O.S.pop();z() def x():O.i[1]=[3,2,1,0][O.i[1]] def w():O.i[1]=[2,3,0,1][O.i[1]] def v():O.S+=[[O.i[0][:],O.i[1]]] while 1: p=O();p.s=a(O.i);p.S={a(i)for i in O.S};l=O.A.setdefault(p.s,[]);c=any((b(p,s)for s in l));l+=[p];e=O.i[0];d=not((0<=e[0]<len(I))and(0<=e[1]<len(I[0])))or((x,w,z,v,lambda:len(O.S)==0 or y(),lambda:0)["\\/!@#.".find(I[e[0]][e[1]])]()==1);z() if d!=c:return not c or d ``` [Try it online!](https://tio.run/##hZFBb6swDMfvfIoA0lOi5SXQ3sgiseNOPXAMOdBCtUiU0kLXddM@e59d2pVVrR6IJNg/23877aF/WzfT47GslqSiryzxyEobGvG/MeOw4RqfVzBZVei6WM3LgriE9ru2rqgzkWXcmdgyNb94O75JOtFpvREdKZqSdCL7sxEZGjKPLOqi68iMssRpYyIeWT6xKtPGqhf99e0R1PMJ7lKvzExgcqtwj6wpYbFPugTbwB2AA5@eiUy065YyBZGD62NwAarNlE94DJUu@QZiPyImfMqh5Rvi/URkTyD0rCCx/EwAsn9zdUViGBxpNXSkWmi7oADgMdNfBXVsud4SR1xDING3qkHqi@iqHtIXu7qnEMINjG@hi@ZA6Zy2vDvFdBhTM6ZqKN9aVelBgip1s@4pjZ51Bb/PddXA5TEY9GCKzya8GsbWW0o/@J5/8nc@3E@CXtDCtI4I1IERXjwRM0GeSz8NRSCWDjK@GqxhDaa1zFIIis8zJm5JSl8vkm3V77YNAVFkgQnLY7t1TU8raoAiJBCBB1I878acwxPwy1neh0SeCymuIBx9KR7AKTrDEZrC331S3L4PQF/@qv2osI/NhBIFXHkpUylFCPpHGULhY0vwXYwh9oQZgP4JFSgK6oX@dUSoEjWkDwYqfHntZyRj3OdPhXzc/P9gkHIPPkka0ajq@A8 "Python 3 – Try It Online") I feel like this is more of minified source than golf... I'm sure there's a better way to get there. Program works as a full interpreter for the language. It stops either when: 1. We exit the program 2. We detect we're in a loop. Loop detection is somewhat naive (and memory heavy). Before we evaluate each move, we cache off our current Direction, Position, and Stack. If we see we've come to a position we've been to before, moving the same direction, and our current stack is a super set of a previous stack at this position + direction, then we know we're in a loop and the stack is either growing (or staying constant). Edit 1 - Thanks to [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l) for cutting "pass". Also cut "True". Edit 2 - Lambda-ified some functions. Reduced number of returns. Returns "True" for terminating and "False" for non-terminating. Leveraged existing O class as tracking object, eliminating the need for N class. [Answer] # JavaScript (ES6), ~~258~~ 254 bytes ``` p=>(d=>{for(x=y=r=k=1,s=[],v={};w=[--x,--y,d],c=1<<"\\!@/#".indexOf(q=(p[y]||0)[x]),q&&r&&(e=v[w]?v[w].some(u=>!s.some(t=>u+0==t+0)):1);x+=d>>2,y+=d&3)v[w]=[...s],k=k?c&9?d=c&1?d/4|4*d&12:(d+5)%10:c&4?s.push(w):c&16?(r=s.pop())&&!([x,y,d]=r):c-2:1})(9)|e ``` Expects a non-empty program as an array of strings, where each element represents a line of Modilar SNISP. Outputs `1` if the given program halts, and `0` otherwise. Same logic as [@machina.widmo's answer](https://codegolf.stackexchange.com/a/168997). A few failed attempts at alternative methods led me to conclude that they'd produce longer code anyway! [Try it online!](https://tio.run/##nVRtk5owEP7OrwjHFEPFjVyvnTnvonzp5/4AcEYGoqUqYBI9nPN@u91o1esL4jQOhGyeZ/fZzcYfySZRqcwr3SvKTOynfF/xIc348HVaSlrzLZd8zgNf8Wjsb/jr29MLj3q92u/1tn429lMePD/fxbEdMucO8iIT9bcpXXFaRdvxbtf3onrs@SvXla5LBd9EL@OReYEql4Ku@dBWx0/Nh@tun3Pd7XveIPCe6i7PhsN7f4uz@8kzJB4BgBr7cz4fpe7jKOOpG4wy9rB7@Ji5wf2AZt3P3oegP0jdh5GCaq2@0xcPV8GXEZUcLWVFPc91bRrVvkmAS9zu3Q@CN48@ejuxZ4wsknROyilJlBJS52VBhJSlVIQTtU5ToZS1SSTRuJZitc6loJ0jtuM9WRZ6mOUbURAtlCZpooSyCA4NSss81V9X62RBpzTqQAdrQzDXhv0YR8cnOLMWJMQxMDiicbIZtDFCg3J@4fHw2uDw5@/CaKDY7KznKKbfjA1tk6vDjCrDOsA6jIWMgYOZnSzoywHbJIvPyeiYjI0HRJ@pYERiZMc@mZCBqo2aEK7rmYDNLonGscXeZ84sjATX9k3g3/YPoS@ACahqketJXExOMrBpkizLTbcli3ed45NS5rMcjYst0YmcCS0ykmiSkGUpBUnLZbUQNVq0WFba7GQISXVezEheTPMi14IsyrJSjccUOueSn8ahoeBybI3UEP7JdUKnrQFNiaEh8C1k226SfZNwuMaH9vhg2ttuSoDdVr5WJ6cy/q8T5@DklnTMaDpK/HNvV3HdQ5uLyaEZACxz5/EqWwfxuDZGrMLfV2b/Ew "JavaScript (Node.js) – Try It Online") ## Explanation Similar to the other answer, this function exits with: * `1` if the program halts (e.g. the IP moves off the grid or an empty stack is popped) * `0` if the IP reaches a **position** it has already visited, moving in the same **direction**, and with a **superset** of the stack present in the previous visit. ### Why the same direction? ``` 1 !\/ ``` The above program halts, but hits the same position (character 1), with an identical stack, but from a different direction. ### Why a superset and not merely stack size? ``` ab4 !/@@.\ .\..#/ ``` This also halts, and the IP hits character 4 from a consistent direction four times, with the following stack states (`*` indicates the top of the stack): * size = 2 [a, b]\* * size = 1 [a]\* * size = 1 [b]\* * size = 0 []\* ### How the interpreter works Instructions (`q`) are translated into binary (`c`) as follows (with all other characters, `.` or otherwise, serving as nops): ``` 1 2 4 8 16 \ ! @ / # ``` Direction (`d`) is represented as a bit field: ``` 9 -> right : 1001 1 -> left : 0001 6 -> down : 0110 4 -> up : 0100 ``` Mirrors (`\/`) transform the direction: `\`: 6->9 9->6 4->1 1->4 `d/4 | 4*d&12` `/`: 1->6 6->1 4->9 9->4 `(d+5) % 10` New directions transform the position: `x += d>>2 - 1` `y += d&3 - 1` ### Other global variables * `x`, `y`: IP position * `r`: holds value popped off the stack * `k`: falsy if skipping the next instruction (e.g. from `!#`) * `s`: stack * `v`: caches visited positions, direction, snapshot of stack * `w`: `[x, y, d]`, the value stored on the stack and used as the key value for `v` * `e`: falsy if program does not halt due to a cache match ### Ungolfed ``` p => (d => { // set initial direction and avoid a verbose `return` statement for ( x = y = r = k = 1, s = [], v = {}; w = [--x, --y, d], // decrement positions early so that x,y // do not require a separate assignment to 0 c = 1 << "\\!@/#".indexOf(q = (p[y]||0)[x]), // taking an index of undefined produces an error; using 0 does not q && r && ( e = v[w] ? v[w].some(u => !s.some(t => u+0 == t+0)) // in order to compare two arrays, must coerce to strings : 1 ); x += d>>2, y += d&3 ) v[w] = [...s], // clone stack k = k ? c&9 // if \ or / ? d = c&1 ? d/4 | 4*d&12 : (d+5) % 10 : c&4 // if @ ? s.push(w) : c&16 // if # ? (r = s.pop()) && !([x, y, d] = r) // destructure value in stack if any exists : c-2 // 0 if ! : 1 })(9) | e ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 93 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` ⍬{~1∊∊⍺⍷¨⊂⍵:(⍺,⊂⍵)∇(1↓⍵),⍨⊃⍬(⊂1⌽⍉g)(⊂⍉⊖⌽1⌽g)(⊂2⌽g)((1⌽g)(2⌽g))(⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⎕,0 ``` [Try it online!](https://tio.run/##nZDPSsNAEMbveYose9gE2lmjt55y8Q087iXQEoWQhrYeRPRgobahK4roM4h401IQvPgo8yLtzKbFFPZkEja73/ebf5tVRbd/lRXDfIPz@2qD9uP6NsF5zZ/9Rrv@fcP6Du2qF9G50@xjYqMEZ8@876AlZEqREbkJLn/QLvI4cugC61dSWG2k42YX7ZTmGO8j8xiXa8qnpNEiBYX2k1PX0xxnj67I6sah9p2rPrx0jrjvIKBldFlOBuNJEPbORlkVngQhPZVbVTksu@dZMbkoc0XAaTEeNEZbLPscGISUlqopxUk3@6yNmIRU@kuBCg51nD0pY1SojPZZYEAD22CEBi@SkiMdkdLfB0D79SJSaFcE/F3s3H@YqTBGamqRGa1TrUHSRC5AgqDpDB8kjUco2YwBN2q0FHwt3DIlT703B0L/TeZKtGflZKY9u5egUoeEOSS2 "APL (Dyalog Unicode) – Try It Online") Instead of moving the IP around the grid, we move the grid around the IP, so the current IP is always at the top-left with direction pointing right. Raises an IndexError to indicate halting; no error indicates a non-halting SNISP program. ``` (⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⍵,0} ⍬{~1∊∊⍺⍷¨⊂⍵:(⍺,⊂⍵)∇(1↓⍵),⍨⊃⍬(⊂1⌽⍉g)(⊂⍉⊖⌽1⌽g)(⊂2⌽g)((1⌽g)(2⌽g))(⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⎕,0 ⊂1⍪⍨⎕,0 ⍝ Pass an initial stack: the input padded with 0s on the right and 1s on the bottom ⍝ This lets us treat the program grid as wraparound ⍝ 1 and 0 could be any 2 distinct values not in '#\/!@.' ⍝ They have to be different to differentiate SNISP programs that are symmetric on the main diagonal ⍬ ⍝ Pass an initial stack history {...} ⍝ Inner function: ~1∊∊⍺⍷¨⊂⍵: ⍝ Only continue if the stack is not a prefix of any member of the stack history ⍝ Prefix because the top of the stack is the first element and gives the current direction/position (⍺,⊂⍵)∇ ⍝ Recurse with an appended stack history and an updated stack: g←⊃⍵ ⍝ Pop the current grid off the stack ⍬...⊂1⌽g ⍝ A list of all possible stack changes. Will add to the stack: ⍬ ⍝ #: nothing, so the next step pops the stack ⊂1⌽⍉g ⍝ \: transposed grid, wrap-rotated right by 1; the new IP is 1 unit down ⊂⍉⊖⌽1⌽g ⍝ /: new grid such that the new IP is at the current bottom-left 2⌽g ⍝ !: new grid has IP 2 units to the right (1⌽g)(2⌽g) ⍝ @: push both 1⌽g, which is the same as the '.' instruction, ⍝ and 2⌽g, which is the same as the '!' instruction. ⍝ The 1⌽g will be immediately popped for the next position ⊂1⌽g ⍝ .: Push 1⌽g, which simply moves the IP 1 unit to the right ⌷⍨'#\/!@.'⍳⊃⊃g ⍝ Get the next-grid corresponding to the character under the IP ⍝ If that character is 0 or 1, then the pointer has walked off the edge, ⍝ This causes an IndexError since 7='#\/!@.'⍳1, and the list of ⍝ stack changes has only 6 elements ⍝ If the stack is empty, and there is no current grid, ⍝ then it would also try to get the 7th elements, also raising the IndexError (1↓⍵),⍨⊃ ⍝ Add the next grid to the beginning (top) of the popped stack ``` ]
[Question] [ I posted [this challenge](https://codegolf.stackexchange.com/questions/67600) a while ago, which concerns *how many* elves Santa needs to deliver presents. Due to population increase, Santa is a little more pressed for time this year. Although in the past we operated very asynchronously, we are beginning to experiment with being more and more synchronized. So, Santa needs to know how long it will take him to deliver presents to each region with a given number of elves. The weight of coal hasn't changed over the past two years — it's still heavier than presents, so Santa needs three elves per naughty person in the house, and two elves per nice person in the house. Elves spend all year training for Christmas, so they don't need any rest between deliveries. They can only deliver presents to one house at a time, and must go back Santa's sleigh and collect the next gift before going to the next house. For reasons that I am not at liberty to share, elves do not spend time traveling between Santa's sleigh and houses (but can only travel when Santa's sleigh is on the roof), nor does his sleigh spend time moving from house to house. (Santa's sleigh *does* needs to move from house to house in order to collect fuel, but I'm already saying too much). Elves that are delivering presents need to spend **four seconds**\* each delivering the presents, and Elves that are delivering coal need to spend **five seconds**\* each delivering it (as per Santa Aviation Administration regulations, gloves with coal dust on them must be incinerated immediately upon boarding the sleigh, which takes up some time). Additionally, the houses must be visited in the order they are on the map, from left to right, and elves can not begin delivering presents to other houses until all presents have been delivered to the house they are currently at. If we assumed that Santa had more than enough elves for this region, it would take only as long as it takes to deliver a present to someone on the naughty list, 5 seconds, per house, or 4 seconds per house if everyone is nice. Yet, as opposed to previous seasons, this coming Christmas Santa may not have more than enough elves for each region, so 4 seconds is the absolute minimum amount of time\* that it will take to deliver presents to any given house, unless there are 0 nice people and 0 naughty people in which case it will take 0 seconds. Additionally, if even one of the houses has someone on the naughty list, Santa will need at least three elves. If at least one of the houses has someone on the nice list and none of them have people on the naughty list, Santa will need at least two elves. If none of the houses are in the Christmas spirit, any number of elves (including 0) will takes 0 seconds. On Santa's map, a house is represented by a `*`, and each house is split by a `+`. Santa still uses the same maps as in [the other challenge](https://codegolf.stackexchange.com/questions/67600), but I'll include documentation about them here. There will be a number on either side of the house - the one on the left representing the number of naughty people in the house, and the one on the right representing the number of nice people in the house. If there is no number on one side it is interpreted as a 0. I know it may sound crazy, but some people "don't like Christmas", so sometimes, a house may not have a number on either side of it. One of Santa's maps could look something like this. ``` 1*3+2*+*5+*+4*7 ``` Let's say Santa has nine elves in his sleigh. 1. (0s) The first house has 1 naughty and 3 nice people. Three of the elves deliver coal, taking five seconds, and six deliver presents, taking four seconds. After five seconds, Santa's sleigh moves to the next house 2. (5s) The second house has 2 naughty and 0 nice people. Six of the elves deliver coal, taking five seconds. After five seconds, Santa's sleigh moves to the next house 3. (10s) The third house has 0 naughty and 5 nice people. Eight of the elves go to deliver four presents (the one that is left behind can't deliver a present). After four seconds, all of the elves are back, and two of them go to deliver the other present (the sleigh must wait for the elves to get back before going to the next house), taking another four seconds 4. (18s) The fourth house is not in the Christmas spirit, so has 0 naughty and 0 nice people, and is skipped 5. (18s) The fifth house has 4 naughty and 7 nice people. This gets a bit complicated... I. All nine of the elves go to deliver three gifts of coal (leave t+0s, return t+5s) II. After 5s, they are all back on the sleigh, and three of them go to deliver the last present of coal (leave t+5s, return t+10s) while the other six of them go to deliver three nice presents (leave t+5s, return t+9s). III. After four seconds, six of the elves are back and go to deliver three more nice presents (leave t+9s, return t+13s). IV. One second after they leave, the three elves that were delivering the coal present get back, and two of them leave to deliver the last nice present (leave+10s, return t+14s) 6. (18 + 14 = **32 seconds**) Santa is finished delivering presents to that region. As we can see, it takes Santa a total of **32 seconds** to deliver presents to this region. That was an over-simplified version of one of Santa's maps, though. Normally, Santa's maps have multiple lines, and are in a square shape as to better fit on his list. A normal map might look something like this (a `\n` at the end of each line) ``` 1*2+*+*4+1* 2*4+3*+1*6+* *+*+4*2+1*1 *4+*3+1*+2*3 3*10+2*+*5+* ``` With **26 elves** (or any higher amount), it would take Santa **71 seconds**. With **20 elves**, it would take Santa **76 seconds**. With **15 elves**, it would take Santa **80 seconds**. With **3 elves**, it would take Santa **288 seconds**. With **2 elves** (or any lower amount), it would be **impossible.** Oh, and one more thing — **the order in which the elves deliver presents matters** (because of the time difference of delivering presents naughty/nice people), so your code should **always output the least amount of time that the elves can take delivering presents.** ## Challenge Help Santa determine how long it will take for a given number of elves to deliver presents. **Houses** * A house is represented by a `*` * Houses are split by `+` * The number on the left of the house symbolizes the number of naughty people (no number means 0) * The number on the right symbolizes the number of nice people (no number means 0) * There may be newlines (`\n`) in the input, which should also be handled as a split **Elves** * Santa needs help from **three** elves for naughty people (coal is much heavier than presents), and it will take these elves **five seconds**\* to deliver the presents * Santa needs help from **two** elves for nice people, and it will take these elves **four seconds**\* to deliver the presents * If there is no number on either side of the house, Santa will not visit that house, and therefor it will not take any time (people not in the Christmas spirit don't even deserve coal) **Santa** * Santa must deliver presents to the houses one-by-one * Santa can not move onto the next house until all of the elves are back on the sleigh and all of the presents have been delivered to that house (we don't want to leave elves behind, now do we?) * Santa's sleigh doesn't spend any time traveling from house to house (Again, for reasons which I am not at liberty to share) **What to do** Given a map of a houses and a number of elves, print how long it will take Santa to deliver presents to the houses on the map. **\*** (I may not share the amount of time it takes elves to deliver presents. I can neither confirm nor deny that the times included in this challenge are correct) ## Rules * There are two inputs — the map and the number of elves. The inputs can be either taken as arguments to a function, or from **STDIN** or equivalent. If taking two inputs is impossible in your language, then and only then may you accept the two inputs as a single input string, delimited by some character not normally in an input (not one of `+*\n` or `0-9` — the input string can't be ambiguous) e.g. `,`. * The number of elves will always be a non-negative integer (0 is valid) * The output can either be the return value of a function, or printed to **STDOUT** or equivalent. If it is impossible for Santa to deliver presents to the given region with a given number of elves, you must output a consistent negative number, or a consistent message *without any numbers in it* * Everything printed to **STDERR** will be ignored, so you may not print the result or the error message to **STDERR** * Your program can not crash given an invalid number of elves for a region * The output should be only the total amount of time it will take Santa to deliver the presents with the given number of elves. * The output should always be the least amount of time it takes for the elves to deliver presents * The input will only contain numbers, `+`, `*`, and newlines `\n` (unless you specify another character which the input will include if your language can't take two inputs (look at the first rule)) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/20634) apply ## Test Cases ``` "1*1", 5 elves => 5 "1*1", 3 elves => 9 "1*2", 7 elves => 5 "1*2", 5 elves => 10 "1*2", 3 elves => 13 "2*1", 8 elves => 5 "2*1", 5 elves => 9 "2*1", 3 elves => 14 "1*" , 3 elves => 5 "1*" , 2 elves => (error message) "*1" , 2 elves => 4 "*1" , 0 elves => (error message) "*" , 0 elves => 0 "1*1+1*1", 5 elves => 10 "1*1+1*1", 3 elves => 18 "1*1+*+1*1", 3 elves => 18 "1*2+2*1", 8 elves => 10 "1*2+2*1", 7 elves => 14 "1*2+2*1", 6 elves => 18 "1*2+2*1", 3 elves => 27 "1*2+2*1", 2 elves => (error message) "*+*+*+*", 2 elves => 0 "*+*+*+*", 0 elves => 0 "1*3+2*+*5+*+4*7", 9 elves => 32 ``` (hopefully I got all of that correct) ## Scoring Santa spends every single day always looking at *a lot* of things — all of the presents he's going to deliver, all of the elves he has, all of the houses he's delivering presents to... For Santa, the best Christmas present would be being able to see a little bit of a something. For this reason, **the shortest submission in bytes wins**. ## Leaderboard This is a Stack Snippet that generates both a leaderboard and an overview of winners by language. To ensure 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, in bytes, of your submission If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header ``` ## Language Name, <s>K</s> X + 2 = N bytes ``` ``` var QUESTION_ID=151568;var OVERRIDE_USER=20634;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] # [Ruby](https://www.ruby-lang.org/), ~~433~~ ~~400~~ 392 bytes Well, this one is indeed hard, because it turns out the elf scheduling is NP hard. Also, please be nice, this is my first submission, so I might have missed some obvious optimizations: ``` ->e,h{h.split(/\+|\n/).map{|h|n,g=h.split(?*).map(&:to_i)+[0,0];return-1if(g>0&&e<2)||(n>0&&e<3);([[3,5]]*n+[[2,4]]*g).permutation.map{|j|c=[0]*e;j.map{|q|w,y=q;i=j=0;r=c.map{|x|a=b=0;c[i..e].map{|r|r<=x ?a+=1:p};(t=i+=1).times{c[t-=1]<=x ?b+=1:p};[a,b]};d=r.inject([]){|k,x|k<<j if x[0]>=w;j+=1;k}.min{|a,b|c[a]<=>c[b]};b=d-r[d][1]+1;z=c[d]+y;(b..(b+w-1)).map{|x|c[x]=z}};c.max}.min||0}.sum} ``` [Try it online!](https://tio.run/##dZFfj5pAFMXf/RQTTFyQkQXUasVxu0nbpEkfmmzfRmL4Myqo6MKw4jJ8djsyi6toAwk3v3PPmXuZOHUPx8a3xImoM6PBhgAEjp0Jgct8qSW7dUDlx6nKptGjom2cXc6WLIILVGlP7RLLrRHdzgJFxTrUbSsmNI2jjhHM5cVEb7XI2FQYkyNRdxVLxrgL@7bdjlSMTdjj1ULRdiTepNShwTYSZ4XMQ1i328QKBXhle3hAr1aAQqRbMfIEzpiDXA48HGgasQWMWTxGGXhyVGSMdoUlUxTwUtFOWya5h2kHGXbZ4n60YAe6dmH5KNaCKCQelbGt5GwFM7Yaj0MQzEHG55mgvRVyi7UqtE0Q5YzbmIcdHjbx8CnBRX4nxr6NDVs1rHfk8Vo9WLKrabKr7juGolSTeziz0XtRWKddsjKQMb3QknRTHH0yB3Ea/SUJBcttmpAEArJ@Kz/Zjg9I/AYAMUnSNeUXd3GNmues17LoFU6Fd1IeNDu3VwU6h4EnIP15fnn58V0CIyD9fP71m5fcuEtpAqSHZi6yigcImnmZXoiBAJpwIhKLKZ3SZn5xWCE1SOQ3Gh@7yJLRNiQI@vxV6rALwdcraHI4qHeawj68gdxudC@oWYYOr/1mdbyh39BTQO8qVsB@nZkQ8Iv8hKWbw16d6fVGwfTr1VXj7lCfymmwYU1p/1cz1fPmtbxKGdwsWilfuDK4q/BzzPvKzd9Qy0co@l2h/AfHfw "Ruby – Try It Online") I initially had longer test cases, but because I'm iterating over all possible permutations for the scheduling in some cases it takes to long, so I removed them. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 344 bytes Elf scheduling is more difficult than I thought so this took a little while, and is pretty long. Despite that, this has definitely been my favourite challenge to code golf! ``` (e,d)->{int r=0,x,y,c,p,b,g,m;for(String h:d[0].split("\\+")){d=h.split("\\*",-1);b=new Byte("0"+d[0]);g=new Byte("0"+d[1]);m=-1>>>1;for(y=1;y<=e/3&(x=(e-y*3)/2)>0;c=b/y+(b%y++<1?0:1),p=g/x+(g%x<1?0:1),x=c*5>p*4?c*5:p*4,m=x<m?x:m);for(y=0;b+g>0;b-=c,g-=p){c=e/3<b?e/3:b;x=(e-c*3)/2;p=x<g?x:g;if(c+p<1)return-1;y+=c>0?5:4;}r+=m<y?m:y;}return r;} ``` [Try it online (with all tests)!](https://tio.run/##fVRRj5pAEH7GX7EhuYaFBQG13oGruaZtckl7aWLfznsA3EOvgATWK8T42@3sAneJYtXA7HzffDPOZuY1eAvMXc6y1/WfU74Pk22EoiQoS/Qz2GYH1H4GndFSthlnxUsQMfR4GCgKHFGsiScjaMmLbRZblrXB/kA5DgZKG1TygMPrbbddoxTUtYb59IyCIi4xkkovmjhYCctivkGUIhejZV1yllq7PbdyiOBJpmVWrD1AETErrDwoSgYHGfnkPGMiBZ/sZywqUFhSMimuFPvsNyu5pjq6oxI0gZ9knAMjgu4uABeAaV@E20jd9gIg5YzOEFcmub3UcruyHLsXEWLjizQNMOnzuwSZzhkglQAY9/ntvoDGb1@2ynCuFvyBiqJve1D9v7hrvHepR7tDp70N6dDPgE6vopDXvY72ds6Q3wa1r4K9vRqBrqFPgDLWp0C6gwLcM9ZYd8YN5DYCRzE/ykBpJ@cRZYiik8bIGpvzg5i3gtqkIjWJSE5CEpPUf9kV7WChjbeGIbDKPNmC@mplqBgf1nTz4YFyxb8Macb@oi81Z5pqq4aIwn587oTJ8lNqOvP53JFpaur49Yyy4eiTVlGNmbU@wkMXz20/ouGwNrTwpjaMmbOwPQeTnMbDytDim6rzVDTSJ/NcHy/g7cGbpLSapYvKS3GbwfZDIwbB0KQRiU2a40MkMs7CBTy90JeJI5nYzyE6hujYhz0SGfnMwQXj@yIzoVCDRnN7MfHG/rEwaDqrF6lXgy0JqPCPJ79/V3X303V1ty9ZSZBcd8nbu1nlLOJsjbuFWLByn3C4MLGrWmITK@@2VeOgDJyGTGmnskDqr/vl8ttXFXlI/X7/8ANMGXa5C9WVqiKj1QYDzgQJj0wqHK1F59LdFiaIfMWFRxTRLOvj6R8 "Java (OpenJDK 8) – Try It Online") # Explanation; *Brace yourself: It's a long one* ``` int r=0,x,y,c,p,b,g,m; // Define all the variables I need for(String h:d[0].split("\\+")){ // Split houses on '+' and loop through them d=h.split("\\*",-1); // Split the current house on '*' using the limit // to preserve empty strings. b=new Byte("0"+d[0]); // Parse the naughty (b) and nice (g) people g=new Byte("0"+d[1]); m=-1>>>1; // Initialise minimum time as max integer using // overflow for(y=1;y<=e/3&(x=(e-y*3)/2)>0; // For each number of elves that can concurrently // deliver coal, and still leave enough elves to // deliver presents c=b/y+(b%y++<1?0:1), // Determine the number of runs needed to deliver // all coal using this number of elves p=g/x+(g%x<1?0:1), // Determine the number of runs needed to deliver // all presents using this number of elves x=c*5>p*4?c*5:p*4, // Get the maximum time required for the // delivery of coal or presents m=x<m?x:m); // If this is less than the current minimum time, // set it as the minimum time for(y=0;b+g>0;b-=c,g-=p){ // While there are still people to deliver to; c=e/3<b?e/3:b; // Determine the max amount of coal to deliver x=(e-c*3)/2; // Determine how many presents can be // delivered with the remaining elves. p=x<g?x:g; // If this number is more than nice people // remaining, just use the nice people remaining if(c+p<1)return-1; // If no presents can be delivered, return the // error code (-1) y+=c>0?5:4; // Increase the time by 5 if coal was // delivered, and 4 if only presents } // At the end of each loop (see above) // remove the presents and coal delivered // from the number of naughty and nice houses r+=m<y?m:y; // Increment the total time by which ever // is smaller of the calculated times } return r; // Return the total time ``` *NB: This answer depends on my corrections to the test cases being correct* ]
[Question] [ ## Introduction "Muhuhuhahahah!" The mad scientist laughs. "You're trapped in my own little game!" In front of you is a deadly pit of snakes, while behind you is a bottomless chasm. There's no way out, you're stuck! "Two steps in front of you is the snake pit, and two steps behind you is the chasm. But! Before you move, you MUST write down a sequence of steps, forwards and backwards, and give them to me. But! because I'm feeling a bit *evil* today, I can make you take, instead of every step, every `n`th step, where `n` is less than your sequence length! Choose wisely, now." What's the maximum number of steps you can take before your imminent death? ## Task The intro above is a twist on the [Erdős discrepancy conjecture](https://en.wikipedia.org/wiki/Sign_sequence#Erd.C5.91s_discrepancy_problem), which was recently proven true (if you want to understand more about this, go to [this video](https://www.youtube.com/watch?v=pFHsrCNtJu4), by James Grime - I "stole" the twist question off of him). The answer to the intro is `11` steps, but I won't go too in-depth with a proof. The answer, if the distance between you and the two "dangers" were `3` steps, is `1160` steps, although that isn't validated properly yet. Your task is to make a program that generates the longest sequence of steps you can achieve for a larger `x`, where `x` is the number of steps between you and the two "dangers". Your program must take an input for `x`, and output a valid sequence for that `x`. For the purposes of this challenge, `+` represents a step forward, and `-` represents a step back. So, an output for an input `2` is: ``` +--+-++--++ ``` Which works, no matter what `n` the mad scientist chooses. For our challenge, `x = 5`. **NOTE: This challenge is not a dupe of [this challenge](https://codegolf.stackexchange.com/q/59608/62131) or [this challenge](https://codegolf.stackexchange.com/q/123228/20260), as my challenge focuses on the output, as opposed to the code itself - in other words, it's not a code golf challenge. As well as that, these challenges are based off of `x = 3`, which already has an established upper bound.** ## Rules: * Your entire program should fit into your answer. However, if it doesn't fit, please provide an additional Github repository, or something similar. * You may update both your answer and your program, if you can get a better score via optimising your code - but by doing so, you must update everything in the list below. * In your answer, you must have: + Your program, in its entirety, or a link to a GH repository hosting your code + The amount of steps generated - **this will be your final score**. - You must also **provide an online version of the sequence** in a Pastebin, or something similar. This is so we can check your answer. + The time your final score was last updated, so I don't have to check your history * You may NOT hardcode sequences beforehand. * Your program **must work for all `x`** (where `x` is the number of steps between you and the pit & chasm), but you only need to provide the score for `x = 5`. The answer with the largest score wins! [Answer] # Rust, score=4997216, time=2017-07-12 00:18 UTC This improves on the best result I was able to find in the literature, which was 1148805 (Ronan Le Bras, Carla P. Gomes, Bart Selman, [On the Erdős Discrepancy Problem](https://arxiv.org/abs/1407.2510), 2014), by a factor of 4.3. [Output sequence of length 4997216](https://raw.githubusercontent.com/andersk/discrepancy/38f34b6b9c57bc4f8ff54d1a49a17ec5fb29d893/4.4997216.txt) [Source code on GitHub](https://github.com/andersk/discrepancy) ### Running The program accepts the maximum discrepancy as an argument (this is *x* − 1 in the language of the challenge, to align with the more common mathematical convention). It produces incremental outputs in a slightly compressed format that looks like this for *x* = 3: ``` $ cargo run --release 2 add +--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-+ length 90 delete 12 add --++--+-++-++--+-++--+--+-++--+- length 110 delete 4 add +-+--+-++-++--+-++--+--+-++-++--+-++-+ length 144 delete 6 add --++-++--+-++--+--++++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-+- length 214 delete 208 add --+++--+++--+-+--+++--+-+--+++--++---+-+--+-+-++-+--+++--+++--+---++-+--+-++-+++---++--+-++-++--++--+--++--+++--+-+-++-+--+-+--+++---+++-+----+++--+-++--++-+-++--+-+--+-+-++-+--+++--++--+--+--+-++-++---++-++-++-+--+-++ length 224 delete 2 add -+++--+-+--+++---++--+-- length 246 done ``` where `add` means append a sequence of signs to the end of the current sequence, `delete` means remove some number of signs from the end of the current sequence, and `length` asserts the length of the current sequence. This scheme avoids the production of many gigabytes of intermediate results as longer and longer sequences are discovered. You can extract the best result so far with the following Python program: ``` import sys s = '' for line in sys.stdin: cmd = line.split() if cmd[0] == 'delete': s = s[:-int(cmd[1])] elif cmd[0] == 'add': s += cmd[1] elif cmd[0] == 'length': assert len(s) == int(cmd[1]) print(s) ``` ### How it works There are about a thousand lines of code here, so this is only going to be a very rough overview. We limit the search to [completely multiplicative](https://en.wikipedia.org/wiki/Completely_multiplicative_function) sequences (those with *f*(*a*·*b*) = *f*(*a*)·*f*(*b*)), because that means we need only concern ourselves with bounding the partial sums for *n* = 1, and the partial sums for *n* ≥ 2 will satisfy the same bound automatically. For any substring *f*(*i* + 1), …, *f*(*j*) of a partially assigned sign sequence (so each element is ‘+’, ‘−’, or unknown), define danger+(*i*, *j*) to be twice the number of ‘+’s minus the length *j* − *i* (for convenience, we allow *i* to be as small as −*x* + 2 and assume *f*(−*x* + 3) = ⋯ = *f*(0) = ‘+’ for this purpose). Define danger−(*i*, *j*) similarly. Then the bound on partial sums for *n* = 1 is equivalent to the condition that whenever *i* ≡ *j* ≡ *x* (mod 2), danger+(*i*, *j*) ≤ *x* − 2 and danger−(*i*, *j*) ≤ *x* − 2. We build an incremental data structure that supports constant time queries for the substring with largest danger, with logarithmic time updates. It works by associating four values: * danger(*i*, *j*), * max*i* ≤ *k* ≤ *j* danger(*i*, *k*), * max*i* ≤ *k* ≤ *j* danger(*k*, *j*), and * max*i* ≤ *k* ≤ *l* ≤ *j* danger(*k*, *l*), with every string of length 2, every other string of length 4, every fourth string of length 8, and so on. The values associated with a longer string can be computed in constant time from the values associated with its two halves. This structure, augmented with some auxiliary information, lets us perform constraint propagation and conflict detection on partial sequences very quickly. We use it to do a [CDCL](https://en.wikipedia.org/wiki/Conflict-Driven_Clause_Learning)-like search, with unit propagation, decision levels, and non-chronological backtracking (but without clause learning, for now), for full sequences of longer and longer lengths. At each search step, we make a guess for the earliest unassigned sign. The heuristic used to make this guess is very important for avoiding a lot of backtracking; we use *f*(3·*k*) = −*f*(*k*), *f*(3·*k* + 1) = ‘+’, *f*(3·*k* + 2) = ‘−’. ### Results The discrepancy 0, 1, and 2 searches immediately find the optimal completely multiplicative sequences of length 0, 9, and 246. The discrepancy 3 search gets stuck within seconds at 41319, which is pretty far from the known optimal completely multiplicative sequence of length 127645 found by Le Bras et al., 2014 (and a very slightly longer non-multiplicative extension of [length 130000](http://cgi.csc.liv.ac.uk/%7Ekonev/edp/) found shortly thereafter), but much better than the best known sequence before that of [length 17000](http://cgi.csc.liv.ac.uk/~konev/SAT14/). The discrepancy 4 search improves the longest sequence more or less continually for about five minutes until it gets stuck at 4997216. The best previously known sequence of length 1148805 = 9·127645 was expanded from the discrepancy 3 sequence by replacing every sign *s* with +−−+−++−*s*. As far as I can tell, sequences this long are too hard for a general SAT solver to reasonably improve directly (but maybe you, dear reader, can prove me wrong!). I expect I’ll need to add some kind of clause learning to my program to get past these barriers. ### The sequence as a 2187×2285 bitmap (Click to view at full resolution.) [![the sequence as a 2187×2285 bitmap](https://i.stack.imgur.com/RPRBz.png)](https://i.stack.imgur.com/RPRBz.png) [Answer] # [Haskell](https://www.haskell.org/), score=9020, time=2017-06-09 00:52 UTC ``` f 1="" f n="+-"++do c<-f(n-1)++"-";"-+-++-"++c:"+-" ``` [Try it online!](https://tio.run/##TY07DsIwEER7TjHaytGykVzQBMwJoKIEhKIQY4SziUgQxzf5NHSjeU8zoexfdYwpeVhHtPJQRyzEfG9R7cQbFZsxk9CWhIVnVhWTk5ryqXBoyu54g7koZI/uM5yG90FhaFwCM/rQfqFTojVirY8h/AGzNDDjc5bNVoEZL8XZ5vnmmn4 "Haskell – Try It Online") This scores (9*n* − 1 − 1)⋅11/8 for all *n*. Here are the first few outputs: ``` n=1, length=0: n=2, length=11: +--+-++--+- n=3, length=110: +--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+- n=4, length=1001: +--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+- n=5, length=9020: +--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++-++--+-++-++--+-++--+--+-++--+--+-++-++--+-++--+--+-++--+- ``` ]
[Question] [ A *ballot number*, which we'll label *B*, is the number of ways of arranging the numbers from 1 through B(B+1)/2 into a triangle, such that each row and column is in any increasing order. The first four ballot numbers are: ``` a(0) = 1 a(1) = 1 a(2) = 1 a(3) = 2 ``` `a(3)` is 2, which means that there are 2 ways of arranging the numbers from 1 to `3(3+1)/2 = 6` in such a triangle: ``` 1 1 2 3 or 2 4 4 5 6 3 5 6 ``` See the [OEIS sequence entry](http://oeis.org/A003121) for more details. Your challenge, given a ballot triangle, is to verify its correctness. If it satisfies the conditions of a ballot triangle (rows and columns increasing), you should output how many *other* ways (excluding the one in the input) there are to arrange the triangle correctly. If the input triangle is incorrectly constructed, you should output nothing. Trailing newlines are allowed. ## Input A triangle of numbers, which may or may not be a valid ballot triangle. For example: ``` 1 2 3 4 5 6 1 10 5 9 8 2 7 6 4 3 1 3 2 9 2 11 14 3 5 12 8 1 7 15 13 10 4 6 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ``` ## Output If the input is a valid ballot triangle, the remaining number of ways to arrange the same numbers in a valid ballot triangle. If the input is not a valid ballot triangle, nothing. For example, the inputs above produce these outputs (`<nothing>` is a placeholder for an actual empty output): ``` 1 # the same as a(3)-1 <nothing> <nothing> <nothing> 33591 # the same as a(6)-1 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): as usual, lowest byte-count wins. Tiebreaker is earliest posted. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;Zµ⁼Ṣ€ ẋÇFŒ!ṁ€⁸ÇÐfL’ ``` For valid ballot triangles, run time and memory usage are at least **O(n!)**, where **n** is the number of entries of the triangle. Invalid ones are recognized by crashing, thus printing nothing. [Try it online!](http://jelly.tryitonline.net/#code=O1rCteKBvOG5ouKCrArhuovDh0bFkiHhuYHigqzigbjDh8OQZkzigJk&input=&args=WzFdLCBbMiwgM10sIFs0LCA1LCA2XQ) ### Test run Locally, I was able to verify that **a(4)** is calculated correctly. ``` $ time jelly eun ';Zµ⁼Ṣ€¶ẋÇFŒ!ṁ€⁸ÇÐfL’' '[1],[2,3],[4,5,6],[7,8,9,10]' 11 real 6m9.829s user 6m7.930s sys 0m2.579s ``` ### How it works ``` ;Zµ⁼Ṣ€ Helper link. Argument: T (triangular array) Z Zip/transpose T. ; Concatenate the original and the transposed copy. µ Begin a new monadic chain, with the previous result (R) as argument. Ṣ€ Sort each array in R. ⁼ Test for equality with R. This returns 1 if T is a ballot triangle, 0 if not. ẋÇFŒ!ṁ€⁸ÇÐfL’ Main link. Argument: A (triangular array) Ç Call the helper link with argument A. ẋ Repeat A that many times. This yields an empty array if A is not a ballot triangle. F Flatten the result. Œ! Generate all permutations of the digits of A. ṁ€⁸ Mold each permutation like A, i.e., give it triangular form. This crashes if permutation array is empty. ÇÐf Filter; keep permutations for which the helper link returns 1. L’ Compute the length and decrement it. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes ``` {:{o?}a,?z:2a},?ly+yb:3flw p~c.:laBtybB,.:1& ``` [Try it online!](http://brachylog.tryitonline.net/#code=ezp7bz99YSw_ejoyYX0sP2x5K3liOjNmbHcKcH5jLjpsYUJ0eWJCLC46MSY&input=W1sxXTpbMjozXV0) This runs in double-exponential time, so for truthy testcases you would need to believe me that it theoretically produces the correct result, for triangles with length greater than or equal to `3`. You can still test for falsey testcases, those should terminate rather quickly. [Answer] ## JavaScript (ES6), 143 bytes ``` a=>a.some((b,i)=>b.some((c,j)=>c<b[j-1]||i&&c<a[i-1][j]))?'':(f=n=>n<2||n*f(n-1),g=(n,m=f(n*n+n>>1))=>n<2?m:g(--n,m*f(n)/f(n+n+1)),g(a.length)) ``` Searches the triangle for an invalid entry and then uses a recursive formulation of the formula in OEIS to calculate the result. ]
[Question] [ ![Cheddar](https://raw.githubusercontent.com/vihanb/Cheddar/master/misc/logo_wide.png) [Cheddar](https://github.com/cheddar-lang/Cheddar) is a high-level, functional + object-oriented programming language created by our user [Downgoat](https://codegolf.stackexchange.com/users/40695/downgoat) designed to make programming easier, faster, and more intuitive. What general tips do you have for golfing in Cheddar? I'm looking for ideas which can be applied to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") problems and which are also at least somewhat specific to Cheddar (e.g. "Remove unnecessary whitespace." is not an answer). [Answer] # Use Functionized Properties If you ever use just a property in a function: ``` A->A.long.property(n).foo.bar ``` You can use functionized properties to save some bytes: ``` @.long.property(n).foo.bar ``` You can reference the variable in the functionized property with `$0`. [Answer] ## Use the String Operator for string sequences I'm talking about the **`@"`** operator which does different things, all of which deal with strings. This has quite a bit of uses but this is one of my favorite uses: Take a look at this: ``` @" [103, 111, 97, 116, 115] === "goats" ``` not that useful but the opposite is: ``` @"'goats' === [103, 111, 97, 116, 115] 'goats'.bytes // compare the above too ``` This is especially useful to **generate the alphabet**: ``` 65@"90 // Uppercase Alphabet 97@"122 // Lowercase Alphabet 65@"90+97@"122 // Both cases String.letters // Compare 97@"122 to this ``` [Answer] ## Curry No not red curry (what other curry would you be thinking about ¬\_¬). I mean this type of curry: ``` a->b-> ``` If you have a function taking two arguments. It's shorter to curry than to not: ``` (a,b)-> a->b-> ``` Note: This is only shorter when you have **exactly two** arguments. [Answer] ## Use default arguments Declaring Cheddar variables can be quite the byte-waster: ``` ->{var a=b+1} ``` luckily, you can (ab)use function default values for creating variables: ``` b=a+1->b ``` --- Here are some examples of uses: ``` let f= (a,b=a+1)->b f(5) // 6 let f= a=Math.rand()->a f() // 0.8757450950797647 ``` [Answer] # Use Functionized Operators and Bonding This is a simple one. If you have anything like: ``` i->1+i ``` or any similar operation. You can shorten using functionized operators + bonding: ``` 1&(+) ``` [Answer] # Use the mapping operator The `=>` maps LHS to RHS, due to it's precedence, this also means you can use it with ranges and use it multiple times: ``` a=>f (a).map(f) ``` Additionally: ``` a=>f=>g // This is equivilant to... (a).map(f).map(g) // this ``` ]
[Question] [ ## Challenge Winter is fast approaching with many places receiving the first layers of snow for the 15/16 season, so why don't we break out the snow machines and code ourselves some snow? Given a integer `n` via STDIN, output an ASCII representation Beta's snowflake (as described below) at level `n`. ## Beta's Snowflake The snowflake starts off at level 0 with a single x: ``` x ``` Then, on each corner you add one of these shapes: ``` x xx ``` You add the above shape to a top right corner. For a bottom right corner, rotate it 90° clockwise, for bottom left, 180° clockwise and for top left, 270° clockwise. If you do that, you get the following shape: ``` x x xx xx x xx xx x x ``` Take note of the orientation of the shapes. Carrying on we add more of the shapes to each corner, using the orientation rules described above, to the diagram to get level 2: ``` x x x xxxxxxx xx x x xx xxx xxx xx x xx xxx xxx xx x x xx xxxxxxx x x x ``` Note that the shapes are only added to `x`s with two or more exposed sides (which is referred to as a corner above). The L-shapes may and will overlap for values of `n` greater than 1. For example: If level 0 is: ``` x x ``` Then there must be overlaps in level 1 (indicated with an `o`, do not include the `o` in your output): ``` x o x xxxoxxx x x xxxoxxx x o x ``` Your task is to output this ASCII representation of Beta's snowflake. ## Bonus There will be a 50 rep bonus for the shortest program which, when `n` is negative, outputs the snowflake (at level `n*-1`) as an image or graphically to the screen. You may have a separate programs for the bounty and the main task. ## Winning The shortest program in bytes wins. [Answer] # CJam, ~~88~~ ~~83~~ 82 bytes ``` 1]]{{0f+zW%}8*{YYb_m*{~W$m>fm>}%z:z8Ybff=__1m>\1fm>]:zWf%(\:..|}4*..|}q~*" x"ff=N* ``` [Test it here.](http://cjam.aditsu.net/#code=1%5D%5D%7B%7B0a2*f%2BzW%25%7D4*%7B%5B2%2C_m*%7B~W%24m%3Efm%3E%7D%2F%5Dz%3Az2ffb1ff%3D__1m%3E%5C1fm%3E%5D%3AzWf%25(%5C%3A..%7C%7D4*..%7C%7Dq~*%22%20x%22ff%3DN*&input=3) I think I can save a lot in how I detect where the corners are. But at least I finally know what the next iterations look like: **N = 3**: ``` x x x x xxxxxxxxx xx x x x xx xx xxxxxxx xx xxx x x xxx xx xxx xxx xx xxx x xxx xx xxx xxx xx xxx x x xxx xx xxxxxxx xx xx x x x xx xxxxxxxxx x x x x ``` **N = 4:** ``` x x x x x xxxxxxxxxxx xx x x x x xx xx xxxxxxxxx xx xx xx x x x xx xx xxx xxxxxxx xxx xx xxx x x xxx xx xxx xxx xxx xxx xx xxx x xxx xx xxx xxx xxx xxx xx xxx x x xxx xx xxx xxxxxxx xxx xx xx x x x xx xx xx xxxxxxxxx xx xx x x x x xx xxxxxxxxxxx x x x x x ``` Looking at these, they seem to be a lot more regular than I expected, and some sort of analytic solution which generates them directly might be much shorter. [Answer] # Python 2, 269 bytes Doesn't place the shapes at each corner, but determines whether a character is in the snowflake based on the coordinates. First one corner is generated, and then mirrored around to the full snowflake. ``` i=input() d=2*i+1 s=[x[:]for x in[[0]*d]*d] s[0][0]=1 if i:s[1][1]=1 for j in range(2,d): for v in range(j+1):s[j][v]=s[v][j]=(j+v)%3!=1and j+v<d+i if v>j/2 else j%2==1or j%4+v%2in[0,3] for l in[l[:0:-1]+l for l in s[:0:-1]+s]:print''.join(['X'if n else' 'for n in l]) ``` ]
[Question] [ [![Golf Wars](https://i.stack.imgur.com/0NXzam.png)](https://i.stack.imgur.com/0NXzam.png) [![enter image description here](https://i.stack.imgur.com/1R3Unm.png)](https://i.stack.imgur.com/1R3Unm.png) [Background theme](http://www.youtube.com/watch?v=zt0UuNpUqK4) # Introduction Obi-Wan Kenobi, Qui-Gon Jinn and Darth Maul are about to fight! However, they've all forgotten to bring their respective lightsabers. Write a program or function which, given the string `Jedi` as input, generates an image similar to this\*: [![enter image description here](https://i.stack.imgur.com/9q1xMm.png)](https://i.stack.imgur.com/9q1xMm.png) and given the string `Sith`, generates an image similar to this: [![enter image description here](https://i.stack.imgur.com/JhqyFm.png)](https://i.stack.imgur.com/JhqyFm.png) # Images specifications * Any of the 3 lightsabers (the white blade **including the round edge at the end**(2 round edges for the red one) and **including the handle**) is 900px long (This does **not** include the color gradient around the blade). * The round edge at the end of the blade is a halfcircle (a discrete approximation of it, obviously) with a diameter equal to the width of the blade. * The blade (i.e. the white part of the lightsaber) is 12px wide. * The green and blue lightsabers are separated by 200 px (from the center line of the green blade to the center line of the blue blade). * The handle for all 3 lightsabers is 180px (1/5 of the total length). Therefore the blade itself including the round edge(s) is 720px long for the blue and green lightsabers and 360px long for the two blades of the red lightsaber. * The handle for the blue and green lightsabers is at the bottom of the lightsaber. The handle for the red lightsaber is horizontaly centered. * The length of the gradient from the edge of the white blade to a completely white color is 1.5 \* the width of the blade (e.g. 18px for the linear parts). * The green gradient goes from RGB (0,255,0) to white (255,255,255) (or transparent if it's easier for you to implement). The red gradient goes from (255,0,0) to white, and the blue gradient goes from (0,0,255) to white. * The color of the handle is RGB (128,128,128). * There can be white empty space around the lightsaber(s). # Inputs Either `Sith` or `Jedi` as a string. You can take this string from STDIN, as a function argument, command line parameter, or anything similar. You may assume that the input will always be exactly `Sith` or `Jedi` and nothing else. # Output You must generate an image file containing the image corresponding to the input string. You are relatively free to choose whatever image format you want, as long as it is a [True Color](https://en.wikipedia.org/wiki/Color_depth#True_color_.2824-bit.29) image. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. May the force be with you. --- \* The images in this post are not displayed full size. [Answer] # HTML/CSS solution, ~~765 740~~ 541 bytes ``` <style>[id]:not(:target){display:none}table{width:900px;height:12px;border-spacing:0}td:last-child{border-radius:0 12px 12px 0}#Sith td:first-child{border-radius:12px 0 0 12px}#Sith td{box-shadow:0 0 18px red}#Jedi{transform:rotate(-90deg);margin:350px 0}#Jedi td{box-shadow:0 0 18px #0f0}*+table{margin:200px 0 0 0}#Jedi *+table td{box-shadow:0 0 18px #00f}td:nth-last-child(2){background:#888;width:180px;box-shadow:none!important}</style><div id=Jedi><table><td><td></table><table><td><td></table></div><table id=Sith><td><td><td></table> ``` The recent refactor uses the [`:target` pseudo-class](http://www.w3.org/TR/css3-selectors/#target-pseudo) rather than a `<form>` and Javascript. To enter either input, add it to the end of the URL as a target, e.g. `test.html#Jedi` or `test.html#Sith` Here it is again with whitespace and a few comments: ``` <style> /* hide all but the anchored lightsaber (only lightsabers have ids) */ [id]:not(:target) { display:none } /* tables are lightsabers */ table { width:900px; height:12px; border-spacing:0 } td:last-child { border-radius:0 12px 12px 0 } /* curved tip */ #Sith td:first-child { border-radius:12px 0 0 12px } /* 2nd curved tip */ #Sith td { box-shadow:0 0 18px red } #Jedi { transform:rotate(-90deg); margin:350px 0 } #Jedi td { box-shadow:0 0 18px #0f0 } /* green */ * + table { margin:200px 0 0 0 } /* gap between Jedi lightsabers */ #Jedi * + table td { box-shadow:0 0 18px #00f } /* blue */ /* handles */ td:nth-last-child(2) { background:#888; width:180px; box-shadow:none!important } </style> <div id=Jedi> <table><td><td></table> <table><td><td></table> </div> <table id=Sith><td><td><td></table> ``` The lightsabers are `<table>` elements with one cell per part (blade/handle) that are unhidden via their `id` attributes. The blades are colored with CSS [`box-shadow`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow)s and the Jedi lightsabers undergo a [`transform: rotate()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform). Pictures or it didn't happen (click for full res): [![](https://i.stack.imgur.com/q45Hz.png)](https://i.stack.imgur.com/q45Hz.png) If you add `td{background:#fff}body{background:#000}` to the CSS, you'll get a cool dark view. Tested in Firefox and Chrome (on Linux). Note that this is not at all standards-compliant, as I was trying to shrink the size as much as possible. Thanks to @manatwork for [`border-spacing`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing) and `:target`. ]
[Question] [ In this form of the game Tic-Tac-Chec, the goal is to move chess pieces to get four-in-a-row. Your goal here is to figure out if a position has a winning move. # Rules The rules are similar, but not identical, to those of Tic-Tac-Chec. The board is 4 by 4 squares. Each player has a rook, bishop, knight, and queen. On your turn, you have two options. You can move one of your pieces already on the board, following standard chess rules. Or you can place a piece not already on the board, on any unoccupied place. If you move an existing piece onto an opponent's piece, their piece is taken off the board and returned to them. However, you may not place a new piece on top of an opponent's piece. As soon as one player has all of their pieces in a row (or column, or diagonal), they win. # Challenge Write a full program that accepts a board from STDIN, and outputs whether the white player can win on the next turn. ## Input Four strings of 4 characters each. Each character is either a space or a chess piece. Only rooks, bishops, knights, and queens are used, and at most one of each (per color) may appear. Neither player already has a four-in-a-row. You can choose whether to accept as input the Unicode symbols for the chess pieces, or letters. If you choose letters, `RBKQ` represents white pieces, and `rbkq` represents black pieces. ## Output If the white player can win on the next turn, output `true` or `1`. Otherwise, output `false` or `0`. ## Program Choose a number X. Your program may contain at most X distinct characters, and no character may appear more than X times. ## Winning Lowest X wins. In case of a tie, fewest characters wins. # Examples These examples assume the input uses letters to represent the pieces. ``` rkb RB Q true - the white player can place the knight to complete the bottom row. ----------------------------------- rk RBbQ false - the black bishop prevents the white knight from completing the row. ----------------------------------- rk K RBbQ true - the white knight can capture the black bishop and complete the row. ----------------------------------- rkRB Qb K true - the white rook can move down one to complete the diagonal. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 369 characters, score 28 ``` {Q←(QQ←⍴⍵)[1] R←∨/¨⍵=⊂'RBQK' B←({⍵(⍵[↑(⍳Q),¨¨⊂1--Q-⍳Q])}↑(⍳Q)=⊂⍳Q),{⍵,{⍵[{⍵[(1--1)1]}¨⍳QQ]}¨⍵}(⊂QQ)⍴¨(⍳Q)=⊂⍳Q K←(Q-1)={∨/1↑⍴{(,⍵)/,⍳⍴⍵}⍵}¨B×⊂R 1-∨/K:1-1 K←↑∨/K/B BB←{(,⍵)/,⍳⍴⍵}K×1-R R←↑∨/BB-B←{(,⍵)/,⍳⍴⍵}R×1-K 1-⍴B:⍵[BB]=1↑'' BB←(1-∨/¨'RBQK'=⊂⍵[(,K)/,⍳⍴K])/'RBQK' 'K'=BB:×/∨/¨(⍳1--1)=⊂R∨-R 1-∨/(1-(⍳1--1)='RB'⍳BB)×(=/,{∨/1-×⍵})R∨-R:1-1 ×/(1↑'')=⍵[B--(×⊂R)×⍳-1-∨/R]}↑⍞⍞⍞⍞ ``` [Try it online!](https://tio.run/##7VOxTiMxEK3xV2xnW6y1Z9FF2sZINL7GPl0VbZGAOCQigUKFom0oIETJ6Q6EchUF1XYUAR1Cotn8iX8kzHiSRZzg7j6A1e6sd@a98fNbu3PYUzvHnd7Bt0UYnu0uBi6c/hAOY5jchcm9bOuCefwcVlldQSYPoxPujbOcGQQPICfgaYfTn/CeOZnWFSBHJ1oppzBTyLIpIp1QSIyhHYMAuJa6KHGWmXM0uC8FEJyTIKeuXrdgNooFVj5AeRomAdhApCg8gzijRZT41JWZT4HpmVaIti2tdGyBNExkhhlc0hsN7HyqlScjCG2MegfrEWtxlsmdaeHSjClyFMc5TSBIQV2Rj7QecCC1TSNbyGzpMgeEMa35NCMSmhC9Qp6HnFotCfq@FIHN4cMYOZ@KPEvJIgUegEZJvGgBNBakDjqiWqUEOSURPFPU3Bdl9Pe6uXHLLNZ2WX@/m7AELgreJI6tKaVYrCWva90/a/admjdLnoPuFkdNze//q@aw519q3eTNWtcttdiVYrwQshrz7b1O/4in4fwmfL/Cf4k/b/grTC4wjp/C@HcY3UjY0o/88xZv63UY5YD9uvkl0Z@KyMQtOX6ob8H2yzAcAfg6bSB0APQG@ziMH4fxvw/jMw "APL (Dyalog Unicode) – Try It Online") Character statistics: ``` - 1 B ) ( ⍵ / Q ⍳ R ' ∨ LF K , = ← } { ⊂ × ¨ ⍴ ↑ ] [ ⍞ : 27 26 22 20 20 19 19 18 15 15 14 12 12 12 12 11 10 10 10 9 9 9 8 8 7 7 4 4 chars 28 ``` Decisions made during optimizing the score: * Boolean guard `:` is needed for early returns from a dfn `{}`. Either LF (`\n`) or a statement separator character `⋄` cannot be removed as a side effect. * I didn't try to avoid four letters `RBQK` as avoiding it requires *at least* `⎕A` and the code would get messy. * Removed composition `∘`, reflex/flip `⍨`, and self `⊢` in favor of dfns and explicitly writing down arguments with parentheses. * Removed `≢` (tally) in favor of `⍴` (shape/reshape), as tally = first element of shape, and reshape is unavoidable. * Removed `⍉` (transpose) and `⌽` (reverse/rotate) in favor of explicit indexing `[]` combined with index generator `⍳`. Although there are one-char functions to do the indexing (`⌷`, `⊃`), none is suitable for transpose operation. * Removed `⊃` (first/pick) in favor of `↑` (mix/take), as take is unavoidable and indexing+mix can simulate both uses of `⊃`. * Removed `∧` (logical and) in favor of `×` (times), and `|` (abs/mod) by using the workaround `x∨-x` for `|x` (abs) and explicit membership `∊` (which was removed later) for `x|y` (mod). `⊤` was also removed that way. * Removed `∘.f` in favor of `f⊂` or `f¨⊂`. Similar trick was used to simulate `∊` (membership) and `~` (set minus): `x∊y → ∨/¨x=⊂y`, `x~y → (1-∨/¨x=⊂y)/x` * Removed `⍸` (extract indices of ones) with the workaround `(,x)/,⍳⍴x`. * Removed zero with `1-1`, four by extracting from `⍴⍵`, and `+` with `--`. * Removing blanks in plain code is easy, but this code has `' '`. I avoided it with `1↑''`, which "overtakes" length 1 from an empty string and gives a single blank. (It is a slightly different thing from the literal `' '`, but they are compatible in most cases.) ### Ungolfed with comments ``` { ⍝ 4×4 boolean matrix where 1 means a white piece whites←⍵∊'RBKQ' ⍝ one matrix per a winning position; roughly looks like ⍝ 1 0 0 0 ... 1 1 1 1 ... 1 0 0 0 ⍝ 1 0 0 0 0 0 0 0 0 1 0 0 ⍝ 1 0 0 0 0 0 0 0 0 0 1 0 ⍝ 1 0 0 0 0 0 0 0 0 0 0 1 masks←((⊂,⊂∘⌽)∘.=⍨⍳4),(⊢,⍉¨)(⍳4)⌽¨⊂4 4⍴4↑1 ⍝ 1 if the white is about to win in that specific winning position filter←3=masks{≢⍸⍺∧⍵}¨⊂whites ⍝ No three-in-a-row: return false ~∨/filter:0 ⍝ fetch the mask closest to white's winning mask←(⍸filter)⊃masks ⍝ coordinates of misplaced piece (from) and empty position (to) from←⍸whites>mask to←⍸whites<mask ⍝ No from: the remaining place must be empty ~≢from:' '=⍵[to] ⍝ get the type of the piece to move type←'RBKQ'~⍵[⍸mask] ⍝ Knight: true if 1×2 steps away, ignoring any obstacles 'K'=type:∧/1 2∊|⊃from-to ⍝ two booleans indicating if it can move in diagonals (BQ) or ⍝ cardinal directions (RQ) diag cross←0 2⊤⊃'RB'⍳type ⍝ two booleans indicating if the direction to move is actually ⍝ diagonal or cardinal isdiag←=/|⊃from-to iscross←0∊|⊃from-to ⍝ Not aligned with the piece to move: return false diag cross⍱.∧isdiag iscross:0 ⍝ If aligned, true if all cells between from and to are blanks ∧/' '=¯1↓⍵[from+(×v)×⍳⌈/⊃|v←to-from] }↑{⍞}¨⍳4 ⍝ Take 4 lines of input, format as matrix and pass to function ``` [Answer] # C, 53 distinct chars This uses `"#%&()*+,-./01234569;<=>BKQR[\]acdefghilmnoprstu{|}`, space and newline, distributed as follows: 24×`\n`, 33×, 20×`"`, 2×`#`, 3×`%`, 16×`&`, 46×`(`, 46×`)`, 13×`*`, 12×`+`, 35×`,`, 10×`-`, 2×`.`, 2×`/`, 18×`0`, 9×`1`, 4×`2`, 4×`3`, 4×`4`, 4×`5`, 3×`6`, 3×`9`, 34×`;`, 6×`<`, 46×`=`, 2×`>`, 2×`B`, 2×`K`, 3×`Q`, 2×`R`, 8×`[`, 1×`\`, 8×`]`, 39×`a`, 23×`c`, 5×`d`, 19×`e`, 15×`f`, 1×`g`, 22×`h`, 36×`i`, 5×`l`, 1×`m`, 35×`n`, 9×`o`, 33×`p`, 44×`r`, 20×`s`, 43×`t`, 15×`u`, 8×`{`, 14×`|`, 8×`}`. ``` #include <stdio.h> #include <string.h> int n(char*a,char*e,int i) {int c=0;for(;a<e;)c+=*a++=="\n"[0];return c==i;} int p(char *t, int r, int u) {char h[]=" RBQK";char*p=t+r;char*a;int c=0; for(int i=0;i<=3;++i,p+=u){char*s=strchr(h,*p);if(s&&s==h==0){++c;*s=" "[0];}else{a=p;}} if(c-3)return 0; char o=h[strspn(h, " ")]; p=strchr(t, o); if(p==0)return*a==" "[0]; if(p<a){char*s=p;p=a;a=s;} if(o=="K"[0])return(p-a)==3&&n(a,p,1)||(p-a)==2+5&&n(a,p,1)||(p-a)==9&&n(a,p,2)||(p-a)==11&&n(a,p,2); if((p-a)%5==0||n(a,p,0))return (int)strchr("RQ", o); return((p-a)%4==0&&n(a,p,(p-a)/4)||(p-a)%6==0&&n(a,p,(p-a)/6))&&strchr("BQ",o);} int f(char *t) {for(int i=0;i<4;++i)if(p(t,i,5)||p(t,i*5,1))return 1; return p(t,0,6)||p(t,3,4);} int main() {char t[20];fread(t,19,1,stdin);t[19]=0; if(f(t))puts("true");else puts("false");} ``` ## Explanation ``` #include <stdio.h> #include <string.h> /* count newlines */ int n(char *a, char *e) { int c = 0; for (;a<e;) c += *a++=='\n'; return c; } /* check a single row, column or diagonal */ int p(char *t, int start, int stride) { char h[] = " RBQK"; /* pieces not in line */ char *p = t+start; char *a; int c = 0; for (int i = 0; i <= 3; ++i, p+=stride) { char *s = strchr(h, *p); if (s && s == h == 0) { /* a white piece */ ++c; *s = " "[0]; } else { /* candidate target square */ a = p; } } /* did we find three white pieces in this line? */ if (c != 3) return 0; char o = h[strspn(h, " ")]; p = strchr(t, o); if (p==0) return *a == " "[0]; /* ensure a < p */ if (p < a) { char *s = p; p = a; a = s; } /* knight moves */ if (o == 'K') return (p-a)==3 && n(a,p)==1 || (p-a)==7 && n(a,p)==1 || (p-a)==9 && n(a,p)==2 || (p-a)==11 && n(a,p)==2; /* rook moves */ if ((p-a)%5 == 0 || n(a,p)==0) return 0==strchr("RQ", o)==0; /* bishop moves */ return ((p-a)%4==0 && n(a,p)==(p-a)/4 || (p-a)%6==0 && n(a,p)==(p-a)/6) && strchr("BQ", o); } /* main predicate function */ int f(char *t) { /* try rows and columns */ for (int i = 0; i < 4; ++i) if (p(t, i, 5) || p(t, i*5, 1)) return 1; /* try diagonals */ return p(t, 0, 6) || p(t, 3, 4); } int main() { char t[20]; fread(t, 19, 1, stdin); t[19]=0; if (f(t)) puts("true"); else puts("false"); } ``` It works by looking for a row, column or diagonal containing three of the white pieces; `a` points to the target position (not already containing a white piece). Then the missing piece (`o`) is identified - it's the one we didn't remove from string `h` as we saw it. If the piece is not on the board, it must be in the hand, and it can only be played into a space. Otherwise (if we found it on the board), it must be in a position where it can move into the target square. Since moves are reversible, we swap if necessary, so that `a < p`. We test knight moves first - there are four legal downwards moves, and we avoid wrapping around the left/right edges of the board by verifying the number of newlines we pass. After that, we test rook moves, and then bishop moves, using a similar algorithm (and a queen can use either of these moves). ## Test program ``` int expect_true(char *board) { if (strlen(board) != 19) { fprintf(stderr, "Wrong length board:\n%s\n\n", board); return 1; } if (!f(board)) { fprintf(stderr, "Expected true, but got false, for\n%s\n\n", board); return 1; } return 0; } int expect_false(char *board) { if (strlen(board) != 19) { fprintf(stderr, "Wrong length board:\n%s\n\n", board); return 1; } if (f(board)) { fprintf(stderr, "Expected false, but got true, for\n%s\n\n", board); return 1; } return 0; } int main() { return + expect_true("rkb \n" " \n" " \n" "RB Q") + expect_false("rk \n" " \n" " \n" "RBbQ") + expect_true("rk \n" " K \n" " \n" "RBbQ") + expect_true("rk \n" " \n" "K \n" "RBbQ") + expect_true("rkRB\n" " \n" " Qb \n" "K ") + expect_true("rk \n" " \n" "K \n" "RBbQ"); } ``` ## Counting program (in C++) ``` #include<algorithm> #include<iostream> #include<map> int main() { std::map<char,int> m; for (int c; (c = getchar()) != EOF; ) ++m[c]; for (auto e: m) std::cout << e.first; std::cout << "\n distributed as follows: "; for (auto e: m) std::cout << e.second << "×`" << e.first << "`, "; } ``` ]
[Question] [ This question originates in [this reddit thread](http://www.reddit.com/r/mathriddles/comments/28kgo7/a_centrifuge/) by reddit user taho\_teg but it is expanded to a more general 'puzzle'. You have a centrifuge with 24 holes for the vials uniformly distributed in a circle around the central axis. If you now have a number of vials and you want to start the centrifuge, you need to make sure that they are placed in a balanced manner. The only numbers of vials you cannot balance are 1 and 23. You can for example balance 4 obviously, but you can also balance 5 by making a 'triangle' with 3 vials and placing the other two on two opposite sites. # Goal You have to write a program that accepts the number of holes (that are uniformly distributed in a circle around the rotating axis) of your centrifuge as input, and that outputs a list of numbers of vials that cannot be balanced in the centrifuge. You have to do the calculation and cannot just hardcode the precomputed solutions. Input and output have to be implemented in a way so that the program code does not have to be changed for calling the program for different inputs. It is also acceptable to write a function (or a similar construct in your language) that can be called via a console. Be also aware that if you have 6 holes in your centrifuge, you can centrifuge 2 and 3 vials, but you cannot balance 5 since the 'triangle' and the opposite two will overlap at one point. Another example would be for n=15 you cannot balance 11 vials, you can balance 6 and 5 vials, but the combination of those solutions will overlap (this is of course not yet the criterion that it is impossible to do so). ### Update It seems some people did not understand the given example, so I made a graphic here. **PLEASE** write a short description of how your algorithm works as well as some example outputs for verification. Please include following examples: ``` n = 1, 6, 10, 24, 63, 100 = 10^2, 163 (prime), 40320 = 8!, 65536=2^2^2^2^2, 105953 (prime) ``` Note that 40320 and 65536 will produce huge lists, it will perhaps be a good idea to only indicate the length of those lists. If you know some interesting numbers to add to that list please let me know! The algorithm should work at least up to n = 1'000'000. ![5 vials placed balanced on a 24 hole centrifuge](https://i.stack.imgur.com/JhSW7.png) ### Example outputs: These are some example outputs-but perhaps faulty because I just calculated them manually. ``` 1: 1 2: 1 3: 1,2 4: 1,3 5: 1,2,3,4 6: 1,5 7: 1,2,3,4,5,6 8: 1,3,5,7 9: 1,2,4,5,7,8 10:1,3,7,9 11:1,2,3,4,5,6,7,8,9,10 12:1,11 13:1,2,3,4,5,6,7,8,9,10,11,12 14:1,3,5,9,11,13 15:1,2,4,7,8,11,13,14 ``` ### Hint If you have a centrifuge with *n* holes, and you cannot balance e.g. *6* vials, you will also not be able to blance *n-6* vials - it is basically the same task to balance *m* vials on an empty centrifuge or to balance a filled centrifuge by taking away *m* vials. So you if you have the number *m* in your list you will also have to include *n-m*. [Answer] # Sage – ~~102~~ 104/115 Why use number theory, when there is brute force? ``` v=lambda n:[j for j in range(n+1)if all(sum(e^(i*2*I*pi/n)for i in c)for c in Combinations(range(n),j))] ``` For a given number of vials, this goes over all ways to position the vials and calculates their center of mass by using complex arithmetics. If the center of mass is zero for none of these ways, the number is returned. Unfortunately, this does not work in certain cases (10,14), because Sage fails to simplify some expressions to zero (which may be related to [this bug](http://trac.sagemath.org/ticket/16724)). One could regard this as a flaw of the interpreter and not the program and still say that the algorithm and program are fine. The following 113-character alternative relies on floats instead of symbols and does not suffer from these problems: ``` v=lambda n:[j for j in range(n+1)if all(abs(sum(exp(i*2j*pi/n)for i in c))>1e-9for c in Combinations(range(n),j))] ``` --- Test output of the 113-character version (`for n in range(14): print n,v(n)`): ``` 0 [] 1 [1] 2 [1] 3 [1, 2] 4 [1, 3] 5 [1, 2, 3, 4] 6 [1, 5] 7 [1, 2, 3, 4, 5, 6] 8 [1, 3, 5, 7] 9 [1, 2, 4, 5, 7, 8] 10 [1, 3, 7, 9] 11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 12 [1, 11] 13 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 14 [1, 3, 5, 9, 11, 13] ``` I did not want to wait the runtime for higher `n`. --- This originates from the following Python solution. Exact arithmetics and not having to import some modules is quite something. # Python – ~~173 154~~ 156 ``` from itertools import* from cmath import* v=lambda n:[j for j in range(n+1)if all(abs(sum(exp(i*2j*pi/n)for i in c))>1e-9for c in combinations(range(n),j))] ``` Test output of this variant (`for n in range(24): print n,v(n)`): ``` 0 [] 1 [1] 2 [1] 3 [1, 2] 4 [1, 3] 5 [1, 2, 3, 4] 6 [1, 5] 7 [1, 2, 3, 4, 5, 6] 8 [1, 3, 5, 7] 9 [1, 2, 4, 5, 7, 8] 10 [1, 3, 7, 9] 11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 12 [1, 11] 13 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 14 [1, 3, 5, 9, 11, 13] 15 [1, 2, 4, 7, 8, 11, 13, 14] 16 [1, 3, 5, 7, 9, 11, 13, 15] 17 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] 18 [1, 17] 19 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] 20 [1, 3, 17, 19] 21 [1, 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20] 22 [1, 3, 5, 7, 9, 13, 15, 17, 19, 21] 23 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] 24 [1, 23] ``` I did not want to wait the runtime for higher `n`. [Answer] # Lua - 197 A non brute force method, it creates a list of factors and rules them out. It also rules out numbers that can be gotten with the addition of those factors as long as the greatest factor used is less than the amount of unfilled holes. One is always printed and isn't used in the algorithm. ``` i=io.read("*n")f={}print(1)for z=2,i do x=z if i%x<1 then table.insert(f,1,x)end for q=1,#f do y=f[q]x=x*math.min(1,z%y)while x>=y and x-1~=y and y<=i-z do x=x-y end end if x>0 then print(z)end end ``` Example output: (some put as ranges so I don't exceed the character limit) ``` 1: 1 6: 1,5 10:1,3,7,9 24:1,23 63:1,2,4,5,8,11,13,17,20,22,23,25,26,29,32,34,38,41,44,47,50,53,58,59,61,62 100:1,3,13,23,33,43,53,63,73,83,93,97,99 163:1-162 40320:1,11,13,17,19,29,31,37,41,43,61,71,73,97,113,121,127,139,157,169,179,181,191,193,209,211,221,223,241,251,253,263,269,271,277,281,289,299,307,313,331,337,347,349,353,361,373,377,379,397,401,403,409,421,431,433,437,439,449,461,467,473,479,481,491,493,499,517,521,523,529,533,541,547,571,577,587,589,593,601,607,613,617,619,631,641,653,659,671,673,683,689,691,697,701,703,709,713,731,733,737,739,751,757,761,769,781,793,811,817,841,851,853,857,859,869,871,877,881,883,907,913,929,937,953,961,971,977,979,989,991,997,1003,1009,1019,1021,1027,1033,1037,1039,1049,1051,1069,1073,1079,1081,1093,1121,1133,1139,1151,1153,1163,1171,1177,1181,1189,1193,1201,1213,1217,1223,1237,1243,1249,1261,1271,1273,1277,1279,1289,1291,1297,1301,1303,1321,1331,1333,1357,1361,1363,1369,1373,1381,1387,1409,1417,1429,1441,1451,1453,1457,1459,1469,1471,1481,1483,1489,1501,1511,1513,1531,1537,1553,1567,1579,1597,1601,1609,1619,1621,1633,1643,1649,1651,1661,1663,1681,1691,1693,1697,1699,1709,1711,1717,1721,1723,1741,1751,1753,1777,1793,1801,1807,1819,1837,1849,1859,1861,1871,1873,1889,1891,1901,1903,1921,1931,1933,1937,1949,1951,1957,1961,1963,1969,1991,1993,2011,2017,2027,2029,2033,2041,2047,2053,2057,2059,2077,2081,2087,2089,2101,2113,2129,2137,2143,2161,2171,2173,2197,2207,2209,2221,2227,2237,2239,2251,2257,2269,2273,2281,2297,2311,2321,2353,2369,2381,2419,2431,2449,2461,2477,2491,2503,2509,2521,2531,2533,2537,2539,2549,2551,2557,2561,2563,2581,2591,2593,2617,2633,2641,2647,2659,2677,2689,2699,2701,2707,2713,2717,2719,2729,2731,2749,2753,2759,2761,2773,2801,2809,2827,2833,2843,2857,2867,2869,2879,2881,2893,2897,2899,2909,2911,2917,2921,2923,2929,2941,2951,2953,2971,2977,2993,3001,3007,3019,3037,3041,3049,3061,3071,3083,3089,3091,3103,3121,3131,3133,3149,3151,3161,3169,3179,3181,3187,3193,3211,3217,3229,3233,3251,3253,3257,3259,3277,3281,3289,3293,3301,3313,3317,3319,3329,3341,3347,3359,3361,3371,3373,3377,3379,3389,3391,3397,3401,3403,3421,3431,3433,3457,3473,3481,3487,3499,3517,3529,3539,3541,3551,3553,3569,3571,3581,3583,3601,3611,3613,3623,3629,3631,3637,3641,3649,3659,3667,3673,3691,3697,3707,3709,3713,3721,3733,3737,3739,3757,3761,3763,3769,3781,3791,3793,3797,3799,3809,3821,3827,3833,3839,3841,3851,3853,3859,3877,3881,3883,3889,3893,3901,3907,3931,3937,3947,3949,3953,3961,3967,3973,3977,3979,3991,4001,4013,4019,4031,4033,4043,4049,4051,4057,4061,4063,4069,4073,4093,4097,4103,4117,4129,4153,4159,4171,4177,4187,4189,4201,4211,4213,4223,4237,4241,4243,4253,4267,4273,4283,4297,4301,4303,4309,4313,4321,4331,4337,4339,4363,4369,4379,4381,4387,4393,4409,4411,4427,4429,4433,4441,4447,4453,4463,4469,4471,4477,4481,4493,4499,4511,4513,4517,4523,4537,4541,4553,4561,4577,4601,4607,4609,4619,4621,4637,4649,4661,4673,4691,4703,4717,4721,4733,4751,4757,4769,4787,4793,4801,4811,4813,4817,4829,4841,4853,4859,4877,4883,4889,4897,4901,4913,4919,4939,4957,4961,4973,4979,4997,5003,5009,5017,5021,5027,5041,5051,5053,5057,5059,5069,5071,5077,5081,5083,5101,5111,5113,5137,5153,5161,5167,5179,5197,5209,5219,5221,5231,5233,5249,5251,5261,5263,5281,5291,5293,5303,5309,5311,5317,5321,5329,5339,5347,5353,5371,5377,5387,5389,5393,5401,5413,5417,5419,5437,5441,5443,5449,5461,5471,5473,5477,5479,5489,5501,5507,5513,5519,5521,5531,5533,5539,5557,5561,5563,5569,5573,5581,5587,5611,5617,5627,5629,5633,5641,5647,5653,5657,5659,5671,5681,5693,5699,5711,5713,5723,5729,5731,5737,5741,5743,5749,5753,5771,5773,5777,5779,5791,5797,5801,5809,5821,5833,5851,5857,5881,5899,5917,5921,5939,5941,5951,5953,5963,5969,5981,5983,6001,6011,6023,6029,6031,6037,6049,6059,6061,6067,6073,6091,6107,6109,6113,6121,6131,6133,6137,6157,6161,6163,6169,6173,6191,6193,6197,6199,6221,6227,6233,6239,6241,6253,6257,6259,6277,6281,6283,6289,6301,6313,6331,6337,6347,6353,6361,6367,6373,6379,6401,6413,6431,6443,6449,6451,6457,6463,6469,6473,6481,6491,6493,6497,6499,6509,6511,6521,6523,6529,6541,6551,6553,6571,6577,6593,6611,6613,6617,6619,6631,6637,6641,6649,6667,6673,6689,6697,6721,6731,6733,6737,6739,6749,6751,6757,6761,6763,6781,6791,6793,6817,6833,6841,6847,6859,6877,6889,6899,6901,6911,6913,6929,6931,6941,6943,6961,6971,6973,6983,6989,6991,6997,7001,7009,7019,7027,7033,7051,7057,7067,7069,7073,7081,7093,7097,7099,7117,7121,7123,7129,7141,7151,7153,7157,7159,7169,7181,7187,7193,7199,7201,7211,7213,7219,7237,7241,7243,7249,7253,7261,7267,7291,7297,7307,7309,7313,7321,7327,7333,7337,7339,7351,7361,7373,7379,7391,7393,7403,7409,7411,7417,7421,7423,7429,7433,7451,7453,7457,7459,7471,7477,7481,7489,7501,7513,7531,7537,7561,7571,7573,7577,7579,7589,7591,7597,7601,7603,7627,7633,7649,7657,7673,7681,7691,7697,7699,7709,7711,7717,7723,7729,7739,7741,7747,7753,7757,7759,7769,7771,7789,7793,7799,7801,7813,7841,7853,7859,7871,7873,7883,7891,7897,7901,7909,7913,7921,7933,7937,7943,7957,7963,7969,7981,7991,7993,7997,7999,8009,8011,8017,8021,8023,8041,8051,8053,8077,8081,8083,8089,8093,8101,8107,8129,8137,8149,8161,8177,8191,8203,8209,8219,8221,8233,8243,8257,8269,8273,8287,8299,8317,8327,8329,8333,8341,8353,8363,8369,8371,8377,8401,8411,8413,8417,8419,8437,8441,8443,8459,8461,8467,8473,8479,8497,8501,8503,8509,8513,8531,8537,8543,8557,8563,8569,8579,8581,8587,8593,8597,8599,8609,8611,8641,8651,8653,8657,8669,8671,8677,8681,8683,8689,8717,8723,8737,8747,8749,8753,8761,8767,8773,8777,8779,8797,8801,8803,8809,8821,8833,8849,8857,8881,8917,8921,8923,8929,8933,8941,8947,8971,8977,8989,8993,9001,9017,9041,9043,9049,9053,9061,9067,9073,9083,9089,9091,9097,9101,9103,9109,9113,9133,9137,9143,9157,9169,9197,9203,9209,9217,9227,9229,9241,9253,9257,9259,9277,9281,9287,9301,9307,9313,9337,9341,9343,9349,9353,9361,9367,9389,9397,9409,9419,9421,9427,9433,9437,9439,9449,9451,9469,9473,9479,9481,9493,9517,9521,9523,9529,9533,9547,9553,9577,9589,9601,9617,9631,9643,9649,9659,9661,9673,9683,9697,9707,9713,9727,9739,9757,9761,9763,9769,9773,9781,9787,9809,9817,9829,9841,9857,9871,9883,9889,9899,9901,9913,9923,9937,9949,9953,9967,9979,9997,10001,10009,10013,10021,10027,10033,10049,10057,10069,10081,10091,10093,10097,10099,10109,10111,10117,10121,10123,10141,10151,10153,10177,10193,10201,10207,10219,10237,10249,10259,10261,10271,10273,10289,10291,10301,10303,10321,10331,10333,10343,10349,10351,10357,10361,10369,10379,10387,10393,10411,10417,10427,10429,10433,10441,10453,10457,10459,10477,10481,10483,10489,10501,10511,10513,10517,10519,10529,10541,10547,10553,10559,10561,10571,10573,10579,10597,10601,10603,10609,10613,10621,10627,10651,10657,10667,10669,10673,10681,10687,10693,10697,10699,10711,10721,10733,10739,10751,10753,10763,10769,10771,10777,10781,10783,10789,10793,10811,10813,10817,10819,10831,10837,10841,10849,10861,10873,10891,10897,10921,10931,10933,10937,10939,10949,10951,10957,10961,10963,10987,10993,11009,11017,11033,11041,11051,11057,11059,11069,11071,11077,11083,11089,11099,11101,11107,11113,11117,11119,11129,11131,11149,11153,11159,11161,11173,11201,11213,11219,11231,11233,11243,11251,11257,11261,11269,11273,11281,11293,11297,11303,11317,11323,11329,11341,11351,11353,11357,11359,11369,11371,11377,11381,11383,11401,11411,11413,11437,11441,11443,11449,11453,11461,11467,11489,11497,11509,11521,11531,11533,11537,11539,11549,11551,11561,11563,11569,11581,11591,11593,11611,11617,11633,11647,11659,11677,11681,11689,11699,11701,11713,11723,11729,11731,11741,11743,11761,11771,11773,11777,11779,11789,11791,11797,11801,11803,11821,11831,11833,11857,11873,11881,11887,11899,11917,11929,11939,11941,11951,11953,11969,11971,11981,11983,12001,12011,12013,12017,12029,12031,12037,12041,12043,12049,12071,12073,12091,12097,12107,12109,12113,12121,12127,12133,12137,12139,12157,12161,12167,12169,12181,12193,12209,12217,12223,12241,12251,12253,12277,12287,12289,12301,12307,12317,12319,12331,12337,12349,12353,12361,12377,12391,12401,12433,12449,12461,12499,12511,12529,12541,12557,12571,12583,12589,12601,12611,12613,12617,12619,12629,12631,12637,12641,12643,12661,12671,12673,12697,12713,12721,12727,12739,12757,12769,12779,12781,12787,12793,12797,12799,12809,12811,12829,12833,12839,12841,12853,12881,12889,12907,12913,12923,12937,12947,12949,12959,12961,12973,12977,12979,12989,12991,12997,13001,13003,13009,13021,13031,13033,13051,13057,13073,13081,13087,13099,13117,13121,13129,13141,13151,13163,13169,13171,13183,13201,13211,13213,13229,13231,13241,13249,13259,13261,13267,13273,13291,13297,13309,13313,13331,13333,13337,13339,13357,13361,13369,13373,13381,13393,13397,13399,13409,13421,13427,13439,13441,13451,13453,13457,13459,13469,13471,13477,13481,13483,13501,13511,13513,13537,13553,13561,13567,13579,13597,13609,13619,13621,13631,13633,13649,13651,13661,13663,13681,13691,13693,13703,13709,13711,13717,13721,13729,13739,13747,13753,13771,13777,13787,13789,13793,13801,13813,13817,13819,13837,13841,13843,13849,13861,13871,13873,13877,13879,13889,13901,13907,13913,13919,13921,13931,13933,13939,13957,13961,13963,13969,13973,13981,13987,14011,14017,14027,14029,14033,14041,14047,14053,14057,14059,14071,14081,14093,14099,14111,14113,14123,14129,14131,14137,14141,14143,14149,14153,14171,14173,14177,14179,14191,14197,14201,14209,14221,14233,14251,14257,14281,14291,14293,14297,14299,14309,14311,14317,14321,14323,14347,14353,14369,14377,14393,14401,14411,14417,14419,14429,14431,14437,14443,14449,14459,14461,14467,14473,14477,14479,14489,14491,14509,14513,14519,14521,14533,14561,14573,14579,14591,14593,14603,14611,14617,14621,14629,14633,14641,14653,14657,14663,14677,14683,14689,14701,14711,14713,14717,14719,14729,14731,14737,14741,14743,14761,14771,14773,14797,14801,14803,14809,14813,14821,14827,14849,14857,14869,14881,14891,14893,14897,14899,14909,14911,14921,14923,14929,14941,14951,14953,14971,14977,14993,15007,15019,15037,15041,15049,15059,15061,15073,15083,15089,15091,15101,15103,15121,15131,15133,15137,15139,15149,15151,15157,15161,15163,15181,15191,15193,15217,15233,15241,15247,15259,15277,15289,15299,15301,15311,15313,15329,15331,15341,15343,15361,15371,15373,15377,15389,15391,15397,15401,15403,15409,15431,15433,15451,15457,15467,15469,15473,15481,15487,15493,15497,15499,15517,15521,15527,15529,15541,15553,15569,15577,15583,15601,15611,15613,15637,15647,15649,15661,15667,15677,15679,15691,15697,15709,15713,15721,15737,15751,15761,15793,15809,15821,15859,15871,15889,15901,15917,15931,15943,15949,15961,15971,15973,15977,15979,15989,15991,15997,16001,16003,16021,16031,16033,16057,16073,16081,16087,16099,16117,16129,16139,16141,16147,16153,16157,16159,16169,16171,16189,16193,16199,16201,16213,16241,16249,16267,16273,16283,16297,16307,16309,16319,16321,16333,16337,16339,16349,16351,16357,16361,16363,16369,16381,16391,16393,16411,16417,16433,16441,16447,16459,16477,16481,16489,16501,16511,16523,16529,16531,16543,16561,16571,16573,16589,16591,16601,16609,16619,16621,16627,16633,16651,16657,16669,16673,16691,16693,16697,16699,16717,16721,16729,16733,16741,16753,16757,16759,16769,16781,16787,16799,16801,16811,16813,16817,16819,16829,16831,16837,16841,16843,16861,16871,16873,16897,16913,16921,16927,16939,16957,16969,16979,16981,16991,16993,17009,17011,17021,17023,17041,17051,17053,17063,17069,17071,17077,17081,17089,17099,17107,17113,17131,17137,17147,17149,17153,17161,17173,17177,17179,17197,17201,17203,17209,17221,17231,17233,17237,17239,17249,17261,17267,17273,17279,17281,17291,17293,17299,17317,17321,17323,17329,17333,17341,17347,17371,17377,17387,17389,17393,17401,17407,17413,17417,17419,17431,17441,17453,17459,17471,17473,17483,17489,17491,17497,17501,17503,17509,17513,17533,17537,17543,17557,17569,17593,17599,17611,17617,17627,17629,17641,17651,17653,17663,17677,17681,17683,17693,17707,17713,17723,17737,17741,17743,17749,17753,17761,17771,17777,17779,17803,17809,17819,17821,17827,17833,17849,17851,17867,17869,17873,17881,17887,17893,17903,17909,17911,17917,17921,17933,17939,17951,17953,17957,17963,17977,17981,17993,18001,18017,18041,18047,18049,18059,18061,18077,18089,18101,18113,18131,18143,18157,18161,18173,18191,18197,18209,18227,18233,18241,18251,18253,18257,18269,18281,18293,18299,18317,18323,18329,18337,18341,18353,18359,18379,18397,18401,18413,18419,18437,18443,18449,18457,18461,18467,18481,18491,18493,18497,18499,18509,18511,18517,18521,18523,18541,18551,18553,18577,18593,18601,18607,18619,18637,18649,18659,18661,18671,18673,18689,18691,18701,18703,18721,18731,18733,18743,18749,18751,18757,18761,18769,18779,18787,18793,18811,18817,18827,18829,18833,18841,18853,18857,18859,18877,18881,18883,18889,18901,18911,18913,18917,18919,18929,18941,18947,18953,18959,18961,18971,18973,18979,18997,19001,19003,19009,19013,19021,19027,19051,19057,19067,19069,19073,19081,19087,19093,19097,19099,19111,19121,19133,19139,19151,19153,19163,19169,19171,19177,19181,19183,19189,19193,19211,19213,19217,19219,19231,19237,19241,19249,19261,19273,19291,19297,19321,19339,19357,19361,19379,19381,19391,19393,19403,19409,19421,19423,19441,19451,19463,19469,19471,19477,19489,19499,19501,19507,19513,19531,19547,19549,19553,19561,19571,19573,19577,19597,19601,19603,19609,19613,19631,19633,19637,19639,19661,19667,19673,19679,19681,19693,19697,19699,19717,19721,19723,19729,19741,19753,19771,19777,19787,19793,19801,19807,19813,19819,19841,19853,19871,19883,19889,19891,19897,19903,19909,19913,19921,19931,19933,19937,19939,19949,19951,19961,19963,19969,19981,19991,19993,20011,20017,20033,20051,20053,20057,20059,20071,20077,20081,20089,20107,20113,20129,20137,20161,20171,20173,20177,20179,20189,20191,20197,20201,20203,20221,20231,20233,20257,20273,20281,20287,20299,20317,20329,20339,20341,20351,20353,20369,20371,20381,20383,20401,20411,20413,20423,20429,20431,20437,20441,20449,20459,20467,20473,20491,20497,20507,20509,20513,20521,20533,20537,20539,20557,20561,20563,20569,20581,20591,20593,20597,20599,20609,20621,20627,20633,20639,20641,20651,20653,20659,20677,20681,20683,20689,20693,20701,20707,20731,20737,20747,20749,20753,20761,20767,20773,20777,20779,20791,20801,20813,20819,20831,20833,20843,20849,20851,20857,20861,20863,20869,20873,20891,20893,20897,20899,20911,20917,20921,20929,20941,20953,20971,20977,21001,21011,21013,21017,21019,21029,21031,21037,21041,21043,21067,21073,21089,21097,21113,21121,21131,21137,21139,21149,21151,21157,21163,21169,21179,21181,21187,21193,21197,21199,21209,21211,21229,21233,21239,21241,21253,21281,21293,21299,21311,21313,21323,21331,21337,21341,21349,21353,21361,21373,21377,21383,21397,21403,21409,21421,21431,21433,21437,21439,21449,21451,21457,21461,21463,21481,21491,21493,21517,21521,21523,21529,21533,21541,21547,21569,21577,21589,21601,21617,21631,21643,21649,21659,21661,21673,21683,21697,21709,21713,21727,21739,21757,21767,21769,21773,21781,21793,21803,21809,21811,21817,21841,21851,21853,21857,21859,21877,21881,21883,21899,21901,21907,21913,21919,21937,21941,21943,21949,21953,21971,21977,21983,21997,22003,22009,22019,22021,22027,22033,22037,22039,22049,22051,22081,22091,22093,22097,22109,22111,22117,22121,22123,22129,22157,22163,22177,22187,22189,22193,22201,22207,22213,22217,22219,22237,22241,22243,22249,22261,22273,22289,22297,22321,22357,22361,22363,22369,22373,22381,22387,22411,22417,22429,22433,22441,22457,22481,22483,22489,22493,22501,22507,22513,22523,22529,22531,22537,22541,22543,22549,22553,22573,22577,22583,22597,22609,22637,22643,22649,22657,22667,22669,22681,22693,22697,22699,22717,22721,22727,22741,22747,22753,22777,22781,22783,22789,22793,22801,22807,22829,22837,22849,22859,22861,22867,22873,22877,22879,22889,22891,22909,22913,22919,22921,22933,22957,22961,22963,22969,22973,22987,22993,23017,23029,23041,23057,23071,23083,23089,23099,23101,23113,23123,23137,23147,23153,23167,23179,23197,23201,23203,23209,23213,23221,23227,23249,23257,23269,23281,23297,23311,23323,23329,23339,23341,23353,23363,23377,23389,23393,23407,23419,23437,23441,23449,23453,23461,23467,23473,23489,23497,23509,23521,23531,23533,23537,23539,23549,23551,23557,23561,23563,23581,23591,23593,23617,23633,23641,23647,23659,23677,23689,23699,23701,23711,23713,23729,23731,23741,23743,23761,23771,23773,23783,23789,23791,23797,23801,23809,23819,23827,23833,23851,23857,23867,23869,23873,23881,23893,23897,23899,23917,23921,23923,23929,23941,23951,23953,23957,23959,23969,23981,23987,23993,23999,24001,24011,24013,24019,24037,24041,24043,24049,24053,24061,24067,24091,24097,24107,24109,24113,24121,24127,24133,24137,24139,24151,24161,24173,24179,24191,24193,24203,24209,24211,24217,24221,24223,24229,24233,24251,24253,24257,24259,24271,24277,24281,24289,24301,24313,24331,24337,24361,24371,24373,24377,24379,24389,24391,24397,24401,24403,24427,24433,24449,24457,24473,24481,24491,24497,24499,24509,24511,24517,24523,24529,24539,24541,24547,24553,24557,24559,24569,24571,24589,24593,24599,24601,24613,24641,24653,24659,24671,24673,24683,24691,24697,24701,24709,24713,24721,24733,24737,24743,24757,24763,24769,24781,24791,24793,24797,24799,24809,24811,24817,24821,24823,24841,24851,24853,24877,24881,24883,24889,24893,24901,24907,24929,24937,24949,24961,24971,24973,24977,24979,24989,24991,25001,25003,25009,25021,25031,25033,25051,25057,25073,25087,25099,25117,25121,25129,25139,25141,25153,25163,25169,25171,25181,25183,25201,25211,25213,25217,25219,25229,25231,25237,25241,25243,25261,25271,25273,25297,25313,25321,25327,25339,25357,25369,25379,25381,25391,25393,25409,25411,25421,25423,25441,25451,25453,25457,25469,25471,25477,25481,25483,25489,25511,25513,25531,25537,25547,25549,25553,25561,25567,25573,25577,25579,25597,25601,25607,25609,25621,25633,25649,25657,25663,25681,25691,25693,25717,25727,25729,25741,25747,25757,25759,25771,25777,25789,25793,25801,25817,25831,25841,25873,25889,25901,25939,25951,25969,25981,25997,26011,26023,26029,26041,26051,26053,26057,26059,26069,26071,26077,26081,26083,26101,26111,26113,26137,26153,26161,26167,26179,26197,26209,26219,26221,26227,26233,26237,26239,26249,26251,26269,26273,26279,26281,26293,26321,26329,26347,26353,26363,26377,26387,26389,26399,26401,26413,26417,26419,26429,26431,26437,26441,26443,26449,26461,26471,26473,26491,26497,26513,26521,26527,26539,26557,26561,26569,26581,26591,26603,26609,26611,26623,26641,26651,26653,26669,26671,26681,26689,26699,26701,26707,26713,26731,26737,26749,26753,26771,26773,26777,26779,26797,26801,26809,26813,26821,26833,26837,26839,26849,26861,26867,26879,26881,26891,26893,26897,26899,26909,26911,26917,26921,26923,26941,26951,26953,26977,26993,27001,27007,27019,27037,27049,27059,27061,27071,27073,27089,27091,27101,27103,27121,27131,27133,27143,27149,27151,27157,27161,27169,27179,27187,27193,27211,27217,27227,27229,27233,27241,27253,27257,27259,27277,27281,27283,27289,27301,27311,27313,27317,27319,27329,27341,27347,27353,27359,27361,27371,27373,27379,27397,27401,27403,27409,27413,27421,27427,27451,27457,27467,27469,27473,27481,27487,27493,27497,27499,27511,27521,27533,27539,27551,27553,27563,27569,27571,27577,27581,27583,27589,27593,27611,27613,27617,27619,27631,27637,27641,27649,27661,27673,27691,27697,27721,27731,27733,27737,27739,27749,27751,27757,27761,27763,27787,27793,27809,27817,27833,27841,27851,27857,27859,27869,27871,27877,27883,27889,27899,27901,27907,27913,27917,27919,27929,27931,27949,27953,27959,27961,27973,28001,28013,28019,28031,28033,28043,28051,28057,28061,28069,28073,28081,28093,28097,28103,28117,28123,28129,28141,28151,28153,28157,28159,28169,28171,28177,28181,28183,28201,28211,28213,28237,28241,28243,28249,28253,28261,28267,28289,28297,28309,28321,28337,28351,28363,28369,28379,28381,28393,28403,28417,28429,28433,28447,28459,28477,28487,28489,28493,28501,28513,28523,28529,28531,28537,28561,28571,28573,28577,28579,28597,28601,28603,28619,28621,28627,28633,28639,28657,28661,28663,28669,28673,28691,28697,28703,28717,28723,28729,28739,28741,28747,28753,28757,28759,28769,28771,28801,28811,28813,28817,28829,28831,28837,28841,28843,28849,28877,28883,28897,28907,28909,28913,28921,28927,28933,28937,28939,28957,28961,28963,28969,28981,28993,29009,29017,29041,29077,29081,29083,29089,29093,29101,29107,29131,29137,29149,29153,29161,29177,29201,29203,29209,29213,29221,29227,29233,29243,29249,29251,29257,29261,29263,29269,29273,29293,29297,29303,29317,29329,29357,29363,29369,29377,29387,29389,29401,29413,29417,29419,29437,29441,29447,29461,29467,29473,29497,29501,29503,29509,29513,29521,29527,29549,29557,29569,29579,29581,29587,29593,29597,29599,29609,29611,29629,29633,29639,29641,29653,29677,29681,29683,29689,29693,29707,29713,29737,29749,29761,29777,29791,29803,29809,29819,29821,29833,29843,29857,29867,29873,29887,29899,29917,29921,29923,29929,29933,29941,29947,29969,29977,29989,30001,30017,30031,30043,30049,30059,30061,30073,30083,30097,30109,30113,30127,30139,30157,30161,30169,30173,30181,30187,30193,30209,30217,30229,30241,30251,30253,30257,30259,30283,30299,30301,30307,30313,30323,30329,30337,30347,30349,30353,30361,30367,30383,30389,30391,30397,30413,30419,30431,30433,30449,30451,30467,30469,30473,30481,30487,30493,30497,30523,30529,30539,30547,30553,30557,30559,30571,30577,30593,30617,30623,30637,30641,30643,30649,30661,30673,30683,30689,30691,30697,30701,30703,30713,30721,30733,30743,30757,30763,30769,30803,30809,30811,30817,30823,30829,30833,30841,30859,30881,30889,30913,30923,30929,30931,30937,30941,30943,30949,30953,30973,30977,30983,30997,31009,31033,31039,31051,31057,31067,31069,31081,31091,31093,31103,31117,31121,31123,31133,31147,31153,31163,31177,31181,31183,31189,31193,31201,31211,31217,31219,31243,31249,31259,31261,31267,31273,31289,31291,31307,31309,31313,31321,31327,31333,31343,31349,31351,31357,31361,31373,31379,31391,31393,31403,31411,31417,31427,31429,31433,31441,31447,31453,31457,31459,31483,31489,31499,31501,31513,31517,31519,31529,31531,31537,31543,31553,31571,31583,31597,31601,31603,31609,31613,31621,31627,31643,31649,31651,31657,31663,31669,31673,31681,31693,31697,31723,31729,31753,31763,31769,31771,31777,31781,31783,31789,31793,31819,31837,31841,31849,31873,31883,31889,31891,31897,31901,31903,31909,31921,31931,31933,31937,31939,31949,31951,31957,31961,31963,31981,31991,31993,32017,32033,32051,32057,32063,32077,32083,32089,32093,32101,32107,32113,32129,32149,32161,32173,32183,32189,32191,32197,32201,32203,32209,32213,32233,32237,32243,32257,32267,32269,32273,32281,32293,32297,32299,32317,32321,32323,32329,32341,32351,32353,32357,32359,32369,32381,32387,32393,32399,32401,32411,32413,32419,32437,32441,32443,32449,32453,32461,32467,32491,32497,32507,32509,32513,32521,32527,32533,32537,32539,32551,32561,32573,32579,32591,32593,32603,32609,32611,32617,32621,32623,32629,32633,32651,32653,32657,32659,32671,32677,32681,32689,32701,32713,32731,32737,32761,32779,32797,32801,32819,32821,32831,32833,32843,32849,32861,32863,32881,32891,32903,32909,32911,32917,32929,32939,32941,32947,32953,32971,32987,32989,32993,33001,33011,33013,33017,33037,33041,33043,33049,33053,33071,33073,33077,33079,33101,33107,33113,33119,33121,33133,33137,33139,33157,33161,33163,33169,33181,33193,33211,33217,33227,33233,33241,33247,33253,33259,33281,33293,33311,33323,33329,33331,33337,33343,33349,33353,33361,33371,33373,33377,33379,33389,33391,33401,33403,33409,33421,33431,33433,33451,33457,33473,33491,33493,33497,33499,33511,33517,33521,33529,33547,33553,33569,33577,33601,33611,33613,33617,33629,33641,33653,33659,33683,33689,33697,33701,33713,33739,33757,33773,33779,33797,33809,33821,33827,33833,33841,33851,33853,33857,33869,33871,33877,33881,33883,33889,33911,33913,33931,33937,33953,33961,33967,33979,33997,34001,34009,34019,34021,34031,34033,34043,34049,34051,34061,34063,34081,34091,34093,34103,34109,34117,34121,34129,34141,34147,34171,34177,34187,34189,34193,34201,34211,34213,34217,34219,34241,34243,34249,34253,34261,34271,34273,34277,34289,34301,34313,34319,34331,34333,34337,34339,34357,34361,34369,34373,34381,34387,34393,34411,34417,34427,34429,34441,34453,34457,34459,34471,34481,34493,34499,34511,34513,34523,34529,34537,34541,34543,34549,34553,34561,34571,34577,34579,34603,34609,34619,34621,34627,34633,34649,34651,34667,34669,34673,34681,34687,34693,34703,34709,34711,34717,34721,34733,34739,34751,34753,34757,34763,34777,34781,34793,34801,34817,34841,34847,34849,34859,34861,34877,34889,34901,34913,34931,34943,34957,34961,34973,34991,34997,35009,35027,35033,35041,35051,35053,35057,35069,35081,35093,35099,35117,35123,35129,35137,35141,35153,35159,35179,35197,35201,35213,35219,35237,35243,35249,35257,35261,35267,35281,35291,35293,35297,35309,35321,35327,35333,35339,35351,35377,35389,35393,35411,35417,35423,35429,35449,35453,35473,35477,35489,35513,35519,35521,35531,35533,35537,35549,35561,35573,35597,35603,35617,35627,35629,35633,35657,35663,35669,35681,35699,35713,35723,35729,35741,35747,35753,35771,35789,35801,35807,35809,35813,35831,35837,35851,35857,35867,35869,35879,35881,35887,35893,35897,35921,35923,35929,35947,35953,35963,35969,35971,35977,35989,35993,36011,36013,36017,36019,36031,36037,36047,36049,36053,36061,36077,36083,36089,36097,36107,36109,36121,36131,36133,36137,36139,36149,36151,36157,36161,36163,36187,36193,36203,36209,36217,36221,36223,36229,36233,36241,36247,36257,36269,36287,36289,36299,36301,36307,36313,36317,36319,36329,36331,36349,36353,36359,36361,36373,36401,36409,36427,36433,36443,36457,36467,36469,36479,36481,36493,36497,36499,36509,36511,36517,36521,36523,36529,36541,36551,36553,36571,36577,36593,36601,36607,36619,36637,36641,36649,36661,36671,36683,36689,36691,36703,36721,36731,36733,36749,36751,36761,36769,36779,36781,36787,36793,36811,36817,36829,36833,36851,36853,36857,36859,36877,36881,36889,36893,36901,36913,36917,36919,36929,36941,36947,36959,36961,36979,36991,37003,37021,37063,37069,37081,37091,37097,37099,37109,37111,37117,37123,37129,37141,37151,37153,37171,37193,37201,37207,37237,37241,37249,37259,37267,37273,37277,37279,37291,37297,37309,37313,37319,37321,37333,37339,37361,37369,37393,37403,37409,37417,37427,37439,37447,37453,37477,37481,37483,37489,37493,37501,37507,37529,37537,37549,37561,37577,37591,37603,37609,37619,37621,37633,37649,37661,37699,37711,37729,37741,37757,37771,37783,37789,37801,37817,37831,37841,37867,37873,37889,37897,37913,37921,37927,37937,37969,37997,38011,38047,38077,38081,38089,38107,38113,38123,38137,38147,38149,38159,38161,38173,38177,38179,38189,38191,38203,38209,38219,38221,38233,38237,38239,38249,38251,38257,38273,38279,38281,38293,38299,38317,38321,38329,38341,38351,38363,38369,38371,38383,38401,38411,38413,38417,38419,38429,38431,38441,38443,38449,38461,38471,38473,38491,38497,38513,38527,38539,38557,38561,38569,38579,38581,38593,38603,38609,38611,38621,38623,38641,38653,38657,38663,38677,38683,38701,38711,38713,38719,38729,38737,38741,38743,38749,38761,38771,38797,38803,38809,38813,38821,38827,38833,38849,38869,38881,38893,38903,38909,38911,38917,38921,38923,38929,38933,38953,38957,38963,38977,38981,38989,38993,39001,39013,39017,39023,39037,39043,39049,39061,39073,39089,39097,39121,39149,39161,39167,39169,39173,39211,39217,39229,39233,39241,39257,39281,39283,39289,39293,39301,39307,39313,39329,39337,39353,39379,39397,39401,39409,39433,39451,39457,39481,39493,39497,39499,39511,39521,39533,39539,39551,39553,39563,39569,39577,39581,39583,39589,39593,39601,39607,39617,39629,39647,39649,39653,39659,39671,39691,39701,39703,39709,39713,39721,39761,39773,39779,39791,39793,39803,39811,39821,39827,39833,39839,39841,39857,39863,39869,39877,39881,39883,39889,39901,39913,39923,39929,39931,39937,39947,39953,39961,39979,40003,40007,40009,40013,40021,40037,40051,40057,40067,40081,40093,40109,40127,40129,40139,40141,40157,40171,40219,40241,40247,40253,40267,40273,40277,40289,40297,40301,40307,40319 65536: This makes my answer go over the character limit (32768 numbers) 105953: 1-105952 ``` [Answer] # Pyth - 39 37 bytes A direct translation of @Wrzlprmft's python answer. ``` f.Am>.asm^.n1c*.jZyk.nZQd^10_9.cUQTSQ ``` Explanation and probably further golfing coming soon. [Try it online here](http://pyth.herokuapp.com/?code=f.Am%3E.asm%5E.n1c*.jZyk.nZQd%5E10_9.cUQTSQ&input=9&debug=1). ]
[Question] [ Turns out there are some distant aliens who know English *(and have coincidentally standardized on 8-bit computer architectures)*. Yet they have never heard of ASCII, nor even alphabetical order. It is believed that these aliens are picking up information from Earth. Yet they are doing so with digital equipment that reads meaningless information when no transmission is being sent...thus the signal must be contained in a way to stand out from surrounding noise. A new standard has been created, modeled after the Arecibo Message's use of a semiprime signal length: # Universal Semiotic Coding for Information Interchange (USCII) *(See: <http://uscii.hostilefork.com>)* In USCII, each code is derived from a bitmap representing the character, that has a prime width and a prime height. For instance, this 5x7 representation of a letter A: ``` 01110 10001 10001 10001 11111 10001 10001 ``` That produces 35 bits. Yet in order to make even single-character messages stand out from the noise and look coherent, strings are embedded in a container format that helps reinforce the prime factors. The container has been chosen to also make it easy to manipulate the strings on architectures that operate on multiples of 8 bits. With its container, the "A" above would look like: ``` 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 0111010001100011000111111100011000100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111100000 1111111111111111111111111111111111111111 1111111111111111111111111111111111111111 1111111111111111111111111111111111111111 1111111111111111111111111111111111111111 1111111111111111111111111111111111111111 ``` The characters of the message are first prefixed with five solid 5x7 bitmaps, and seven solid 5x7 bitmaps added to the end. (The **"meter"**.) Then each of these have five 0 bits tacked onto the end to make an even 40 bits. Finally there are 7 all-zero 40-bit runs added to the beginning, and 5 all-one 40-bit runs added to the end. (The **"silence"**.) # Your mission You are to write an encoder. Input is a conventional ASCII string typed from the keyboard. The bitmaps you will use are from the 5x7 [PIC CPU font](http://www.noritake-itron.com/Softview/fontspic.htm). *(Note: It's easy enough to extract the font from the page for all the talented code golfers here, but if you want those bytes all together [here they are](https://github.com/hostilefork/uscii/blob/435c5a788e4456332f70ac908c0aa75d5534ca76/uscii-5x7-english-c0.reb#L909).)* Output should be a printed string in hexadecimal. # Examples **Input**: ``` ABCDEFG ``` **Output**: `0000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE074631FC620F463E8C7C074610845C0E4A318CB80FC21E843E0FC21E84200746178C5E0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF` **Input**: ``` Dear aliens: Please get me off of this planet!!! ``` **Output**: `0000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0E4A318CB80001D1FC1E0001C17C5E0002D9842000000000000001C17C5E061084211C00100421080001D1FC1E0002D98C620001F0707C003180630000000000000F463E8420061084211C0001D1FC1E0001C17C5E0001F0707C0001D1FC1E00000000000001F1787C0001D1FC1E0213E421440000000000000375AD620001D1FC1E00000000000001D18C5C01148E210801148E210800000000000001D18C5C01148E210800000000000213E4214408421E8C6200100421080001F0707C00000000000003D1F420061084211C0001C17C5E0002D98C620001D1FC1E0213E421440210840008021084000802108400080FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF` # Clarifications * There is no need to handle any non-printable characters for this assignment *(although feedback on [ideas for what those might look like](https://github.com/hostilefork/uscii/blob/435c5a788e4456332f70ac908c0aa75d5534ca76/uscii-5x7-english-c0.reb#L113) is welcome)* # Winning Conditions `0000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE074610845C0001D18C5C00842F8C5E0001D1FC1E00000000000746178C5E0001D18C5C061084211C01148E21080210840008021084000802108400080FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFE0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF` [Answer] # Python 2, ~~671~~ ~~669~~ 663 bytes ``` D=str.decode d=D(D("eJxNUmsSHiEIuxIgvn76sXr/IzVB26kzqyxCCBGRt0xlOM5RbXp6qv32Omu6lT22nTGiOVe05muMFXM11ZuuynwV52f8E7W11+SdzGMvTl6GHvm3ig6RRBbp3nqNqGEFeACK7m5YZYPAMMGV6qyk4ydKKD3FTPeAcQZhUAw4lh4aR8YcWaaVV480lDTJF64thyT4T+8tCjVofOtLnKInAAYDyJ0e9lxj+wJk/MYJ0nBQvYaRhnbQQEIrB5t1fX2VwdMnZF1zLF/Gf2H62PtXGYwypU5msXo2mNUvclE+QXqY3sNkg3GcKReKRTPrGnizNNCOw+tenSWaLQZf6VC926UYVw7I0y/eDEOo/LfKvvLdEQjt7NTzLXrkI2MmNrMPRYDng4a6VR0ThTKMgUA9XlYzTIsk+XtCH+y2mk1rf6VD4V7Xh2Cxb2YWkdkprlDCTR6yv5jnQSuQScEb0CBu5WXZ1ScN6gMDvWa73HNoy845VMg7wLBlA9wwhAMTiNn6ravFH00dtSc=","base64"),"zip") i=raw_input() m="F"*8+"E0" o="0"*70+m*5 for c in i:x=ord(c)*9-288;o+=d[x:x+9]+"0" print o+m*7+"F"*50 ``` --- # PHP with zlib, ~~738~~ ~~716~~ 715 bytes ``` <?php $d=gzinflate(base64_decode("TVJrEh4hCLsSIL5++rF6/yM1QdupM6ssQggRkbdMZTjOUW16eqr99jprupU9tp0xojlXtOZrjBVzNdWbrsp8Fedn/BO1tdfkncxjL05ehh75t4oOkUQW6d56jahhBXgAiu5uWGWDwDDBleqspOMnSig9xUz3gHEGYVAMOJYeGkfGHFmmlVePNJQ0yReuLYck+E/vLQo1aHzrS5yiJwAGA8idHvZcY/sCZPzGCdJwUL2GkYZ20EBCKwebdX19lcHTJ2Rdcyxfxn9h+tj7VxmMMqVOZrF6NpjVL3JRPkF6mN7DZINxnCkXikUz6xp4szTQjsPrXp0lmi0GX+lQvdulGFcOyNMv3gxDqPy3yr7y3REI7ezU8y165CNjJjazD0WA54OGulUdE4UyjIFAPV5WM0yLJPl7Qh/stppNa3+lQ+Fe14dgsW9mFpHZKa5Qwk0esr+Y50ErkEnBG9AgbuVl2dUnDeoDA71mu9xzaMvOOVTIO8CwZQPcMIQDE4jZ+q2rxR8="));$i=trim(fgets(STDIN));$f="str_repeat";echo $f(0,70).$f($m="FFFFFFFFE0",5);foreach(str_split($i)as$c)echo substr($d,ord($c)*9-288,9)."0";echo $f($m,7).$f("F",50); ``` First, your PHP needs to be configured with `--with-zlib`. And run this script from command line, like `php 26972.php`. This program takes input from STDIN. (If `short_open_tag=On`, I can save 3 more bytes.) ## Ungolfed ``` <?php $data = gzinflate(base64_decode("TVJrEh4hCLsSIL5++rF6/yM1QdupM6ssQggRkbdMZTjOUW16eqr99jprupU9tp0xojlXtOZrjBVzNdWbrsp8Fedn/BO1tdfkncxjL05ehh75t4oOkUQW6d56jahhBXgAiu5uWGWDwDDBleqspOMnSig9xUz3gHEGYVAMOJYeGkfGHFmmlVePNJQ0yReuLYck+E/vLQo1aHzrS5yiJwAGA8idHvZcY/sCZPzGCdJwUL2GkYZ20EBCKwebdX19lcHTJ2Rdcyxfxn9h+tj7VxmMMqVOZrF6NpjVL3JRPkF6mN7DZINxnCkXikUz6xp4szTQjsPrXp0lmi0GX+lQvdulGFcOyNMv3gxDqPy3yr7y3REI7ezU8y165CNjJjazD0WA54OGulUdE4UyjIFAPV5WM0yLJPl7Qh/stppNa3+lQ+Fe14dgsW9mFpHZKa5Qwk0esr+Y50ErkEnBG9AgbuVl2dUnDeoDA71mu9xzaMvOOVTIO8CwZQPcMIQDE4jZ+q2rxR8=")); $input = trim(fgets(STDIN)); $f = "str_repeat"; echo $f(0, 70).$f($m = "FFFFFFFFE0", 5); foreach(str_split($input) as $c) echo substr($data, ord($c) * 9 - 288, 9)."0"; echo $f($m, 7).$f("F", 50); ``` [Answer] **C** This actually prints human readable hex (vs binary for readablity). Everything is represented in unsigned long long and only 9-10 hex digits are used due (depending whether you include the 00000 padding) the unfortunate 6x5 format (an 8x4 font would have just been too easy) ``` #include <stdio.h> #define u unsigned long long void p(int n, u x){while(n--) printf("%09llX",x);} int main(void){ char *s="ABCDEFG"; u a[128]={0xAAAAAAAAAULL,0xADEB7ADEAULL,0xDFF7FDFF6ULL,0xDEF7BDFF6ULL,0xFFFFFFCE6ULL,0xFF41DB82EULL,0xFD7FF747EULL,0xDC63107F6ULL,0xFEEE0BEFEULL,0x0003D0800ULL,0xE1084FB88ULL,0x21084201CULL,0xFB880FB88ULL,0x084ADFB08ULL,0x25F7BDF78ULL,0xE777BDDC8ULL,0xFFC8E27FEULL,0xFDE719DFEULL,0xDED4A73A2ULL,0xFD6B5AD7EULL,0xFC6318C7EULL,0xFD7FF8BBEULL,0xFFFFFFABEULL,0xF81CA703EULL,0x881445022ULL,0xFC58A347EULL,0x8BBDDDFF6ULL,0x1995E73A2ULL,0xAD6B5AD6AULL,0xDEF7BDEF6ULL,0xF7B5204F6ULL,0xFFFFF9EEEULL,0x000000000ULL,0x210840008ULL,0x529400000ULL,0x52BEAFA94ULL,0x23E8E2F88ULL,0xC644444C6ULL,0x64A88AC9AULL,0x611000000ULL,0x111084104ULL,0x410421110ULL,0x012AEA900ULL,0x0109F2100ULL,0x000006110ULL,0x0001F0000ULL,0x000000318ULL,0x004444400ULL,0x74675CC5CULL,0x23084211CULL,0x74422223EULL,0xF88820C5CULL,0x11952F884ULL,0xFC3C10C5CULL,0x3221E8C5CULL,0xF84444210ULL,0x7462E8C5CULL,0x7462F0898ULL,0x031806300ULL,0x031806110ULL,0x111104104ULL,0x003E0F800ULL,0x410411110ULL,0x744222008ULL,0x7442DAD5CULL,0x74631FC62ULL,0xF463E8C7CULL,0x74610845CULL,0xE4A318CB8ULL,0xFC21E843EULL,0xFC21E8420ULL,0x746178C5EULL,0x8C63F8C62ULL,0x71084211CULL,0x388421498ULL,0x8CA98A4A2ULL,0x84210843EULL,0x8EEB58C62ULL,0x8C7359C62ULL,0x746318C5CULL,0xF463E8420ULL,0x74631AC9AULL,0xF463EA4A2ULL,0x7C20E087CULL,0xF90842108ULL,0x8C6318C5CULL,0x8C6318A88ULL,0x8C631AD54ULL,0x8C5445462ULL,0x8C62A2108ULL,0xF8444443EULL,0x72108421CULL,0x000000000ULL,0x70842109CULL,0x22A200000ULL,0x00000003EULL,0x410400000ULL,0x001C17C5EULL,0x8421E8C7CULL,0x001F0841EULL,0x0842F8C5EULL,0x001D1FC1EULL,0x1148E2108ULL,0x001F1787CULL,0x8421E8C62ULL,0x010042108ULL,0x100421498ULL,0x4212A6292ULL,0x61084211CULL,0x00375AD62ULL,0x002D98C62ULL,0x001D18C5CULL,0x003D1F420ULL,0x001F17842ULL,0x002D98420ULL,0x001F0707CULL,0x213E42144ULL,0x002318C5CULL,0x002318A88ULL,0x00231AD54ULL,0x0022A22A2ULL,0x0022A2110ULL,0x003E2223EULL,0x190882106ULL,0x210802108ULL,0xC10822130ULL,0x0BA000000ULL,0xFE2A2AE3EULL}; p(7,0ULL); p(5,0xFFFFFFFE0ULL); while(*s)p(1,a[*s++]); p(7,0xFFFFFFFE0ULL); p(5,0xFFFFFFFFFULL); return 0; } ``` **bash** ``` #!/bin/sh p(){ i=0 while ([ $i -lt $1 ]) do printf $2 i=$((i+1)) done } t(){ #Given string input $1, go char by char & create "alien" representation C='~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !"#$%&~)*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~' A="AAAAAAAAA0ADEB7ADEA0DFF7FDFF60DEF7BDFF60FFFFFFCE60FF41DB82E0FD7FF747E0DC63107F60FEEE0BEFE00003D08000E1084FB88021084201C0FB880FB880084ADFB08025F7BDF780E777BDDC80FFC8E27FE0FDE719DFE0DED4A73A20FD6B5AD7E0FC6318C7E0FD7FF8BBE0FFFFFFABE0F81CA703E08814450220FC58A347E08BBDDDFF601995E73A20AD6B5AD6A0DEF7BDEF60F7B5204F60FFFFF9EEE000000000002108400080529400000052BEAFA94023E8E2F880C644444C6064A88AC9A0611000000011108410404104211100012AEA90000109F2100000000611000001F000000000003180004444400074675CC5C023084211C074422223E0F88820C5C011952F8840FC3C10C5C03221E8C5C0F8444421007462E8C5C07462F08980031806300003180611001111041040003E0F8000410411110074422200807442DAD5C074631FC620F463E8C7C074610845C0E4A318CB80FC21E843E0FC21E84200746178C5E08C63F8C62071084211C038842149808CA98A4A2084210843E08EEB58C6208C7359C620746318C5C0F463E8420074631AC9A0F463EA4A207C20E087C0F9084210808C6318C5C08C6318A8808C631AD5408C544546208C62A21080F8444443E072108421C0000000000070842109C022A200000000000003E04104000000001C17C5E08421E8C7C0001F0841E00842F8C5E0001D1FC1E01148E21080001F1787C08421E8C620010042108010042149804212A6292061084211C000375AD620002D98C620001D18C5C0003D1F4200001F178420002D984200001F0707C0213E421440002318C5C0002318A88000231AD5400022A22A200022A21100003E2223E019088210602108021080C1082213000BA0000000FE2A2AE3E0" j=0 p 7 0000000000 p 5 FFFFFFFFE0 while ([ "${j}" -lt "${#1}" ]) do i=${C%${1:$j:1}*} i=${#i} printf ${A:$(( $i*10 )):10} j=$(($j+1)) done p 7 FFFFFFFFE0 p 5 FFFFFFFFFF } t "Dear aliens: Please get me off of this planet!!!" ``` [Answer] # PHP, 874 bytes You will need to run this script from the command line (`php uscii.php`) because it takes input from stdin. ``` <?php $f=base64_decode(str_replace('@','AA','@@@QhC@RSl@AClfV9SiPo4viYyIiJjZKiKyawi@@REIQQSCCEIiAEq6p@IT5C@@GEQ@Pg@@@xgAiIiAHRnXMXEYQhCOdEIiI/8RBBi4RlS+IX4eCGLjIh6MXfCIiEIdGLoxc6MXhEwDGAYwAGMAwiBERBBBAB8HwAQQQREQ6IREAR0QtrVzoxj+MfRj6MfOjCEIu5KMYy5+EPQh/8IehCDowvGL4xj+MYuIQhCOOIQhSZGVMUlGEIQhD8d1rGMYxzWcYujGMYu9GPoQg6MY1k30Y+pKL4QcEPvkIQhCRjGMYujGMYqJGMY1qqMVEVGMYxUQhPhEREPuQhCEOBBBBBA4QhCE4iog@@@AH0EE@@A4L4vhCHox8AD4Qg8IQvjF4AOj+DxFI4hC@+Lw+hCHoxiAgCEIQQBCFJiEJUxSWEIQhHAButaxAC2YxiADoxi4APR9C@Pi8IQAtmEI@+Dg+IT5CFEAEYxi4AIxiogARjWqgAioiogBFRCIAD4iI+MhEEIMhCAIQmCEEQmAug@@='));$a=trim(fgets(STDIN));$r='str_repeat';echo$r('0',70).$r($q='FFFFFFFFE0',5);foreach(str_split($a)as$c){$v=(ord($c)-32)*35;$x=$v>>3;$y=1<<(7-$v%8);$b=0;for($i=0;$i<40;$i++){$b+=$b+($i<35&&ord($f[$x])&$y);if(($i&7)==7)$b=!printf('%02X',$b);if(!($y>>=1)&&$x++)$y=128;}}echo$r($q,7).$r('F',50); ``` ## Ungolfed: ``` <?php // Font bitmap data rearranged as 95 consecutive 35-bit strings and padded // out to 416 bytes with zeros: $f=base64_decode(str_replace('@','AA', '@@@QhC@RSl@AClfV9SiPo4viYyIiJjZKiKyawi@@REIQQSCCEIiAEq6p@IT5C@@GEQ@Pg'. '@@@xgAiIiAHRnXMXEYQhCOdEIiI/8RBBi4RlS+IX4eCGLjIh6MXfCIiEIdGLoxc6MXhEw'. 'DGAYwAGMAwiBERBBBAB8HwAQQQREQ6IREAR0QtrVzoxj+MfRj6MfOjCEIu5KMYy5+EPQh'. '/8IehCDowvGL4xj+MYuIQhCOOIQhSZGVMUlGEIQhD8d1rGMYxzWcYujGMYu9GPoQg6MY1'. 'k30Y+pKL4QcEPvkIQhCRjGMYujGMYqJGMY1qqMVEVGMYxUQhPhEREPuQhCEOBBBBBA4Qh'. 'CE4iog@@@AH0EE@@A4L4vhCHox8AD4Qg8IQvjF4AOj+DxFI4hC@+Lw+hCHoxiAgCEIQQB'. 'CFJiEJUxSWEIQhHAButaxAC2YxiADoxi4APR9C@Pi8IQAtmEI@+Dg+IT5CFEAEYxi4AIx'. 'iogARjWqgAioiogBFRCIAD4iI+MhEEIMhCAIQmCEEQmAug@@=')); // Fetch input: $a=trim(fgets(STDIN)); // Header: $r='str_repeat'; echo $r('0',70).$r($q='FFFFFFFFE0',5); // Convert each input character into its corresponding hex sequence: foreach (str_split($a) as $c) { $v=(ord($c)-32)*35; $x=$v>>3; $y=1<<(7-$v%8); $b=0; for ($i=0;$i<40;$i++) { // When $i>34, pad with zeros $b += $b + ($i<35 && ord($f[$x]) & $y); if (($i&7)==7) $b=!printf('%02X',$b); // print out $b and set $b=0 // Shift mask to next bit position if (!($y>>=1)&&$x++) $y=128; } } // Tail: echo $r($q,7).$r('F',50); ``` [Answer] ## JavaScript ES6 (838 Bytes) ``` _="z='00000';r=(n,m)=>m.repean);fop=prompi=o=';i<p.length;)o+=parseInatob('RSlClfV9SiPo4viYyIiJjZKiKyawiRQQSCCEq6pGEQPgxgAiIHRnXMXEYOdiI/8Ri4RlS+IX4eCGLjIhXfCIidGLcXhEwDGAYwAGMAwiBERBAB8HwAQQQREQ6IREAR0QtrVzj+MfRjfOjCu5KMYy5+EP/8IeDowvGL4xj+MYuIOOISZGVMUlGD8d1rxzWcYuju9GPoQgY1k30Y+pKL4QcEPvkIRjujqJ1qqMVEVxUPhEREPuEOBA4E4H0EEA4L4vH8AD4Qg8IQvjF4AOj+DxFI4+Lw+HgCQQBCFJiEJUxSWHAButaxAC2YxDi4APR9CPi8IQAtm+Dg+FEAEYxi4AIxARjWqgAioBFRCIAD4iI+MhEMAIQmCEEQmAugRV8nyE.split p(e=>e028)).join tch(/.{35}/g)[pi++)-32]+z,21610);14,z5,y='E0+o.toUpperCase(7,y5,10,'F)A.charCodeAQhGMY).toString(EI)).slice(-)+ ('.maC')hCoxiog(z+z+t(r(iABB6MFFAIT5C";for(Y in $=" ")with(_.split($[Y]))_=join(pop());eval(_) ``` Not [crushed](http://www.iteral.com/jscrush/) : ``` z='00000';r=(n,m)=>m.repeat(n);for(p=prompt(i=o='');i<p.length;)o+=(z+z+parseInt(atob('AAAAAAQhCAARSlAAAClfV9SiPo4viYyIiJjZKiKyawiAAAAREIQQSCCEIiAEq6pAAIT5CAAAAGEQAAPgAAAAAAxgAiIiAHRnXMXEYQhCOdEIiI/8RBBi4RlS+IX4eCGLjIh6MXfCIiEIdGLoxc6MXhEwDGAYwAGMAwiBERBBBAB8HwAQQQREQ6IREAR0QtrVzoxj+MfRj6MfOjCEIu5KMYy5+EPQh/8IehCDowvGL4xj+MYuIQhCOOIQhSZGVMUlGEIQhD8d1rGMYxzWcYujGMYu9GPoQg6MY1k30Y+pKL4QcEPvkIQhCRjGMYujGMYqJGMY1qqMVEVGMYxUQhPhEREPuQhCEOBBBBBA4QhCE4iogAAAAAAAH0EEAAAAA4L4vhCHox8AD4Qg8IQvjF4AOj+DxFI4hCAA+Lw+hCHoxiAgCEIQQBCFJiEJUxSWEIQhHAButaxAC2YxiADoxi4APR9CAAPi8IQAtmEIAA+Dg+IT5CFEAEYxi4AIxiogARjWqgAioiogBFRCIAD4iI+MhEEIMhCAIQmCEEQmAugAAARV8nyE').split('').map(e=>(z+z+e.charCodeAt(0).toString(2)).slice(-8)).join('').match(/.{35}/g)[p.charCodeAt(i++)-32]+z,2).toString(16)).slice(-10);r(14,z)+r(5,y='FFFFFFFFE0')+o.toUpperCase()+r(7,y)+r(5,r(10,'F')) ``` ]
[Question] [ ### Overview: Your job is to take CSV input in `key=value` format and line it up in a more organized (see below) way. ### Input: Always via **stdin**. Records will always be in the following form `key=value`: ``` foo=bar,baz=quux abc=123,foo=fubar baz=qwe,abc=rty,zxc=uiop,foo=asdf ``` * There will be no list of possible keys in advance, you must find them in the input text. * End of input will be signalled by [`EOF`](http://en.wikipedia.org/wiki/End-of-file), whatever implementation of `EOF` is appropriate for your OS. ### Output: The first row of your output will be a list of all the keys, in alphabetical order (even if the keys are all numbers). After that, print each record in the same CSV format the appropriate number heading, without the keys listed. So, for the example above, the correct output would be: ``` abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop ``` ### FAQ: * Do I have to worry about improperly formatted input? + No. Your program may do whatever it wants (throw an exception, ignore, etc.) if the input is not correctly formatted, e.g. a line of `foo,bar,baz` * How do I handle escaping special characters? + You may assume that there will be no additional `,` or `=` in the data that are not part of the `key=value` format. `"` does not have any special meaning in this contest (even though it does in traditional CSV). is also not special in any way. + Lines should match the following regex: `^([^=,]+=[^=,]+)(,[^=,]+=[^=,]+)*$` - Therefore, both keys and values will match `[^=,]+` * What about `CRLF` vs. `LF`? + You may choose whatever delimiter is appropriate for your platform. Most languages handle this without special delimiting code. * Do I need to print trailing commas if the last few columns don't exist? + Yes. See the example. * Are CSV parsers or other similar external tools allowed? + No. You must parse the data yourself. [Answer] ### GolfScript, 64 characters ``` n%{','/{'='/}%}%:I{{0=}/}%.&$:K','*n{`{{(2$=*}%''*\;}+K%','*n}I/ ``` The code is a straight-forward implementation in GolfScript, you can test the example [online](http://golfscript.apphb.com/?c=OyJmb289YmFyLGJhej1xdXV4CmFiYz0xMjMsZm9vPWZ1YmFyCmJhej1xd2UsYWJjPXJ0eSx6eGM9dWlvcCxmb289YXNkZiIKCm4leycsJy97Jz0nL30lfSU6SXt7MD19L30lLiYkOksnLCcqbntge3soMiQ9Kn0lJycqXDt9K0slJywnKm59SS8%3D&run=true). *Annotated code:* ``` # Split the input into lines, each line into tuples [key, value] # and assign the result to variable I n%{','/{'='/}%}%:I # From each tuple take the 0'th element (i.e the key) {{0=}/}% # Take the unique items (.&), sort ($) and assign the result to variable K .&$:K # Output: join values with , and append a newline ','*n # {...}I/: Loop over all lines of the input { # `{...}+K%: Loop over all keys and initially push the current # line for each of the keys `{ # stack here is [current key, current line] # {}%: map to all the items of the current line { # extract the key from the current item and compare (2$= # if equal keep [value], otherwise multiply with 0, i.e. discard * }% # join the results (may be one or zero) and drop the key ''*\; }+K% # Output: join values of current line with , and append a newline ','*n }I/ ``` [Answer] # Perl 6: 119 characters, 120 bytes ``` my@l=lines.map:{/[(\w+)\=(\w+)]+%\,/;push $!,~«@0;$%(@0 Z=>@1)} say .join(",") for$!.=sort.=uniq,($(.{@$!}X//"") for@l) ``` De-golfed: ``` my@l=lines.map: { # Parse the key=value pairs, # put all the keys in $/[0] (or $0) # put all the values in $/[1] (or $1) / [ (\w+) \= (\w+) ]+ % \, /; # Push all the keys into $! # (@0 just means @$0 or $/[0].list) push $!, ~«@0; # Return a hash of keys zipped into pairs with the values $%( @0 Z=> @1 ) } $!.=sort.=uniq; # …i.e., $! = $!.sort.uniq; # Print the CSV for the keys ($!), # followed by the CSVs for the hashes we made for each line, # as accessed by our sorted key list. (… .{@$!} …) # If the value doesn't exist, just use "" instead. (… X// "" …) say .join(",") for $!, ($( .{@$!} X// "" ) for @l) ``` [Answer] # perl, 129/121 129 bytes, no command line switches: ``` for(<>){push@x,{%g=map{split/=/}split/[, ]/};@h{keys%g}=()}@k=sort keys%h;$"=",";sub P{print"@_ "}P@k;for$x(@x){P map{$$x{$_}}@k} ``` As @Dennis points out below, you can get this to 120+1=121 by using -n: ``` push@x,{%g=map{split/=/}split/[, ]/};@h{keys%g}=()}@k=sort keys%h;$"=",";sub P{print"@_ "}P@k;for$x(@x){P map{$$x{$_}}@k ``` Basically, for each line, we split by commas to get the list of pairs. For each pair, we split by the equals sign to get the key and value. We set the key/value pair in %h and a local hashref. The former is used to determine the list of keys. The latter is used to remember the values for this line. [Answer] # JavaScript (*ES5*) 191 183 179 168 bytes Assuming the code is run in spidermonkey command line: ``` for(b=[a={}];l=readline(i=0);b.push(c))for(c={},d=l.split(/,|=/);e=d[i++];)c[a[e]=e]=d[i++];for(;c=b[i++];)print(Object.keys(a).sort().map(function(x){return c[x]})+[]) ``` Result: ``` > js test.js < input.txt abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop ``` This shim can be used in a browser to simulate spidermonkey's `readline` and `print`: ``` var I = 0, LINES = '\ foo=bar,baz=quux\n\ abc=123,foo=fubar\n\ baz=qwe,abc=rty,zxc=uiop,foo=asdf'.split('\n'), readline = function(){ return LINES[I++]; }, print = function(){ return console.log.apply(console, arguments); }; ``` Ungolfed: ``` a = {}; // this object holds all keys found b = [a]; // array key:value pairs of each line, initialized with our key holder object in position 0 for(;l = readline();){ // store each line in l, loop until blank/undefined line c = {}; // create a new object for this line's key:value pairs d = l.split(/,|=/); // split line by commas and equals for(i = 0; e = d[i++];){ // loop through each key a[e] = e; // set the key=key for key holder object c[e] = d[i++]; // set key=value for the line object } b.push(c); // push line object onto array } for(i = 0; c = b[i++];){ // loop through all line objects until undefined print( // print line Object.keys(a).sort(). // get sorted list of keys map(function(x){ return c[x] // map values from line object }) + [] // cast array to string ); } ``` [Answer] # Bash + coreutils, 188 138 bytes ``` p=paste\ -sd, f=`cat` h=`tr , '\n'<<<$f|cut -d= -f1|sort -u` $p<<<"$h" for l in $f;{ join -o2.2 -a1 - <(tr =, ' \n'<<<$l|sort)<<<"$h"|$p } ``` Output: ``` $ ./lineupcsv.sh < input.csv abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop $ ``` [Answer] # Haskell, 357 334 ``` import Data.List o=1<2 s u|u==""=""|o=tail u t=takeWhile d=dropWhile c=(/=',') e=(/='=') p x|x/=""=Just((t e x,t c.s.d e$x),s.d c$x)|o=Nothing g=m(unfoldr p).lines k=nub.sort.(m fst=<<).g []#_=[] (t@(x,u):z)#n@(a,b)|x==a=n:z|o=t:z#n i=intercalate main=interact$ \d->i"\n"$(i","$k d):m(i",".m snd.foldl(#)(m(flip(,)"").k$d))(g d) m=map ``` `g` is doing the parsing - it splits the input into lines and maps each line to a list of `(key,value)` pairs. `k`, by concatenating all the keys into a list and removing duplicates, creates a list with all unique keys which I can later use for sorting. I do this by creating a "Set" inside `main` (`m(flip(,)"").k$d == [("abc",""),("baz",""),("foo",""),("zxc","")]`) for each line, and then taking every `(key,value)` pair from a line and put it where it belongs in the list (`foldl`). Line 1 from the example yields `[("abc",""),("baz","quux"),("foo","bar"),("zxc","")]`, which I concatenate into a single String (`",quux,bar,"`), concatenate with the other lines, and print. ``` >>> csv.exe < input.txt abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop ``` [Answer] # Python 2.7 - 242 bytes bleh ``` import os c=[r.split(',')for r in os.read(0,99).split('\n')] k=sorted(list(set(sum([[s.split('=')[0]for s in r]for r in c],[])))) print','.join(k) for l in c: t=[''for i in k] for s in l: o,v=s.split('=') t[k.index(o)]=v print','.join(t) ``` Note that the second layer of indentation is a single tab character, not four spaces like SE renders it. Ungolfed: ``` #!/bin/python2 import os # I do input as a list comprehension in the original but this is equivalent c = [] # For each line in the input for r in os.read(0,99).split('\n'): # Add a list of key=value pairs in that row to c c.append(r.split(',')) # Another thing done as a list comprehension, but I'll space it out k = [] # For each list of key=value pair s in c for r in c: # For each actual key=value pair in that list for s in r: # Get the key k.append(s.split('=')[0]) # Discard dupes by converting to set and back, then sort k = sorted(list(set(k))) # Seperate these keys by commas, then print print ','.join(k) # For each line in c for l in c: # t has one empty string for each key in the input t = ['' for i in k] # For each key=value pair in the line for s in l: # o = key, v = value o, v = s.split('=') # Find the position that the key is in the list of keys, then put the # value in t at that position t[k.index(o)] = v # Now each value is in the right position and the keys with no values on this # line have an empty string. Join everything with commas and print print ','.join(t) ``` [Answer] # Python 3: ~~200~~ ~~195~~ ~~192~~ ~~189~~ 187 ``` import sys r=[dict(p.split('=')for p in l[:-1].split(','))for l in sys.stdin] x=set() for d in r:x|=d.keys() k=sorted(x) for l in[k]+[[r.get(k,'')for k in k]for r in r]:print(*l,sep=',') ``` [Answer] ## k4 (40? 51? 70? 46?) the basic expression is ``` ","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/: ``` this both accepts and returns a list of strings to match the spec, we could interactively do ``` -1","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/:."\\cat"; ``` which accepts the input from stdin and prints the output to stdout for a standalone app accepting input from a pipe, we could do this: ``` $ cat i.k .z.pi:{t,:`\:x} .z.exit:{-1","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/:t} $ cat i.txt|q i.k abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop $ ``` altho if you're willing to consider my pre-existing k-as-filter wrapper, awq.k, as an acceptable tool for this kind of puzzle, then we can do this: ``` $ cat i.txt|awq.k '","0:{(x@<x:?,/?!:'\''x)#/:x}(!).'\''"S=,"0:/:' ``` which is either 46 characters or 40, depending on how you count shell quote wrangling [Answer] ## C# - 369 (in LINQPAD) ``` void C(string a){var k=a.Split(new[]{',','\n'}).Select(s=>s.Split('=')[0]).OrderBy(o=>o).Distinct();var t=string.Join(",", k)+"\n";foreach(var x in a.Split('\n')){for(int i=0;i<k.Count();i++){foreach(var y in x.Split(',').OrderBy(o=>o.Split('=')[0]))if(k.ElementAt(i)==y.Split('=')[0])t+=y.Split('=')[1];t+=",";}t=t.Remove(t.LastIndexOf(','),1)+"\n";}Console.Write(t);} ``` **Ungolfed** ``` void C(string a) { var k=a.Split(new[]{',','\n'}).Select(s=>s.Split('=')[0]).OrderBy(o=>o).Distinct(); var t=string.Join(",", k)+"\n"; foreach(var x in a.Split('\n')) { for(int i=0;i<k.Count();i++) { foreach(var y in x.Split(',').OrderBy(o=>o.Split('=')[0])) if(k.ElementAt(i)==y.Split('=')[0]) t+=y.Split('=')[1]; t+=","; } t=t.Remove(t.LastIndexOf(','),1)+"\n"; } Console.Write(t); } ``` **Test string input** ``` C("foo=bar,baz=quux\nabc=123,foo=fubar\nbaz=qwe,abc=rty,zxc=uiop,foo=asdf"); ``` **Output** ``` abc,baz,foo,zxc ,quux,bar, 123,,fubar, rty,qwe,asdf,uiop ``` ]
[Question] [ **Input**: Either one or two strings consisting of `'0'`s and `'1'`s. If there are 2, they are separated by a space. All strings are of length at least 1. **Output**: * If a single input was given as input, 2 are output. * If 2 were input, 1 is output. The output strings can be whatever you like, but if running your program with input A gives you B, then running it with B must give A (if inputting `111 11` gives `00000`, then inputting `00000` must give `111 11`). That means if you pipe your program to itself, you should get back whatever you input. If your program is called `foo`, you can test that like this: ``` >echo 101 101|foo|foo 101 101 ``` To prevent the use of brute force techniques, your code should be able to run with 1000 digit strings in under 10 seconds. My Python solution for this takes less than 1 second on 10000 digit strings so this shouldn't be a problem. Shortest code wins. [Answer] ## Python, 183 Bijection is cached on disk. ``` x=raw_input() try:d=eval(open('d').read()) except:d={'':'','1 ':'1 '} t='1 '*not' 'in x if x not in d: while t in d:t+=`(id(t)/9)%2` d[t]=x;d[x]=t open(*'dw').write(`d`) print d[x] ``` edit: Oops, looks like this isn't the first smartassed answer. Mine's consistent between runs! [Answer] # Python, 326 ``` s=lambda i,l:bin(i)[2:].zfill(l) f=lambda n:2**n*(n-3)+4 g=lambda n:2**n-2 i=raw_input() if' 'in i: a,b=i.split();n=len(a+b);r=f(n)+int(a+b,2)*(n-1)+len(a)-1;l=1 while g(l+1)<=r:l+=1 print s(r-g(l),l) else: n=len(i);r=g(n)+int(i,2);l=2 while f(l+1)<=r:l+=1 r-=f(l);p=r%(l-1)+1;w=s(r/(l-1),l);print w[:p],w[p:] ``` Example inputs/outputs: ``` input | output -----------+----------- 0 | 0 0 0 0 | 0 10 10 | 10101 10101 | 10 10 0000000000 | 101 0100 101 0100 | 0000000000 ``` [Answer] ### Perl 5, 197 characters ``` sub n{'0'x$_[0].sprintf'%b',$_[1]}sub N{/0*(?=.)/;length$&,oct"0b$'"}$_=<>;print/ /?n map{($a,$b)=N;($a+$b)*($a+$b+1)/2+$b}split:"@{[map{$w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y}N]}" ``` With some line breaks: ``` sub n{'0'x$_[0].sprintf'%b',$_[1]} sub N{/0*(?=.)/;length$&,oct"0b$'"} $_=<>;print/ /?n map{ ($a,$b)=N;($a+$b)*($a+$b+1)/2+$b }split:"@{[map{ $w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y }N]}" ``` This program operates by composing two bijections: * A pair of natural numbers may be mapped to a binary string by converting one to a base-2 number and the other to extraneous leading zeroes. `n` is this function and `N` is its inverse (except that `N` uses `$_` as its parameter). * A pair of natural numbers may be mapped to a single natural number using the [Cantor pairing function](http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function). The first `map`'s block is this function and the second is its inverse. Thus two binary strings are split into four numbers, combined into two numbers, and then combined into one binary string — or vice versa. Tested on 100 random inputs of each type with strings up to 8 symbols long. I've been finding lots of ways to make this a little bit shorter, but I'm going to stop and post it. If there's room to optimize further, it's probably in the arithmetic expressions. [Answer] ## Perl, 56 chars added +1 char for `-p` command line switch ``` $s.=1;$h{$h{$_}||=(split>1?$s:"$s $s").$/}=$_;$_=$h{$_} ``` [Answer] # [R](https://www.r-project.org/), 209 bytes *Note that this code will fail for numbers outside [R](https://www.r-project.org/)'s native numeric range; the approach should be valid for any number, though, and this could be solved using arbitrary-precision calculations (for instance, with the [R](https://www.r-project.org/) GMP library).* ``` function(x,z=2^nchar(x)+strtoi(x,2)-1,s=function(v,l=log2(v+1)%/%1)paste((v+1)%/%2^(l:1-1)%%2,collapse=''),d=sum(cumsum(0:z)<z),y=z-sum(0:(d-1)))`if`(length(x)>1,s(sum(0:(sum(z)-2))+z[2]),sapply(c(d+1-y,y),s)) ``` [Try it online!](https://tio.run/##rZHNboMwDMfvPEXUqsMWQSMcq7EX2VY1DWnJFgIioSq8PAulox/TbsvF9s9/x47TDDv1KYVTlcmGfWvOHpxon6UbIwrewAkj6xpXKU9TjBm12aw7Up3p6pDCMWK4el4xrLl1En7idAN6zWLvr1IqKq15bWUWhkjzzLYliLYcTbLu8aVH2mV9PMWQ@yLErdpvQUtzcIWf49X3hkt@ND3GKWLUv6UfSC2va92BgDxicUc7TxCHJbFVKYk88bLW0gbzY2HBkmSBtyBJ2CNIGLtnYqxb0IUvfcDJiNlvPMnPiWBJRCHFF3EFd2SWEWVJI7nWHeFXOoo9dZL47StzIPumKolpy51syBNx0t5cAVdvUvtugjsI302IwYT@4dcClUvjlOAaLutma79GeulJ7@DczuLfc/rkeIZv "R – Try It Online") **How does it work?** First, we convert each string `x` of `0`s & `1`s into an integer value `z`, corresponding to its lexicographical index. The code for this is: ``` z=2^nchar(x)+strtoi(x,2)-1 ``` And at the end of the bijection, we'll convert this back to a string using the opposite function: ``` s=function(v,l=log2(v+1)%/%1)paste((v+1)%/%2^(l:1-1)%%2,collapse='') ``` Using this scheme, the following strings correspond to the integer values `1` to `20`: ``` sapply(1:20,string) [1] "0" "1" "00" "01" "10" "11" "000" "001" "010" "011" [10] "100" "101" "110" "111" "0000" "0001" "0010" "0011" "0100" "0101" ``` Now, to get a single number from a pair of numbers, we consider each number pair to be `x` and `y` coordinates of a grid, and we sequentially number each position in the grid by moving along the diagonals (so the linear sequence gradually fills the two-dimensional space): This function calculates the number for each pair of coordinates: ``` num=function(c)sum(0:(sum(c)-2))+c[2] ``` Which leads to the following mapping: ``` matrix(apply(which(matrix(T,6,6),T),1,num),6,6) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 3 6 10 15 21 [2,] 2 5 9 14 20 27 [3,] 4 8 13 19 26 34 [4,] 7 12 18 25 33 42 [5,] 11 17 24 32 41 51 [6,] 16 23 31 40 50 61 ``` The 'bijection' function just rolls all these steps together. [Answer] # Python, 394 I'm sure this can be golfed further, but this monolith uses the [Cantor Pairing Function](http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function) and its inverse. ``` import math s=lambda n:n*(n+1)/2 p=lambda a:'0'*a[0]+bin(a[1])[2:] q=lambda t:t.index('1') B=raw_input().split() def f(x,y):r=x+y+1;return s(r)-[y,x][r%2]-1 def g(z):r=int(math.ceil((2*(z+1)+1/4.)**(1/2.)-1/2.))-1;d=s(r+1)-z-1;return [(d,r-d),(r-d,d)][r%2] if len(B)<2:a=[g(q(B[0])),g(int(B[0],2))];print p(a[0])+' '+p(a[1]) else:print p([f(q(B[0]),int(B[0],2)),f(q(B[1]),int(B[1],2))]) ``` # Explanation There is a natural association between a binary string and a pair of natural numbers: the first number of the image is the number of leading zeros, and the second is the integer value of the binary number. Knowing that we have: `S ~ N^2` and with the Cantor bijection `N ~ N^2` therefore: `S ~ N^2 ~ N^4 ~ S^2` `S ~ S^2` Where S is set of all binary strings. This solution implements the bijection between S and S^2. ]
[Question] [ In this challenge you will write code to take a list of positive integers and output all maximal linear sublists. * A sublist is is a list which can be created by deleting values from the the input list. Sublists have more structure than just lists. They in a way "remember" which values are deleted. * Similarly we say that sublist A is a sublist of sublist B if A can be formed by deleting elements of B. * A linear list (or sublist) is one such that all consecutive values have the same difference. * A maximal linear sublist is a sublist which is linear, and is not a sublist of any other linear sublist. For example if we receive the input list `[1,3,5,3]` then the maximal linear sublists are: ``` [1,3,5,3] ^ ^ ^ [1,3,5,3] ^ ^ [1,3,5,3] ^ ^ [1,3,5,3] ^ ^ ``` Note that the first sublist does have a sublist with the values `[1,3]`, but there is another sublist of values `[1,3]` which is maximal. # Task Given a list of positive integers you should output all the maximal linear sublists. Despite the previous emphasis, to simplify things you should output the sublists as lists, i.e. just output the values in a list form. You give your outputs in any order, but there should not be duplicates, other than sublists who coincidentally have the same values. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` [] -> [] [19] -> [19] [1,1,2] -> [1,2], [1,2], [1,1] [1,3,5,3] -> [1,3], [3,3], [5,3], [1,3,5] [1,2,3,4,3] -> [1,2,3], [3,3], [4,3] [1,2,3,4] [1,2,3,3] -> [1,2,3], [3,3], [1,2,3] [1,2,3,4] -> [1,2,3,4] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` JŒPịIEɗƇ⁸fƑⱮS¥ÐṂ`ị ``` A monadic Link that accepts a list of integers and yields a list of the maximal linear sublists. **[Try it online!](https://tio.run/##ATUAyv9qZWxsef//SsWSUOG7i0lFyZfGh@KBuGbGkeKxrlPCpcOQ4bmCYOG7i////1sxLDMsNSwzXQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/r6KSAh7u7PV1PTj/W/qhxR9qxiY82rgs@tPTwhIc7mxKAUv91DrcfnfRw54xHTWs03f//j46O5dKJNrQEkzqGOkYQhrGOqY4xhGkE5Jggc5DFY7liAQ "Jelly – Try It Online"). ### How? ``` JŒPịIEɗƇ⁸fƑⱮS¥ÐṂ`ị - Link: list of integers, A J - indices of A ŒP - powerset ɗƇ⁸ - keep those for which: ị - index back into A I - forward differences E - all equal? ¥ÐṂ` - keep those minimal under: Ɱ - map with: Ƒ - is invariant under?: f - filter keep S - sum ị - index back into A ``` [Answer] # Python3, 252 bytes ``` E=enumerate def f(l): q,T=[([a],[],[i])for i,a in E(l)],[] while q: a,c,I=q.pop(0) T+=[(a,I)] for j,k in E(l): if j>max(I)and(c==[]or a[-1]-k==c):q+=[(a+[k],a[-1]-k,I+[j])] return[a for a,b in T if not any(not{*b}-{*B}for A,B in T if B!=b)] ``` [Try it online!](https://tio.run/##bYxRa4MwFEbf/RV3b0m9jllX2AoZTOiD776FPFxtpNE2arBspfS3u6RshZVCINzD@c5wmna9zd4GN88boe3xoB1NOtrqBhq25@sIRiyFZJIUSv@M4k3vwCCBsbDxSuARfO3MXsPofSCssRDj89AP7IV7UMY@QFhw70FYt9j9rcMATAPtx4G@WcHJblkthFReI5mkKumEqPl6vDZi2Sn8xVjEslWh6fR0dFbStU1YhXYZorafgOyJ@f@8qC7JeZFfgvOJ@c3Jn0TF1Tw4YyfWMKk4j25H@v7/xBSXdyTDFWZ3bOnp60P60PRs/gE) [Answer] # JavaScript (ES6), 149 bytes ``` a=>(o=[...Array(1<<a.length).keys(g=n=>[x,y]=a[F]((_,i)=>n>>i&1))][F='filter'](n=>!g(n).some(p=v=>p-(p=v)+y-x)))[F](p=>o.every(q=>p&q-p|q==p)).map(g) ``` [Try it online!](https://tio.run/##dY3LasMwEEX3/Qp3k8xQWcFxsyhkBN3kJ4QoIpVdt44kPzAx9N9duSbUThNtLjNzju6n7nRzrAvfxta9myGjQZMAR5Jz/lrXuodkv9e8NDZvP5B/mb6BnCwJeWa9Ii0PCuCNFUjCClGsEkQlD7TOirI19VpBQB9zsMgbdzLgqSPh4zHxqY/PiDj@4Ek4bjpT91CF@6qK/XdF5BH5SXvIcTg627jS8NLlkIFU0eUhRptNJNXDFZG8qCURFv8YlrCtmjNhZLNIbigp27FUzZR0ZNMpdlP8Ujfcbdg/B@SvbmGPp@iC3dEX1Ut9mu@0XmlhMfwA "JavaScript (Node.js) – Try It Online") ## Commented ### Helper function ``` g = // g is a helper function (actually defined in the n => // scope of the main function) taking an integer n // and returning a sublist of a[] [x, y] = // save the first two entries in global variables a.filter((_, i) => // for each value at index i in a[]: n >> i & 1 // keep it only if the i-th bit of n is set ) // end of filter() ``` ### Main function ``` a => ( // a[] = input array o = [ // build the range going from 0 to 2**N - 1 ...Array( // where N is the length of a[] 1 << a.length // (i.e. all possible bit-masks of length N) ).keys() // ].filter(n => // for each value n in that range: !g(n) // build the sublist for the bit-mask n .some(p = v => // for each value v in this sublist: p - (p = v) + // discard the sublist if the difference y - x // between v and the previous value is not // equal to those of the first 2 entries ) // end of some() ) // end of filter(); save the result in o[] ).filter(p => // for each value p in o[]: o.every(q => // for each value q in o[]: p & q - p | // make sure that either at least one bit q == p // set in p is not set in q, or q = p ) // end of every() ) // end of filter() .map(g) // translate the bit-masks back to sublists ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~58~~ 53 bytes ``` F⮌EX²Lθ⌕A⮌⍘ι²1F›⬤υ⁻ικ⊙ι∧›λ¹↨E⁴§θ§ι⁻λ↔⊖μ±¹⊞υιEυ⭆¹Eι§θν ``` [Try it online!](https://tio.run/##VY9Nb8IwDIbv@xURJ0fyDincOHWaNiHBVLEj4pC1XhstpCNJYfz64ASNab7EH49fv2kH7dtR25Q@Ry9gSyfygWCjv6EZz@ShQrEm18cBjlKieDGuq629g0860Hv0xvVgUFQZmamZ5BBF8NWTjiyTdyYUG@OmkMmvTNbukvPadXfOolA8ybLFxILHceU6@oHjX2p@lRivP8Jop0jwTK2nA7lIHRxkCRRv1LMuqFstmikM2YeRy4eGXcdyhBu3P@RCsTY/5t9hV9aXKe12Ciuc4wLn@316PNkr "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⮌EX²Lθ⌕A⮌⍘ι²1 ``` Loop over the sublists of the indices of the list's elements from largest to smallest. ``` F›⬤υ⁻ικ⊙ι∧›λ¹↨E⁴§θ§ι⁻λ↔⊖μ±¹ ``` If this isn't a sublist of an already found list but is linear, then... ``` ⊞υι ``` ... save this as a new maximal linear sublist. ``` Eυ⭆¹Eι§θν ``` Convert the lists of indices to lists of elements and pretty-print them. Linearity is determined by taking a sliding window of size `3` and computing `x[1]-x[0]+x[1]-x[2]` which should be `0` in all cases. This answer could be written as a single statement instead of four but it would still be ~~58~~ 53 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā<æʒè¥Ë}©ʒ®€æ€`»sðý¢}è ``` [Try it online](https://tio.run/##ATcAyP9vc2FiaWX//8SBPMOmypLDqMKlw4t9wqnKksKu4oKsw6bigqxgcy7Con3DqP//WzEsMyw1LDNd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P8jjTaHl52aFFF8eMWhpYe7aw@tPDXp0LpHTWsOLwMSCcV6hxbVHl7xX@d/dHSsTrShJYjQMdQxAtPGOqY6xmCWEZBtgsRGEo2NBQA). **Explanation:** ``` ā # Push a list in the range [1, input-length] < # Decrease each by 1 to make them 0-based indices: [0,length) æ # Get the powerset of this ʒ # Filter it by: è # Index each into the (implicit) input-list ¥ # Get their forward differences Ë # Check if all are the same }© # After the filter: store the list in variable `®` ʒ # Then filter once again: ® # Push list of lists `®` €æ # Get the powerset of each inner list €` # Then flatten it one level down s # Swap so the current list we're filtering is at the top .¢ # Count how many times this sublist occurs in the larger list of lists # (only 1 is truthy in 05AB1E) }è # After the filter: index each value into the (implicit) input-list # (after which the resulting list of lists is output implicitly) ``` ~~Unfortunately, almost all of 05AB1E builtins are vectorized, hence the need for the `»` and `ðý`.~~ -2 bytes, because luckily with the count builtin `¢`, there is a non-vectorized alternative `.¢`. :) ]
[Question] [ ## Background Fibonacci numbers are defined as follows: $$ F\_0 = 0, F\_1 = 1, F\_n = F\_{n-1} + F\_{n-2} $$ The **Zeckendorf representation** is a representation of positive integers as a sum of one or more non-adjacent Fibonacci numbers, using indices 2 and higher. It is known that such a representation is unique for every positive integer ([Zeckendorf's theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem)), and it can be written as a positional base system using digits 0 and 1. For example: $$ 65 = 55 + 8 + 2 = F\_{10} + F\_{6} + F\_{3} = \overline{100010010}\_F $$ The **\$F\_{4k+2}\$ representation** is a similar representation but using every fourth Fibonacci number only, and with digits of at most 9. Some examples: $$ \begin{align} 7 &= 7F\_2 = \overline{7}\_{F\_{4k+2}} \\ 8 &= 8F\_2 = \overline{8}\_{F\_{4k+2}} \\ &= F\_6 = \overline{10}\_{F\_{4k+2}} \\ 65 &= F\_{10} + F\_6 + 2F\_2 = \overline{112}\_{F\_{4k+2}} \\ \end{align} $$ Note that this representation is not unique in general. I invented this to multiply two numbers in Zeckendorf representation in subquadratic time, from the fact that the product of two \$F\_{4k+2}\$s can be expanded to a sum of \$F\_{4k+2}\$s: $$ \begin{align} F\_2 F\_n &= F\_n \\ F\_6 F\_n &= F\_{n-4} + F\_n + F\_{n+4} \\ F\_{10} F\_n &= F\_{n-8} + F\_{n-4} + F\_n + F\_{n+4} + F\_{n+8} \\ &\cdots \\ F\_{4k+2} F\_n &= \sum\_{i=-k}^{k} F\_{n+4i} \end{align} $$ ## Task Given a positive integer in Zeckendorf representation, output the same number in \$F\_{4k+2}\$ representation. If there are multiple possible representations, output any of them. Both the input and output may be represented using a list or string of digits, in the order of increasing or decreasing positional value. For example, if the given number is `11`, you may choose to take e.g. `"10100"`, `"00101"`, `[1, 0, 1, 0, 0]`, or `[0, 0, 1, 0, 1]` as input, and give `"13"`, `"31"`, `[1, 3]`, or `[3, 1]` as output. ## Test cases ``` Number Zeckendorf F4k+2 (not showing all possible answers) 7 1010 7 10 10010 12 12 10101 14 51 10100101 63 144 10000000000 242 233 100000000000 415 490 1001001000100 1203 or 1172 or 862 986 10101010101010 2414 ``` [Answer] # JavaScript (ES6), 88 bytes Expects a binary array in reverse order. Returns an array which may include leading 0's. ``` a=>a.reduce((q,c,i)=>(t+=c*=x=y+(y=x),i&3?q:[x,...q]),[],t=y=0,x=1).map(x=>t/(t%=x,x)|0) ``` [Try it online!](https://tio.run/##ZZFRT8IwEMff@RQXEk1Palm7wUBy88lXv8CyhzqKYgaDbZAS9bPPFgYqXntp0/vd3T/Xd73XdV4tN839upybdkGtpkSLysx3uWFsy3O@REpYM6D8jiwdBuxAFvnyNnzcPqSWCyG2GfI04w0dKOCWJIqV3jBLSTNkzQ1ZbvEzwHaW9gD6MpBBn8MvGw6Bxegu8Sl@Dfi4DBwg1bmA/A8oD0Rn4C/jgZF0wDjsWpytY44VoghBReqK6BBPqDBEiOToItNv70fEE9HU6ZQqCKGsQMpY@XMy/tF9Wf0uYzoZ@65OedYTi7J60vkbq4ES@HBJhWlAA0Hqplxnx7E@71YvpkL3Q3tT1YbhzHF5ua7LwoiifGULptE9fmH7DQ "JavaScript (Node.js) – Try It Online") ### How? We have two steps: 1. During the `reduce()` step, we convert the input array \$a[\:]\$ of length \$L\$ into an integer \$t\$ by computing Fibonacci numbers \$F\_2\$ to \$F\_{L+1}\$ and adding those for which the corresponding entry in \$a[\:]\$ is set. At the same time, we store the Fibonacci numbers of the form \$F\_{4k+2}\$ in this range in an array \$q[\:]\$, from highest to lowest. 2. During the `map()` step, we convert \$q[\:]\$ into the final output by computing \$\lfloor t/x\rfloor\$ for each entry \$x\$ and reducing \$t\$ modulo \$x\$ after each iteration. ### Commented ``` a => // a[] = input array a.reduce((q, c, i) => // for each value c at index i in a[], ( // using q[] as the accumulator: t += // add to t ... c *= // c multiplied by ... x = y + (y = x), // the next Fibonacci number x i & 3 ? // if i is not a multiple of 4: q // leave q[] unchanged : // else: [x, ...q] // append x at the beginning of q[] ), // [], // start with q = [] t = y = 0, // start with t = 0, y = 0 x = 1 // start with x = 1 ) // end of reduce() .map(x => // for each value x in q[]: t / (t %= x, x) // return floor(t / x) | 0 // and reduce t modulo x ) // end of map() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` Fθ⊞υ∨¬υΣ…⮌υ²≔ΣE⮌θ×Iι§υκθF⮌Φυ¬﹪κ⁴«I÷θι≧﹪ιθ ``` [Try it online!](https://tio.run/##RY5dC4IwFIav9Vfs8ggLLLrrSozAC0usPyC68uB0uQ8pot@@NkUa28U4z3uet24rWYuKW3sXksAYkcKoFgwlFwlnocFElFxND@m75ixtxRNKNjGp2DzZRe4cwkQpfAzgubz6E6MjbtgzBWmlNKD7JjobGvbygs5nKRldfnavqRNyzaQnvD8XjeECOkr2no/IJwwKiYNedmaDPuKEjZNRgnOZwFVYCpX4aNcNbrq4vtZu43i5/tnNxH8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fθ⊞υ∨¬υΣ…⮌υ² ``` Generate `F(2)...F(n+1)` where `n` is the number of bits in the input. ``` ≔ΣE⮌θ×Iι§υκθ ``` Convert the input from Zeckendorf to integer. ``` F⮌Φυ¬﹪κ⁴«I÷θι≧﹪ιθ ``` Greedily convert the input from integer to `F(4k+2)`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 19 bytes ``` ƶ+ÅfODÅF4ι2èRvy‰`s? ``` [Try it online](https://tio.run/##yy9OTMpM/f//2Dbtw61p/i6HW91Mzu00OrwiqKzyUcOGhGL7//@jDXQUgMgQQsYCAA "05AB1E – Try It Online"), or [try all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfGRzk8v/YNu3DrWn@Lodb3UzO7TQ6vCKorPJRw4aEYvv/tYe22f@PVjI0MDRQ0lEA0nAGEMIYCDYcoHERmkEIhOGGwKFSLAA) -2 thanks to @Kevin Cruijssen Takes the input as a reversed list. Turns the number from Zeckendorf representation to an integer, and then finds an \$F\_{4k+2}\$ representation greedily. ## Explanation ``` ƶ multiply each number by its 1-based index + and add that to the original list, so effectively we multiplied by the 2-based index Åf get the n-th Fibonacci number, for each N in that list O and sum, let's call it V D duplicate ÅF list the fibonacci numbers less than or equal to it 4ι uninterleave to four lists [a[0::4], a[1::4], a[2::4], a[3::4]] 2è and take the third element, a[2::4] R reverse that list v and for each element in the list: y push it ‰ calculate divmod(V, element) ` dump (division, mod) to the stack s swap, to get (mod, division) ? and print the result of the division without a newline, leaving the modulo in the stack in place of V. ``` [Answer] # [Python](https://www.python.org), 150 bytes ``` def f(i): a=b=g=1;o=0 def n(o): while(z:=(o+g-1)//8&g):o-=o//8%2-(z*145>>4) return o while i:o=n(o+i%2*b);a,b=b,n(a+b);i//=2;g=16*g+1 return o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XU9JboQwELz7Fb5MZLMEtzEMA_LkKREoLJaQjQijJPOQXHLhkrwol_lNzBJE0ral7ip3dfXHV_c2NEaP4-dlqPzk9v5UVrgiiqYI57KQtYTMSIbwhGtiJhy_NKotyTWVxLi1DzQIkruapsaXxqYH7pOrAyI6nwW1v_tyuPQaG7T0YZUaaZVcdeBOQbPcK2ThaZK7tlBBIHlmh8ZO7QLaeld3D5XpcYuVRbpSEza5efSUZ2R7_9y1aiB2YNcrPRDlNeUrsZvMOaeUeoYuMuPt-4jnAAYM7-KI1hrYXwY4Ar61wJ4RKIKN2ZNxiECIVe03ZoYLjngY_qNmTkCExIltHqY7vdkDC9EpiTcX25kUQSzL_QA) Expects binary coded Zeckendorf and returns hex coded F4k+2. ## How? Uses the identity \$7F\_n= F\_{n-4}+F\_{n+4}\$ to express addition in F4k+2 using "two-sided carry". ]
[Question] [ *A sequel to [What dice do I need to display every integer up to X?](https://codegolf.stackexchange.com/q/260434/117794)* Numbers are great, but let's take it to the next level. I'd like to have a set of dice that can be arranged and rotated to display any words I want. Think Boggle: [![Boggle dice spelling a word](https://i.stack.imgur.com/6LKsD.jpg)](https://i.stack.imgur.com/6LKsD.jpg) And not just that; I want to specify the number of sides those dice have. The set should contain the fewest number of dice possible. For example— If I want to be able to display any of the following words with 4-sided dice: ``` CODE GOLF IS VERY FUN ``` I would need 4 dice with the following letters on their sides (each line represents a die): ``` C G I V O S R U D L N Y E F ``` Note that the last die only has letters on two of its sides. ## The challenge: * Given a number of sides N, and 1 or more words, write a program that outputs the N-sided dice that are required to be able to display all of the words (one at a time). * The first input is always an integer, 4 at minimum. This number determines the number of sides that each of the dice will have. * All other inputs are strings of English-alphabet capital letters, at least 1 character in length. They may be provided in any format you like; delimited, a list, array, etc. * Each side of a die must be either blank or contain a single English-alphabet capital letter. * Unlike the number challenge, you do **not** need to ensure that every die is used for every word. If there's a two-letter word and 4 total dice required, you only need to ensure that 2 dice have the correct letters on them. * Output must be provided so that all the letters on each die is shown, and each die is separated somehow. So `CGIVOSRUDLNYEF` is not valid output for the above example, but these are valid: ``` CGIV OSRU DLNY EF CGIV OSRU DLNY EF ["CGIV", "OSRU", "DLNY", "EF"] [["C", "G", "I", "V"], ["O", "S", "R", "U"], ["D", "L", "N", "Y"], ["E", "F"]] ``` * The dice in the output, and the letters in each side do not need to be in any particular order. * A correct solution outputs the fewest possible dice given the inputs. * There may be multiple correct outputs for a given input. You need only output one. Here are a couple more test cases: ``` Input: 4,EASY,TEST,TEASE Output: E A T S Y T E Input: 5,MEDIC,FROG,WOW,ZEBRA,SCENES,ZOOM,BABOON,LOITER,XRAY,MEDIUM,GUEST,SUNDAY,ROMP Output: M S B L G Z A F W E D E B T M M Y S O R I N W X P U C O A Y ``` ## Bonus challenges: * Your program must also handle the number of sides being 3, 2, or 1. * Your program must assume that an `M` can be rotated and used as a `W`. `W` can never appear in the output. This also goes for `C` and `U`, `Z` and `N`, `H` and `I`. * A correct solution outputs the fewest possible *letters* for a given input, not just the fewest dice. [Answer] # [Python 3](https://docs.python.org/3/), 205 bytes ``` from itertools import* def f(n,w,k=1): for s in product(*[[*product(*[{*''.join(w)}]*n)]]*k): if all(any(all(W.count(c)<=F.count(c)for c in W)for F in product(*s))for W in w):return s return f(n,w,k+1) ``` A recursive function that accepts a positive integer, `n`, and a list of strings `w` and returns a tuple (collection) of tuples (dice) of characters (faces). **[Try it online!](https://tio.run/##VU49b4MwEN39K27zR1GkKFtURrx6QWJADBFg1Q25Q8YIRVV/O8EYper0Pu7uvRuf4Yvwsq7W0wNc6H0gGiZwj5F8UKzrLViB2ZLd87O8MrDkYRsjjJ66uQ1C1bX64z@K89M3ORSL/G0UyqZR93gHzsJtGMQNnyJidWppxiBa@ZnrN4/pbUyvdqr/FU1yN6toLvLq@zB7hInBwY4/P85yXch3E@RQ87IoeAa8NCaCTkofyiRVlGlFRzDJNGml2A4ahlvUhY3ebU/GFtjzpWTrCw "Python 3 – Try It Online")** (adding `'FFF'` [requires four dice](https://tio.run/##VU49b4MwEN39K27zR1GkKFtURrx6QWJADBFg1Q25Q8YIRVV/O8EYper0Pu7uvRuf4Yvwsq7W0wNc6H0gGiZwj5F8UKzrLViB2ZLd87O8MrDkYRsjjJ66uQ1C1bX64z@K89M3ORSL/G0UyqZR93gHzsJtGMQNnyJidWppxiBa@ZnrN4/pbUyvdqr/FU1yN6toLvLq@zB7hInBwY4/P85yXch3E@RQ87IoeAa8NCaCTkofyiRVlGlFRzDJNGmlOA605g3DLfHCRu@2X2MZ7DVSsvUF)) It's too slow for the test cases as it is checking all possibilities (hence the inputs given in the TIO links, with `n=3` and a very small set of letters). We could prune the dice being considered by only using those with `min(n, number of unique letters in inputted words)` unique faces, which most of the time would mean we only consider those with `n` different faces, and we could start our considerations with `min(word length)` dice, but doing both still won't be enough to complete the given test cases on TIO. [Answer] # Python3, 1070 bytes: ``` from itertools import* P=permutations def U(w,c):c=[i for i in c if i];t=[''.join(j)for i in P(c,len(c))for j in product(*i)];return[i for i in w if all(i not in j for j in t)] E=enumerate def f(w,n): C=-1;G=eval(str(w)) while 1: C+=1 q,S=[(G[:i]+G[i+1:],[[j]for j in a]+[[]for _ in range(len(max(G,key=len))-len(a))]+[[]for _ in range(C)])for i,a in E(G[:1])],[] while q: a,b=q.pop(0) if not a:return b F=0 for m in sorted([K for i in P([*E(b)],len(a[0]))if(K:=[(u,I)for(u,x),(I,y)in zip(E(a[0]),i)if x in y])],key=len)[::-1]: I={i for i,_ in E(b)}-{i for _,i in m};w={i for i,_ in E(a[0])}-{u for u,_ in m};W=0 for i in P(I,len(w)): B=eval(str(b));T=1 for x,y in zip(i,w): if len(B[x])<n:B[x]+=[a[0][y]] else:T=0;break if T and B not in S:q+=[(U(a,B),B)];S+=[B];W=1 else:W=max(W,0) if W:F=1 else:F=max(F,0) if F==0: for i in P(E(b),len(a[0])): B=eval(str(b));T=1 for(x,_),y in zip(i,a[0]): if len(B[x])<n:B[x]+=[y] else:T=0 if T and B not in S:q+=[(U(a,B),B)];S+=[B] ``` [Try it online!](https://tio.run/##rVNhb9owEP3Or7C0D7HLtQJ1k6YwfwDqINTRVCSMtZZVBWpWU0hCSAZs6m/vbCcw2k2bJk1COd3l3bv37kK6yx@S@Px9mj0/z7JkiVQuszxJFmuklmmS5Se1a5rKbFnkUa6SeF27lzM0whuYEndKuUKzJEMKqRhNkZohJVo55Y5zNk9UjOfk8PYaT2EhYzwltjY3tTRL7otpjk8UEa1M5kUWHxNuDGG0WGCF4iQ3lTk69OZE1BiVcbGUWZRLK2umZcXEraEuPW22elR@jRZ4nWd4Q0gNbR7UQqKmfo26ddrUYQUB5bjHXSXqPa7qTVcA53NxGBKJOuc2vTNpFsVfJDYultEW9@BR7qjOCDk1tYiQ38G7RJRbgMgUmZnXFERPElpCKWplRKEIJnR1liYpbhCTa/fGd@SWq0ETU/RowwTDuDR8a30jeY/5JTpaNT9heKJHWFm8IQhRM3zparMF9I0aHbcEcB92RDd8UylmJRCUhqKtodkZkXuL3HVPm8LKRH36vboS3JWWJuTptKrdgdWwfGptfoHZCRpZ2HJRljVyXHo6dtC32vXdypGo8/OYE0Jaob1f1bKFHapcKNjsO8z6DEeHbwX5ELsm1ik3GvhOiAokF2vphrTRmmQyeqztG0MUxfeos//uAnelW/EIR9Ah@idagc47QiuvdFieMTXfxRjK8xmesetVCAvwLMCDw309Shvua@9mn0en@/sG8BbuyPESbOOf97B7vYF/9f6cZirO8Qxzp@tfMAeQ0/M/eib2A/P8xIY3JnqjK0fAW/0X3Hc4rB3cQMiCUD/aAXPO1ulC5dgBh7wAcidkljn0fUtVZl6V@WXGwhJiZ/tl0S8hTDcIOP/flAbieRXzm4OtAbvod8Eb@j0Y@2O4ZZ1hG4Iuu2IB3Pr@ADrtju9fwUe/H7IhfB62b8D0jAbQG5ltBKOrC10b@oPrFzt5RwgK1VKuUVLkzz8A) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 133 bytes ``` NθWS⊞υι≔⟦⊞OE⌈⊞OEυLιL⪪⪫υωθωυ⟧υ≔⟦⟧ηFυ«≔⊟ιζ≔§ζ⁰εFΦEXLιLε﹪÷κXLιEενLι⬤κ⁼¹№κμ«≔Eι⁺λ…§ε⌕κμ›№κμ№λ§ε⌕κμκ¿⬤꬛Lλθ¿⊖Lζ⊞υ⊞OκΦζμ⊞ηΦκλ»»⊟Φη⁼Lι⌊EηLλ ``` [Try it online!](https://tio.run/##bVJNb4MwDD2XX5FjIjFp27Wnql/q1C@px2kHBm4TNSQUkrZj6m9nNgXG1B1AsZ@f/fySWEZ5bCNdVQuTebf26Sfk/CSGwUUqDYzX6Z3LlTlwIdjWF5L7kCmsGBWFOhj@TrlNBnnkbM5XUYbfVaU@5Q8AEpdgDk5yJUR33mVaOf5mlaGCCwInIQinoxcf9PudhqHEcG9zxr1g38GgQbY2w7YhKxFtcyO3MAlceRmyZ4SAoJo5U9rBXdTWXvDU6epkAUlY2cRriy64iTqrBPgxZA8E6gIhM6K3lKqDkdbEmJ58pAv@ErKx9cZRKqUVa/mtVuqisLv2BddY@RVrGEtcql0CR8yUSRp2yOY5RLREr2c7APn/s8Td2SMZMVB7xhuFa@t426/ZQLcXwahuAnEOKRgHSVtQit6D@HPXR5pZG1zepw4Z6ALuxbIDsUwLUnILbsEWn5irL7FBZedb32pl6qdFZsnObN0sNqyq12C8mUyD@WY5C6qns/4B "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an integer and a list of newline-terminated strings. Explanation: Brute force, so incredibly slow; link only has two words because that's all it can solve in a reasonable amount of time. ``` NθWS⊞υι ``` Input `N` and the words. ``` ≔⟦⊞OE⌈⊞OEυLιL⪪⪫υωθωυ⟧υ ``` Start off with a number of blank dice equal to the minimum of the length of the longest word or the minimum number of dice needed to write each letter of each word on its own face, and all of the words needing to be placed. ``` ≔⟦⟧η ``` Start collecting possible placements. ``` Fυ« ``` Process all of the partial placements. ``` ≔⊟ιζ ``` Get the remaining words. ``` ≔§ζ⁰ε ``` Get the first word. ``` FΦEXLιLε﹪÷κXLιEενLι⬤κ⁼¹№κμ« ``` Get all of the permutations (even on the first iteration where it makes no difference whatsoever) of placing the letters of the word onto the dice. ``` ≔Eι⁺λ…§ε⌕κμ›№κμ№λ§ε⌕κμκ ``` Get the result of this letter placement. ``` ¿⬤꬛Lλθ ``` Check that there aren't too many letters on any of the dice. ``` ¿⊖Lζ ``` If there are more words left to place, then... ``` ⊞υ⊞OκΦζμ ``` ... create the next partial placement to be processed, otherwise... ``` ⊞ηΦκλ ``` ... collect the possible placement, removing any empty dice. ``` »»⊟Φη⁼Lι⌊EηLλ ``` Output any of the placements that have the fewest dice. Since the above version is so inefficient, I have also written a slightly less inefficient 175 byte version that can handle slightly less trivial cases: ``` NθWS⊞υι≔⌈EυLιη≔⊟Φυ⁼Lιηζ≔⟦⊞OE⌈⟦ηL⪪⪫υωθ⟧⎇‹ιη§ζιω⁻υ⟦ζ⟧⟧υ≔⟦⟧ηFυ«≔⊟ιζ¿ζ«≔§ζ⁰ε≔Φζλζ≔EΦEXLιLε﹪÷κXLιEενLι⬤κ⁼¹№κμEι⁺μ…§ε⌕κν›№κν№μ§ε⌕κνδ≔⌊EδL⪫κωεFδ¿›⁼εL⪫κω⊙κ›Lλθ⊞υ⊞Oκζ»⊞ηΦικ»⊟Φη⁼Lι⌊EηLλ ``` [Try it online!](https://tio.run/##bVNNT8MwDD0vvyLHRCoScOWEgCEQo5XGbdqhrGGJliZdmjA2xG8vdvo5QS9J6/ee7Wd3I3O3sblumidTBf8aynfh2J7fkINUWlAWPy@9U2bLOKdZqCULCVWAuK1rtTVskX@pMpRwVhh5EWbrJVOcJ1SOqMxWbK60B3UAPexDrms2YBGKhNNIWGGqtBIu99ZF8T7RSg5ZlpVWnj1bZVD1AAp7ztdwvAlncneEDHXNFMon9NY/mUJ8sROW36IXyoQaqavTGogJDZMC1m0DH9ZRFjj9JrNJL6qrdqY@KDvFaB@e5LkElEBUH@ssgJDuBWaDj4NDeM3sAW4Th7qrQJ8WtgjawnD8vfpUhWC7hP4hoIpIqInOjmNBJ7RGRjeFq4Te2WA8fip5BCAVXMs0uFNC@LjR4k5C231voDtXpkCKQcKjEzlWPggZ3quWo/PnrPZJaHHmgjLDNhVD2XHCO5xZZLSWxsEUnOIE@vxdS@JfJhRijvjSozuMbvdmst5nu7fDQWHGHzITuhYtSmIvcVpg1A7jPySD38RPV13@t@rTFsdV1p0fN01zTe5T8piSdE7SV7JMyVtKmotP/Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Only one permutation of the longest string and only word placements that reuse the most possible dice are considered, so for the example of `TOO` and `ON`, the letters of `TOO` will be put on three dice, and then the `O` of `ON` will never be matched with the `T`. ]
[Question] [ The Cabbage, Wolf, Goat riddle with a twist! ### Backstory: There’s an intergalactic river than needs to be crossed! Being a space-ferryman you’ve offered some aliens on your small space ferry that can only carry two entities: you and a passenger. However, you know that because politics, some of these aliens will instantly zap some other aliens if they are left at on a planet unsupervised. Supervision means **you** are watching them. (Once they go to the other side, they are no longer affiliated with you and you can just let them sort it out amongst themselves). Being an uneducated earthling, you have no way of knowing who will zap who until you meet them, and therefore you can’t plan who will ride your ship when. So, you decide to write a program that will instantly plan your route. ### Input: Input can be taken in any way that [makes sense](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/2450#2450). It will be a list of strings. The first character of the string will be a length 1 name of the alien. The second character of the string will be who the alien will zap. If there is no second character, the alien is at peace with everybody (unless it has been previously declared that somebody hates that alien). Examples: * `["WG", "GC"]` - the original riddle. * `["YB", "BU", "UJ", "YJ"]` - the Yipiyuks zap the Bobles, the Bobles zap the Umpalumps, the Umpalumps zap the Jogos, and the Yipiyuks zap the Jogos. * `["YB", "U"]` - the Yipiyuks zap the Bobles, and the Umpalumps are just sitting there chilling. * `["YB", "B"]` - the Yipiyuks zap the Bobles, and even though the Bobles want to chill, they can’t. ### Output: Output the solution to the puzzle. The first element of the list will be who goes on the first trip to the destination. The second element of the list (if necessary) is who will come back from the the destination. The third will be who goes to the destination on the second round, and so on. Redundant trips must be avoided (ie. the Yipiyuks go and then come back again.) If there is no solution, output something that is distinguishable from a solution. If there is more than one solution, output any solution as long as it is correct. Examples: * `["G", "", "W", "G", "C", "", "G"]` - Solution to the original Cabbage Wolf Goat riddle. The Goat goes, and nobody goes back. The Wolf goes, and the Goat goes back. The Cabbage goes, and nobody goes back. And finally, the Goat is brought to the other side. * `["Y"]` The Yipiyuks go to the other side, and nothing else happens. ### Test Cases ``` ["WG", "GC"] -> ["G", "", "W", "G", "C", "", "G"] ["YB", "U"] -> ["Y", "", "U", "", "B"] ["YB", "B"] -> ["Y", "", "B"] ["YB", "BU", "YU"] -> No Solution ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), 180 bytes ``` def f(l): X={''}.union(*l);B=X-X;n=1;q=S=L=[] while n or B: while~-len(B)and B in map(set,l)or(n,B)in S:n,B,L,*q=q for i in X-B:q=*q,1-n,X-B-{'',i},L+[i];S=*S,(n,B) return L ``` [Try it online!](https://tio.run/##bZCxasMwEIZ3P8XhxZIrFUI3Gy3qEAimizF1MB5CIxOBerIUmTaU9NVd2YF2aJZD9@n@j@PGSzhZfJrnoxpgIIYWCbTiK8uujxNqiyQ3tJSi5W2JYlM6UYtKdH0CHydtFCBYDzJmbv03NwqJpAc8ggSN8H4YyVkFZqj1BJmkkdVFfLCK5U64GByiQS@zLZeFE7ljG44sNjxuwfSVVQ@d7sta5DVbFQl4FSaPUM2j1xjIQLr0dZsySLfPaU9p8of3csHNXSpXGvwlrv/vr1nq/hZUn29qDL9T2YuFszVTiOfJ7mjXaLNbBbtFMP8A "Python 3 – Try It Online") Raises an exception to indicate no solution. [Answer] # JavaScript (ES7), 187 bytes Returns a string, where `,` means that there's no alien in the ship. Throws an error if there's no solution. ``` f=(a,N=0,s=new Set(','+a),M=2**s.size-1,g=(o,m)=>m^M?[...s].some((v,i,b)=>!o[N]&a.every(s=>~(m^m%2*M)&(h=n=>1<<b.indexOf(s[n]))(0)+h(1))&(m>>i^~m)&&g(o+v,m^1<<i^!!i)):O=o)=>g``?O:f(a,N+2) ``` [Try it online!](https://tio.run/##fZDRasIwFIbvfYpYWJvYmKmXaiooQxDUCxGR0mKsae0wzWg6Nyf66l1aKXMOFkhI8n/fOSGv7MhUkMZvWTORO57nIYUMz2gLK5rwD7DgGbSwZTOEp7TTaCii4i/ebOOIQokFoo7wpwOXEKI8oqTgEB5xjLc6qEt35pmM8CNPT1BR5wqFL546jSky4Z4m1Gn3@1sSJzv@OQ@hchMPIdhC9h62kUaE48T@VSDTjKC0j1j4mo/9ej1GqDunUreINpvBvBsWL7Y7KO@5NQBcYzU2MDDGI8PD4G48P@usjIq5KpliGVVXY8Mr/fWwOC0f9Ju/ruBltRn@sob/WzoG93RZZf3TStMzCRby8J7FMvlDLiclP9FVbqSqSK9GQpm@sGAPGaAOOGs3S0/gDAKZaIqTg4yg/imEeuACApZpkqOH3OJpKlOrQGoXlH8D "JavaScript (Node.js) – Try It Online") ## Commented ### Wrapper ``` f = ( // f is a recursive function taking: a, // a[] = input array N = 0, // N = maximum number of rides - 1 s = new Set(',' + a), // s = set of alien characters // + a leading comma for the pilot M = 2 ** s.size - 1, // M = bit mask of passengers (pilot + aliens) g = ... // g = main search function (detailed below) ) => g`` ? O // if g() does not succeed, : f(a, N + 2) // increase N until it does ``` ### Search function ``` g = ( // g is the main recursive search function taking: o, // o = output string m // m = bit mask of transferred passengers ) => // bit #0 is the pilot m ^ M ? // if m is not equal to M: [...s] // turn s into an array .some((v, i, b) => // for each character v at position i in b[]: !o[N] & // abort if we've reached the max. number of rides a.every(s => // for each string s in a[]: ~(m ^ m % 2 * M) // take the 1's complement of either m or m XOR M & // depending on the side of arrival ( h = n => // h is a helper function that turns the 1st or 1 << // 2nd character of s into a bit mask according b.indexOf(s[n]) // to its position in b[] (2**31 if not found) )(0) + h(1) // if both antagonists are there, we have a *ZAP* // situation ) & // end of every() (m >> i ^ ~m) // make sure the passenger is on the departure side && // if successful: g( // do a recursive call to g: o + v, // append v to the output string m ^ 1 << i // mark the passenger as transferred ^ !!i // unless the passenger is the pilot himself, // mark the pilot as transferred as well ) // end of recursive call ) // end of some : // else: O = o // success: save the solution in O ``` ]
[Question] [ The famous game of [Qwirkle](https://www.ultraboardgames.com/qwirkle/game-rules.php) has simple but intricate rules (See part 2 of this question for a summary of the rules!) 1. The Challenge You are somehow (text input, function parameter, whatever) given a board of a Qwirkle game, like a snapshot from any current timeframe within a game. This board can be anything from completely empty to completely filled with tiles (max board size should be at least 32x32). Each tile can be one of six colors (red r, green g, blue b, orange o, purple p, yellow y) and one if six shapes (circle c, square s, flower f, zacks z, small star m, rhombus r). You can use any distinct letters as well! There are exactly three tiles of each shape-color combination in the whole set of tiles. Simple rules are: * each line (horizontal or vertical) of touching tiles must contain any distinct tile at most once and only tiles of different color and same shape OR tiles of different shape and same color! * every tile has to touch ar least one neighboring tile! No single/islands of tiles! Your task is to calculate wether the given board is in a valid state (see rules down below). That is, wether the given board does not break any of the rules. It can also be interpreted as 'a board that was created from a valid game, not breaking any of the game's rules'. The result is thus one of two possible values, either true or false, 1 or 0 or whatever you prefer. The result can be anything from a text output, a returned boolean or other variable type or whatever you want. Just somehow publish the result (don't just keep it inside a variable) 2. The Game Rules In a possibly infinite 2d checked board, tiles get laid. On every field on the board can either be one or no tile. There are 36 different types of stones, each 3 times, makes a total of 108 tiles. A board doesn't contain more than one set of tiles. (you only play with one sack. When it's empty, the game ends) 3. Special Things to Check * It's important to note that a valid game evolves around one start position. This means, any tile on the field has to touch any other tile through other tiles. There can't be single tiles or islands of tiles disconnected from the main starter island. So, any tile has to touch at least one other tile. * there are only 3 tiles of each color and shape in total. So there can't be, for example, 4 red square tiles or 4 green circles. * 4. Example Image This is an example of a valid qwirkle field: I think all of your questions can be answered by studying this image: [![valid example qwirkle board](https://i.stack.imgur.com/2roaC.jpg)](https://i.stack.imgur.com/2roaC.jpg) 5. Test Cases Note that test cases are going to be in an array (string with linebreaks or similar), for example: your program can take some other format (for example tabbed strings, semicolons as dividers or whatever! Doesn't have to accept any one! Just choose one specific format) ``` 0,0,rs,rc,0,0 0,0,gs,gc,0,0 ``` (this would be valid!) In this case i specified the input as color first letter, shape second letter. So rs is red square, gc is green circle etc. Any other format is ok! 6. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest working code in bytes wins! ## Test cases (based from comments, commas separate columns, semicolons separate rows): Truthy: ``` "" rc,gc,bc,oc,pc,yc;rs,gs,bs,os,ps,ys;rf,gf,bf,of,pf,yf;rz,gz,bz,oz,pz,yz;rm,gm,bm,om,pm,ym;rr,gr,br,or,pr,yr ``` Falsy: ``` rc,rs,rf,rz,rm,rr,rf rc,rs,rf,yc ``` [Answer] # [Haskell](https://www.haskell.org), 265 bytes ``` import Data.Maybe import Data.List i=isJust (#)=map a=all h=head j=fromJust t([]:_)=[];t x=(h#x):t(tail#x) v b=a(a(\z->any(a id)$t$(zipWith(==)$j$h z)#(j#z)))$map(filter(i.h).groupBy((.i).(==).i))b f b=v b&&v(t b)&&(a((==1).length)$group$sort$concatMap catMaybes b) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZG_TsMwEMbFiJ_CaqzIltJIbKjIDIgJURYGhhAhJ01sl_yTfSltXoWlC-J92OBpuLaqguj0-fP97k6f_f5plH8tqmq7_eihnF7-nJ3bumsd0FsFKp6rTVaQvzf31gOx0vq7Hg88ELJWHVFSVRUx0hRqQZaydG29rwNP0tmLkEl6BXQtuQnWYgYclK3wRFY0k4or_jxMr1Wz4YrahWDA-GC7JwuGSynYkhk6iIAvg0EIwXAdL20FheM2NiLWru27mw3nsRXxrgFVZKTE0Tg-DFccaCbCENdg9ULEVdFoMILtG5nHZCxvm1zBXHV0L5jZY8_hRb6_nKeS7uLQifMT4vLR5mjNaM2E6BHWCOsR1gjrEdYIkwJtkjy0YGyjo6M6H7k8cib6V0ijE1T7SOeRPkVTQmplG5zf9fAIjjLqTfuGUtLikOz4578) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~71~~ 69 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø«ε0¡ε€Sø€ËàyD¢*]˜PI˜áD¢4‹PIa©˜ƶIgäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅs«à]˜0KËP ``` Input as a matrix of 2-char strings, with `0` as gaps. Outputs a 05AB1E truthy/falsey result, so `1` for truthy, or `0` or a positive integer for falsey. [Try it online](https://tio.run/##yy9OTMpM/f//8I5Dq89tNTi08NzWR01rgg/vAJKHuw8vqHQ5tEgr9vScAM/Tcw4vBHJMHjXsDPBMPLTy9Jxj2zzTDy85N8XI7fAOg3Nb9A7vqAUxQTr3GNceWqd1buu5rYdbiysP7wCSh1YfXgA0yMD7cHfA///R0UqJSUo6SonJICJFScdAR6mqEsiuqlCK1YlWSksCCyVWAIXSKiDiOkoVQMlYAA) or [verify all test cases](https://tio.run/##jc8xS8NAFAfwvZ8i3KTlLIc6dSlCcXEwILiEDElNa6BtjuQivEKhCE5dHYu04iIVJ1NSdLoDl0I@RL9IvJcr4iDi8uPu/e@9u4sSzw@D8oacdETq9a1wyFPRtEgLaI3YcSAEHPA4HIrg6jujIN/ZdvLArEaT1qBNSpXLZZExuSiy7e3Lhcq1aqrm0JaPdXczs2EzUwu9Od5O1jZ48nkz@1xBTz0V94enKmfFW0PlY1xi58fRWL7Wi6zI1F0CKtfKpZrrQexMTe2SNC7JeSp2L223QmLtiTgV17BP1FJvul4/CfRmTOWKlo7jMMooiROi6RC9Zi41tR7WeruaSy3HMVbnqoD4SIRwBDpEN5thVbePRAhHIDF5F3PERyKEI9A1@QhzxEcihCMwMvkAc8RHIoQjMDB5jDniIxHCEYjJzy@YT@PF1Y3V2KpX134/hx/8xwBG/8xd1/0C). **Explanation:** Step 1: Verify that each connected portion in a row or column is valid, where valid means they're either all the same shape and/or the same color, and in addition there aren't any duplicated pieces in a connected row/column. ``` ø # Zip/transpose; swapping rows/columns of the (implicit) input-matrix « # Merge this list of columns to the (implicit) input-list of rows ε # Map over each inner row/column: 0¡ # Split it on 0s (the gaps) ε # Map over each connected portion: €S # Split each 2-char string to a pair of characters ø # Zip/transpose; swapping rows/columns €Ë # Check for each inner list whether they're all the same à # Pop and get the maximum, to check if this is truthy for either y # Push the current connected portion again D # Duplicate it ¢ # Pop both, and count how many times each piece occurs * # Multiply the earlier check to each count in the list ] # Close the nested maps ˜ # Flatten the list of list of list of checks P # Check if everything was truthy by taking the product ``` [Try just this first step online](https://tio.run/##yy9OTMpM/f//8I5Dq89tNTi08NzWR01rgg/vAJKHuw8vqHQ5tEgr9vScgP//o6OVipKVdBSUiorBZBqYrAKTuWCyCCoeGwsA) or [verify it for all test cases](https://tio.run/##jc8xSwMxFAfwvZ/ieJNKLJm7FKG7BcHlyHA57@pB24RcTkhBEFe/goi61rVScLsbhX6IfpEz/6SIg4jLj@T98154qs5kVfQ3dJbbJpsn1VI3dpTQ2LEBTU1hrTvVplra4uo7Y6794Pu7J54MR2zgJtR323a92/D2ZbfZ379ddFtv99A9u0n7eiI@H6c9DS/pvLGH4ZNxRcmRNY29dsfUrf2lzOZ14S@3rH1nfZqmnHFGpiZPTv7MBYu1GWqzQ02wJE2j4V0ISAIFNHA5@eY4LHRLoIAGro55iRxIoIAGroz5CjmQQAEN3CrmC@RAAgU0cIuYG@RAAgU0cIZ@rhCXxsfhxzA29Pra7@@w4D8GcPZnLoT4Ag). Step 2: Check that each individual piece does not occur more than 3 times: ``` I # Push the input-matrix again ˜ # Flatten it á # Remove all gaps by only keeping the letters D # Duplicate it ¢ # Pop both, and count how many times each piece occurs 4‹ # Check for each that it's smaller than 4 P # Check if everything was truthy by taking the product ``` [Try just this second step online](https://tio.run/##LcohDsJAEEDRqzSjKzkCBodvVjANJRXNTHbVVHEQDNwCS2VvwUUW8rPmqWflovO11tP@2J7Hz@vwvb/PtQ6D5FH6Tm6oaOgYo6S@@6/CQkVDxyhtTSxUNHSMqa2VhYqGjrG2tbBQ0dAxlrYyCxUNHSNLSj8) or [verify it for all test cases](https://tio.run/##jc@xasMwEAbgPU9hbkpBDRo6ZQkF783URXiwXDs1JJGQ5cIFAnmQUmjX7oXSzRn7FnkRV78USodSunxI9@tOnOlK3dbjA11Xvi/XWbu1vZ9ntGAxoaWrvedL69qtr@@@M8HDhzwdnmQ2m4sJ5zTy5@PxOR9erk6H9@VIs1u66f15UL5oKZt61/t7vqDja7g05bqrw2UvhjcxKqWkkIJcR4GKwlkWItVWqK3OtUJkSiXjuxiQBgZYwBWF5jQsdmtggAXcpbxBDjQwwAJuUr5DDjQwwALepXyDHGhggAW8SblDDjQwwAJ29HOFtDQ@jj/GsbE31H5/hwX/MUCKP/OiKL4A). Step 3: Flood-fill the matrix to check if everything is a single connected island (which I've done before in [this answer](https://codegolf.stackexchange.com/a/242094/52210) and [this answer](https://codegolf.stackexchange.com/a/247444/52210) of mine): ``` I # Push the input-matrix yet again a # Convert all pieces to 1s with the is_alphabetic builtin © # Store this matrix of 1s/0s in variable `®` (without popping) ˜ # Flatten it ƶ # Multiply each value by its 1-based index Igä # Mold it back to a matrix matching the input: I # Push the input g # Pop and push the length (the amount of rows) ä # Split the list into that many equal-sized parts Δ # Loop until the result no longer changes: 2Fø0δ.ø} # Add a border of 0s around the matrix: 2F } # Loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Map over each inner list: 0 .ø # Surround it with both a leading and trailing 0 2Fø€ü3} # Then split it into overlapping 3x3 blocks: 2F # Loop 2 times again: ø # Zip/transpose; swapping rows/columns again € # Map over each inner list again: ü3 # Split this list into overlapping triplets ®* # Multiply this matrix of 3x3 blocks and matrix `®` together, # so all 3x3 blocks at the 0-positions will become a block of 0s εεÅsyøÅs«à # Get the largest value from the horizontal/vertical cross of each # 3x3 block: εε # Nested map over each 3x3 block: Ås # Pop and push its middle row y # Push the 3x3 block again ø # Zip/transpose; swapping rows/columns Ås # Pop and push its middle row as well (the middle column) « # Merge the middle row and column together to a single list à # Pop and push its maximum ] # Close the nested maps and flood-fill loop ˜ # Flatten the resulting flood-filled matrix 0K # Remove all 0s (the gaps) Ë # Check if all remaining values are the same, so we have a single island ``` [Try just this third step online](https://tio.run/##yy9OTMpM/f/fM/HQytNzjm3zTD@85NwUI7fDOwzObdE7vKMWxHzUtObwHuPaQ@u0zm09t/Vwa3Hl4R1A8tDqwwtiT88x8D7c/f9/dLRSUbKSjoJSUTGYTAOTVWAyF0wWAUkDEIOQsthYAA) or [verify it for all test cases](https://tio.run/##jc8xS8NAFAfwvZ8ivEnlLIduXYpQXBx0cgkZcjWtgbZ3JBfhCgERnFwdizi4SMXJloJOOXAp5EP0i8T8c0UcRFx@3L3/3Xs8mYYijqorOurrLBx58URluuNR17AWnSWR1mZfJfFERxffGTPFO99cP3Cv3WEt06PKhMXzeva5NEP7VN4fHNsVL9/adpXjuLl5sR@HefG6Vy7Khb1NjV3VFnP7GKxn/MTeVdQ@p9NMb0f3ujF5OzrJ9KXZJTuvL4NwlEb1JWfFklW@73PGGSUp1fSpPvOAudoQteG2FjDP953NuyYgASRQwPSp/uyaNb8FkEABk7p8gBwIIIECZuDyKXIggAQKmKnLx8iBABIoYMYuT5ADASRQwCT0cwW3NAY3E5u2zd@69vs7LPiPBpz9mQdB8AU). Step 4: Combine all three checks of the previous steps, and output the result: ``` P # Simply take the product of all three values on the stack # (which is output implicitly as result) ``` [Answer] # [J](http://jsoftware.com/), 90 87 85 78 74 bytes ``` ((#@~."1@|:e.~1,#)@#~*/@,&,[:g+/@])(,:&(-/~)0j1&*)(g=.+./ .*^:_~)"[[email protected]](/cdn-cgi/l/email-protection):@1 ``` [Try it online!](https://tio.run/##hZDNauMwFEb3ego1Hiwp/SzHXQz0zqSIFgqFMosyu5Ca2ETqhDE2crqwCXr1VO60XXRauhDcq59zvqvd8fyEivX3EzoXgs20sHxJXHDwBae4Ms2v7m6vj1ImJuhZYQ601aFAokwS5rlBihW509yslQSlMsuDWuyKdK6kW@pTnXM9v6cyqNmZ2eo/ZIqjYr8uNZdBG5lTMM9gk8yKPLwjuLc3KqOojA41T@VkVSt6xy8uaH0wWb5mbL/t90u9Ii7l5kDmwmQ6QHHLv@10bhJa0Y2Wm6X@KcpSqEDxTECk9eP@hy7PGNvWDy0Xv/3j/mEQL52Iz8VLM/Gn71kwX8PVqGq0NboaQ818D9ej6tH26HoMPfMWzqKyaC06i8EyP8KNqEa0I7oRw8h8A9egatA26BoMDfMezqPyaD06j8Ez9ZmcleXkLMvnwk6Feh3ievO3Hz6KHXPGYDFJVEeXtx/y/92KY6mvEVH@3yZTxyc "J – Try It Online") ## argument encoding We take the list positions (encoded as complex numbers) as the right arg, and the list of pieces as the left arg. For example, for the board: ``` rc,gc,bc __,gs,__ __,gf,__ ``` the left and right arguments would look like this (boxed for clarity): ``` ┌──┬─────────────────┐ │rc│0 0j1 0j2 1j1 2j1│ │gc│ │ │bc│ │ │gs│ │ │gf│ │ └──┴─────────────────┘ ``` ## idea The high-level idea is the interesting part, so I'll focus on that. 1. Find all horizontally connected pieces. To do this, we create an adjacency matrix of all the positions, where adjacency is defined by the distance between two elements being in the set `_1 0 1`: ``` 0 0j1 0j2 1j1 2j1 +----------------------- 0 |1 1 0 0 0 0j1 |1 1 1 0 0 0j2 |0 1 1 0 0 1j1 |0 0 0 1 0 2j1 |0 0 0 0 1 ``` And then take the transitive closure of that matrix "or-multiplied" by itself until a fixed point. The result shows all the horizontal connections: ``` 1 1 1 0 0 <- 0 is connected to 0, 0j1, 0j2 1 1 1 0 0 <- 0j1 is connected to 0, 0j1, 0j2 1 1 1 0 0 <- 0j2 is connected to 0, 0j1, 0j2 0 0 0 1 0 <- 1j1 is only connected to itself 0 0 0 0 1 <- 2j1 is only connected to itself ``` 2. Find all vertically connected pieces. To do this, we reuse the logic in step 1, by first multiplying every position by `0j1`, which has the effect of rotating the entire board 45 degress left. Now vertical connections will be horizontal ones. The resulting final matrix this time is: ``` 1 0 0 0 0 0 1 0 1 1 0 0 1 0 0 0 1 0 1 1 0 1 0 1 1 ``` 3. Next, we use the rows from the previous steps as masks to define the groups of pieces we need to validate: ``` ┌──┬──┬──┬──┬──┐ │rc│gc│bc│gc│gc│ <- Vertically connected pieces │ │gs│ │gs│gs│ │ │gf│ │gf│gf│ ├──┼──┼──┼──┼──┤ │rc│rc│rc│gs│gf│ <- Horizontally connected pieces │gc│gc│gc│ │ │ │bc│bc│bc│ │ │ └──┴──┴──┴──┴──┘ ``` 4. For each group, we validate that one property is all the same, and that the other property is all different. This part should have been easier to golf but the best approach I came up with was `(#@~."1@|:e.~1,#)`. This takes the transpose of the input: ``` ggg csf ``` and takes the length of the uniq of each row, giving: `1 3`. We then check if both `1` and "input length" are members of that list. 5. Finally, we check that all elements are connected. Here we use our adjacency matrix trick a third time, except now adjacency is defined as a horizontal or vertical connection: ``` 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 0 1 0 1 1 0 0 0 1 1 ``` and we check that its transitive closure becomes the matrix consisting of all ones: ``` 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 ``` ]
[Question] [ The golfing language [Jelly](https://github.com/DennisMitchell/jellylanguage) has a very complex and clever string compression system which I'm not going to go into depth about here. You can find a very good explanation [here](https://codegolf.stackexchange.com/questions/221428/decompress-an-integer-jelly-style). Basically, Jelly's string literals are represented as `“...»`, where `...` is a string of characters from [Jelly's codepage](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) that is decoded into a base-250 integer before being decoded into a string which can contain both words and printable ASCII characters. Your challenge is to find a string that, when decompressed in Jelly, represents itself. For example, if `xxx` is your string, `“xxx»` must return `xxx` to be valid. You can test ideas [here](https://tio.run/##y0rNyan8//9Rwxw9Pb1Du///BwA), or just [download Jelly](https://github.com/DennisMitchell/jellylanguage) and use the [`sss` function](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/interpreter.py#L1055). ## Scoring The shortest submission in bytes (not counting `“` and `»`) wins. I'll happily accept a proof of impossibility, although it seems unlikely. I've tested that there are no 1-or-2-byters, but there might still be a trivial one that is a single word. ## Tips, notes and ideas * Compressing ASCII characters is actually less effective than just using an ordinary string, so with enough, you'll have space to fit an extra word. * You'll have to use printable ASCII (+ newlines) because nothing decompresses into characters that aren't those. * There *might* be trivial solutions of 1-2 short words. The empty string is not a valid solution. The string must be one single string - that is, you can't just escape the string and output it some other way. [Answer] ## closest so far: `'xC~x9u1'` from `“xC~x9u+»` and `'zC~x9u1'` from `“xC~x9u1»`: 6/7, 85.7% floor: above 33\*250^9 ceiling: below 129×250^34 update from last time: no matches in 8 or 9 digits; my computer is too slow to find any more near misses. 9 digits alone took around 634 CPU hours (~26 days, split onto 4 cores), checking the same way for 10 digits would take over 6 CPU years on my computer. I recently thought of a new strategy for skipping a large percent of numbers but it means I also skip near misses as well; so any further digits I do will have yet another new definition for near miss. I also haven't figured out if it's guaranteed that it'll hit every match or if it has a chance to skip some, so I'm gonna do some more math before I figure out how to explain it here. if you know how to improve code performance, I'm still putting new iterations of my code as comments at the bottom of the [gist linked in the comments](https://gist.github.com/panstx/7d008d6d80dbd7fa2de301032659df37), and I would love any suggestions you have. it's still in rust right now; but I have no idea what I'm doing when it comes to optimizations. there were quite a few near misses in the 7 digit range so I am rather disappointed that there were none in 8 or 9; if you spot a bug in my algorithm that'd be cool as well. no other changes since last time: no solution yet, but some preliminary results which may be helpful to others. in the first step of decompression, you divmod by 3 to either select making a character or using one of the dictionaries. if you ignore the dictionary, this means it basically reduces to a base conversion problem where one side is base [1/288](https://en.wikipedia.org/wiki/Non-integer_base_of_numeration "just a cooler way of saying the digits are read backwards, but otherwise the same as normal base 288 (obv. excluding the radix point)"): (using the `�` for when it would touch a dictionary and ¶ for a newline) ``` ��!��"��#��$��%��&��'��(��)��*��+��,��-��.��/��0��1��2��3��4��5��6��7��8��9��:��;��<��=��>��?��@��A��B��C��D��E��F��G��H��I��J��K��L��M��N��O��P��Q��R��S��T��U��V��W��X��Y��Z��[��\��]��^��_��`��a��b��c��d��e��f��g��h��i��j��k��l��m��n��o��p��q��r��s��t��u��v��w��x��y��z��{��|��}��~��¶�� ``` and the other side is [bijective](https://en.wikipedia.org/wiki/Bijective_numeration "basically means it starts at 1 instead of 0") base 250: ``` ¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż ``` since the symbols have different values from each other I think it's just a matter of coincidence to get the same number to be represented with the same symbols. what this means is that until one of them out-bases the other, there may be a number that matches somewhere. (after 250^40 [roughly 8.27e95 or 2^318.7], base250 will always take more digits and you'd have to use the dictionaries to pad the output; but past ~129x250^34 [roughly 4.37e83 or 2^277.8] every base250 number the same length as the corresponding base288 number will start with a digit greater than `¶` so it will never be ascii-only anymore). what I'm calling a 'near miss' in this first section is when an n-1 long string of digits are the same in both bases. this was found with slow python code; but the 'near miss' qualification was different so I'll leave the results in the answer. near misses at one digit: [`“/»` = `'0'`(2 off) and `“2»` = `'1'`(1 off)] near misses at two digits: [`“-Ñ»` = `'¶-'`(111 off) jumps to `“/_»` = `' .'`(303 off)] ``` '"*' “S*» 8,793 '),' “[,» 10,545 '0.' “c.» 12,297 '70' “k0» 14,049 '>2' “s2» 15,801 'E4' “{4» 17,553 'c=' “"=» 25,062 'j?' “*?» 26,814 'qA' “2A» 28,566 'xC' “:C» 30,318 '¶E' “BE» 32,070 also spotted “y©» = 'yC' which I thought was funny since the c is just circled ``` near misses at three digits: [`“+B>»` = `'¶B+'`(65 off) jumps to `“+D⁽»` = `' C+'`(349 off)] ``` '/D,' “eD,» 3,017,295 ';J/' “*J/» 3,768,798 ';Jb' “;J/» 3,768,849 'G2 ' “EG2» 4,512,783 'G2#' “FG2» 4,512,786 'G2&' “GG2» 4,512,789 'G2)' “HG2» 4,512,792 'G2,' “IG2» 4,512,795 'G2/' “JG2» 4,512,798 'G22' “KG2» 4,512,801 'G25' “LG2» 4,512,804 'G28' “MG2» 4,512,807 'G2;' “NG2» 4,512,810 'G2>' “OG2» 4,512,813 'G2A' “PG2» 4,512,816 'G2D' “QG2» 4,512,819 'G2G' “RG2» 4,512,822 'G2J' “SG2» 4,512,825 'G2M' “TG2» 4,512,828 'G2P' “UG2» 4,512,831 'G2S' “VG2» 4,512,834 [ it's so close to ] 'G2V' “WG2» 4,512,837 [ being an anagram ] 'G2Y' “XG2» 4,512,840 [ ...just needs to ] 'G2\' “YG2» 4,512,843 [ shift a tiny bit ] 'G2_' “ZG2» 4,512,846 'G2b' “[G2» 4,512,849 'G2e' “\G2» 4,512,852 'G2h' “]G2» 4,512,855 'G2k' “^G2» 4,512,858 'G2n' “_G2» 4,512,861 'G2q' “`G2» 4,512,864 'G2t' “aG2» 4,512,867 'G2w' “bG2» 4,512,870 'G2z' “cG2» 4,512,873 'G2}' “dG2» 4,512,876 'WW6' “mW6» 5,522,055 '[Y<' “[Y7» 5,772,561 'c]9' “2]9» 6,273,558 '¶j@' “uj@» 8,026,815 '¶j^' “¶j@» 8,026,845 ``` near misses at four digits: [`“)f⁸ȧ»` = `'¶¶g)'` jumps to `“)i4Ḣ»` = `' h)'`] ``` '-I;*' “-I;V» 723,390,087 '`G]5' “`G]K» 1,520,148,576 ``` near misses at five digits: [didn't calculate crossing point] ``` '^)L75' “n^)L7» 435,080,769,306 'f>-A8' “~f>-A» 497,707,074,066 ``` this section is now from much faster rust code; but as is the nature of exponentials it only gets a bit farther. every ascii-only, non-dictionary, number 8 digits or under has now been checked. after some more optimizations, the 8-digit check only took around 4 hours. there's a couple more optimizations I'm going to implement, but then I'm going to start it on 9 digits, which is projected to finish in only 16 days. if you want to steal the code and run it on your computer as well you can see the gist linked in the comments from @pan. as for how it works: most numbers are either not ascii-jelly or not dictionary-free, meaning once you've built one of the strings and you find out there's a non-ascii somewhere in the other one all the work you spent making those strings is wasted. we start with the jelly side; writing a for loop that runs through the combinatorial product of n ascii digits. we then put it through an if that checks it's a non-dictionary decompressed string. since we now know that all numbers used are valid, we construct both vectors, and it prints it if there's n-1 digits with the same chars in the same indices. (the more optimized version that finished 8 digits in 4 hours is basically the same except it also realizes that most invalid numbers tend to follow each other, so it jumps to the next valid number instead of trying every single invalid number) ``` '"*' “S*» 8,793 '),' “[,» 10,545 '0.' “c.» 12,297 '70' “k0» 14,049 '>2' “s2» 15,801 'E4' “{4» 17,553 'c=' “"=» 25,062 'j?' “*?» 26,814 'qA' “2A» 28,566 'xC' “:C» 30,318 '¶E' “BE» 32,070 2 digits '/D,' “eD,» 3,017,295 '/_,' “/L,» 3,024,045 ';J/' “*J/» 3,768,798 ';Jb' “;J/» 3,768,849 'WB6' “WQ6» 5,516,805 'WW6' “mW6» 5,522,055 '[Y<' “[Y7» 5,772,561 'c]9' “2]9» 6,273,558 '¶%@' “¶V@» 8,009,565 '¶j@' “uj@» 8,026,815 '¶j^' “¶j@» 8,026,845 3 digits '-I;V' “-I;*» 723,390,087 '7iw,' “7Rw,» 881,655,045 '`G]K' “`G]5» 1,520,148,576 4 digits ')L]<(' “)L]"(» 165,271,515,291 5 digits 6 digits '"^zHf-%' “"*zHf-%» 8,638,176,928,324,038 ')`K0/-&' “)`Kh/-&» 10,348,931,331,136,539 'jURA9~/' “jtRA9~/» 26,237,629,941,156,798 'xC~x9u1' “xC~x9u+» 29,607,919,863,029,544 'zC~x9u1' “xC~x9u1» 29,607,919,863,029,550 7 digits 8 digits 9 digits ``` [Answer] ## No solution without the dictionary using at most 9 characters Using meet-in-the-middle, we can check that there are no solutions without the dictionary using under 9 characters with the following code: ``` import itertools import tqdm code_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶''' code_page += '''°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”''' pos = code_page[32:96+32] rev = {a: 3*(code_page.index(a) - 32) for a in pos} ver = {a: code_page.find(a) + 1 for a in pos} n = 9 poss = [] for i in range(n): spos = [] for c in pos: spos.append(ver[c] * 250**(n-1-i) - rev[c] * 228**i) poss.append(spos) print(poss) v1 = {sum(x) for x in tqdm.tqdm(itertools.product(*poss[:n//2]), total=96**(n//2))} for x in tqdm.tqdm(itertools.product(*poss[n//2:]), total=96**((n+1)//2)): if -sum(x) in v1: print(x, sum(x)) exit(0) ``` Projecting from the runtime for 9 characters, running it for 10 characters would either take a lot of memory (128GB might be enough) and a couple of hours, or around 1GB and a few days. ]
[Question] [ We've had [Meta Regex Golf](https://codegolf.stackexchange.com/questions/17718/meta-regex-golf) and [Display OEIS Sequences](https://codegolf.stackexchange.com/questions/107209/display-oeis-sequences). Now, it is time for Meta OEIS Golf. ## Challenge Given a sequence of integers, your program/function should output a program/function in the same language that then outputs the same sequence. A simple example in Python would be ``` def f(sequence): # generate a dictionary/table lookup dc = {index: element for (index, element) in enumerate(sequence)} s = "lambda n: " + repr(dc) + "[n]" # at this point, eval(s) gives a lambda function, so # eval(s)(n) = sequence[n] = n-th element of sequence # as required return s ``` The function `f` takes as input a sequence of integers and outputs the source code to a `lambda` function. When the `lambda` function is called on an index `n`, it outputs the `n`-th element of that sequence. [Try it Online](https://tio.run/##tY9NbsIwEIX3OcVTuklUVyUhBGqJXgSxMMkkWA12sB1UhDh7Ok35OUFX43me@d6b/hz21uTjWFODJvF0HMhUlMoIeEFLhpwKBIVaV0Fbo9z5PahdR@is/Rp6HqsrrHHRpqZvCeroQCagsQ7JpIm7lkIbkBkOE/JpdWWGZ0TcqcOuVjASMV7hqHdJXaX8jDdmG0@BVEDYa4/eahOYfFJd4lO0@kSeQ94IzWCmsALeTmu3ucSk7HM3Zih35i3sH6lt8/jFn5/nHMdBO6q5dxQGZ@CjqHf698hkU4hSZDORFSIvxHwmFiux5DbLRZaX25QR6088D7vMJAqBTKIUyCV4FXMurBUSjMBCgjEoJRiFpQTjsOIRRuKDa15eOXkUtRz@P8B/p7XJPB3HHw) ## Output The program that is output should be able to be submitted as an entry on this site for a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. Hence, it could be a program or function and can use one of the following input/output methods (from the [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") tag): * Indexing: Allowed are both 0- and 1-based indexing, and the following rules can be applied with both these types of indexing. * Output: + Given some index n it can return the n-th entry of the list. + Given some index n it can return all entries up to the nth one in the sequence. + Without taking any index, it can return a (potentially infinite) lazy list or generator that represents the whole sequence. Behavior past the final given term in the sequence is undefined. For example, your program may be given A000004 as ``` 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ``` This consists of 101 `0`s. The generated program must then output `0` for each `n` from `1` to `101` (assuming 1-indexing), but it can output anything (even a string or non-integer) for `n=102` and onward. Consequently, the generated program *can* output an infinite generator, as long as the first 101 terms are right. ## Scoring Your score will be the sum of your program's length and the length of all 100 programs it generates from the [A000001 to A000100 sequences](https://pastebin.com/JJxFRrcK) (the program does not necessarily have to work for other sequences). This file has sequence A000001 on line 6, A000002 on line 7, in order up to A000100 on line 105, so each sequence is one line. The sequences have varying number of terms; for example, [A000066](http://oeis.org/A000066) (line 71) only has 10 terms. The ungolfed Python example above would score [46713 + 261 = 46974 points](https://tio.run/##3ZxLj2PXdYXn/BVEe9KNkPZ5PwRo5HjgwEkGjkdJELTVJakBqbpdXTLsBPntyvrWuZdklbpleRihyCJ5ee@557Efa6@9D9//9fHrd/fp@@/f3H15/PLlh7s/fXd3/8Xdq88Ox@ObL46fH//n7f2bu798drz75u7bu/vH45fvHo4vfey0H3t1fHt/vLv/7tu7h9ePd9c2/ldtfFATL755/e0f37w@3n92fHH8h@PD3fuHl2@@eKW3L/79/j9f6KxfHF8/Hh@/fvvh@P7d2/tHtfzn19@8/PDq@NXbP999OL4@bi18@d39F49v392fjh/e@bLtvJf3r3Sf/cZqVJ/uz49fX3r97svLt8d1vw/qx5@@e/tw90afH@4ev3u4P374/hfHL98@fHg8pno9X7f4Tp24@8vjw@svHu/eHL98ePftZ4dfHP/1N7/9/fH3@2n/@Prx9fHl14@P7z/71a/e3b398Mt3D1/96sPjw9v37@/e/PKr/36lS373Wo3/87s3b798e/fms@M/fXd/d4zjGNJnuR7/8G@/PqaQgs77w4c7@uwp@eLd/SNj0Nuv3v357uFeXfjjX/Xd3d6H39y/OeuKh@Pv3n5xd//h7rPj82787re//s2//P43h798/uLFi3CK/kvbs@r/el2fY9k@7F/E9aae@MJfxttTfRJvmr/eGltXrIbcQMx7c9kX6czW9wb31@Cv8mlvTs2si3nZ7ul/Yd3rEPdGt@Fc/8fL/3Tz/offfuyq59f82Dmfau3vueoHPTzEyyLt5zMtac3b9p9p2l@Tpiv7f9mOF79fR8pp@Ph6X7dv2@X/8JnTn8d2/tD5w5@6j2jK2/Z11X8um/7kLwrrMi7NrQt91iGcfjZ/m7jlbQHKZerTNrHrfdsWZmxL0fx@P868pW2S9@NrqTSTeVuVtE3gaiiuJW9eir2lcfvF5UDw8vqbcrlJTJs4lLVQ65Zzu/047JKWL7JT9de2v@6/sf1N/6GAt49480hPH/npo9w86g8e7WOP/vQxbh/qe/h5/d2sRvEqMPfbvK4Z0sLpe0mbBCyestYrnIrOntjLKq2TzoZTl7JqcbViujxotpnxpLXKeuqKiLVteurcOPScajHoqXOSzklF7/V96nqdEk19l/VdLrpnlbnp/ZSnJEurWuhEleTppmV2eYhxqqUdrkZsH8ywuKyhDI9DrehriXrTJe67zpqrywnXomfT2bpV8rilHVO31xCyulWKbhUZt5pvQ1eH01ArU4OPEYljEGoFWeLeQ1OYgq7SIKUpVW2kieolXZWb5q8EDaFUNVCZsNrV05b7VU92u9qW@bNONWtHRGGi31kZk1VsjdjHki0rM@/D@u@rs6/ifWM1UdjECTqiJor1YB3RZOlgdXvFJ@hatVrXzVknjui04ju39b7cdL5YjbmfVkWjyGuiWeOmgdDX2LgZqzwlNj1qbWNutFjLoOmuFZ8JeYm9zaATc6@T9Zs1o/ilDTWcSqhJ3SktN1ZrTDUSELqc9UaSlOsYSY21GsMIjUs5M3ictege6mLpPVfdQUYrjd5Tq5bZ0XrTskkcU9G3c4SL4/x/9PdsZZAar6JmXxOKamatbJXMxzARG0l5Hvq2czwybilq6mpgTonErAXR0qxqNrPUEbnoupa5nWF0ZnbUis52XYCJkFZlbtC1QAN9ZMEGy9KjrmRFc5DF0GJJBKQpY6L6ak3NxHZYoDKcrkOpVnRQHoLbNS6vqECG7MpAqWvTuVMNVt2EsQ19lsLplFjUyRGlq5goSRhT0HVxS3Nm5LW2ILuVaqyxye6FMtHrqHMlPgh@Lbl2mmohlcQtC0NljFGjlmBJbELKI8q@ScA1TyHLu5Sm8zTofIgXs7X839wd3HJkt@5p2ijnm0f1o/sxeWCpo01df/KQNb0@sh/95jFt1vPNYz5/aBp5lP3Rt4cm9frIN7YYwxVtfJCyZCnTfFvKxkXKyi5ladxIGXZokzI07yplNT@RsoqZvkpZZr5vpax2jNSNlLE25bmU1YjtuEjZ8vVrCIaezZZSJhW3hqBhOrGKCHlvtpI4khriuLWAw@FIxfoNLSXRigZZM9pHG7OwTgnBKFi@jmg26Zg8Qu1Y9hAmi64BCDT1ieh0eUPsUkHy1PxIKdJqTWnYoQ11QtJiGU/SCA1JSqGxSgY1YRanoGlVs1oMSXjRzEnkg6YI1ycrHaeaxG2V0OLIdLb0EoqMdumXAVaj9o6wTqPwBe1TWt5qGINyijFEtzPeZjQZY6bt7Ljh2OXkwoZdjSSD3@YNp84N/E4a4kBnLWlaQGRFMWEtWLkVQTBg3UOLtsU5@83SYY99NqfK1eNkyNKYZnkutV75LoQlsb1zw67vk92R5klfjdJYtGSvIuwyDWvwRMhqC3ZIccrrIEIyUo1ZjQ2zN2QN5GkQWl2vM5rWLrfWrkKbZCLlMPGWEufidmbSaVVXSH@qehLt5KckRbrRLivlGevWw2KgJnEEYDXEbiExCZ1MZjxJl4B/srwSjmG979ieOHvH@AjEaFGr/Knmf8h1Wqt70jLgOaVVwgKhZ2xtkoAH0EjNmL4AaNPUjX7Sa5YOYNN0Rsi6p4Be6fK@MgUypLoWFZfEyesGo9DepROlY8ib/Ifa63YIV3fgYCNg7rAlUibJs8xOBtHJpKXEaBs9DRWxKQO1lMke4MqBpxB8VcNAHVki4G2SP1hnaR0aehDGRCq0zlXqXJlW2ZlmPWaSpHV4BhmxolbQd2HWHGdGxcfMTc6kgqc08jaz5l/rdGYE57TQHTivotJSQZmlxP8IblTXIsZSy5OwaXg4QaTKVMndSFODRVBYqRfQjKGglHxK9WXqpEVDZgbLpwVV66M1CS2fJae2DKWp0wWfKNHFdkvCqmZKBjhLhDXxEs1o5yWZFq6Srcai6lWjqW1U2RV50aAeX@Sv73BDF2sWDMkjAPjUrWNAuI6Llp3CNhonyijKNcjDyuSpWcC1HKpO7COD@8MydxVhxBPLekuGA6IsDR09ZvxnLTQPGJaIAj41WeqwzU7LJVuJ01ArDcQpB6KhSVQlGrUH627Pmp3ZIkGQMGSbEgCppa7NOnVp2RkjdSayPePIz9iS84pBzsuZn7HJQScCP/TSCanO2HWdSVSigzjeoYvp/@lMXDVppXjKzjEBCZCVitLxpuMddDumk0jqnEDUOnrOzF7hjYBLls6fS8Gw6WYSP8kWnYz2iaeztFN@TEek0LIp6qUEmdiIQcRCSGFofxstts29xz38dqQ9DFSSgUpgoMRS2WY1ANImrgCcAtw0FYElOrGCxVBFK@VvwSnJOKX4I7bSkUuh4WrSrrphAkK970wd9ioYpzi0sSKdbERPmlTNBCqtdWzPBjM2suHpYDbYNZ6PhnCJqNWw62Y4mP19OOCOfTjl6XA0x2s4mlhg181wtLAaDrr/g@FIR4BdHxsOKARzdgJjajj9cIWUc8eSO4S89v/S7f60h30Hg8U9ufTB931yR8mpPH8E3dgdIK9SMdmIifiwwDjavMJsorjAcYSBfjHheWMMmHlwFtIzFnuAgDgkcFQIPrqsWlvYKo5NNgD@rEeyydDk0Iyj2srIwBvLhGTEsOOUqvCnnKGiymkfgCwKDEpTWq9xDPvsUQmXp0AauiP734li5BRsF6Qpg1C4NHx9QpcU51eTHzKL0fMsB1Ix1TLkE1czDlf6@Ub4PvKXPvKXP/JXPvJXP/LXPvLXP/K3c3Dj6XSX3YKHtYSaIk3YyfBFAF3qYZomIoDRvjsk4yPJkDC6RqkoDNSL0VRDCr7Ustw8@FmWVYug6Rp4TYBCJACddfTKRXIrMmvAqg6@Hzs@GutSIZ4GjSRcD2oTCpGvQJAmoJdY0ygvG46iENZaSTruB/skmJ2l3PJikuRsFgKKqnNDKWdn3TGnkX5IJKCgFGQElDJghUPGf8jxdeLNDjyXMklC4DWCBoucz0FSA2g9kVxdROQlnDHoip2ydUCQB9QS5F8T5jArREoQRfb/9FEuSoKeD2Fn6DFPRAXY7WgQEApYkY5ZJKMaGSZYFIQK8eBCFDSEZr5Fjm8ADYgJmiIaYTi5vwrfpX5rOjXnUmxNuqZGYyzLMw75wKLOdWAA1k8H9LU0ZqSBi5Iu9SkoIGCntQ0OexSdoFBhCFrMPAUaMEOSl5QUHTcDjSIxWUb6Z/K8QNWfzdNOZlmV80YfhycM/PmWTD8vH3rePCiYZfqZDFb0FFJafvMsh3SWQJ@lAyCjswT0LBEGHp0lwWdjl7A9dalc47m17TmAM3rq/tKFM1hImnOW9T8PQJU@y46cpz5L2c6gJ56KtS8D2sfyDA18Cgr8OA74CSDg70AAP8n97445mJpfvrkSE8ktXp20onZFRxleRpOxfPbESmsefn7JjjPiBTg/L2AOKkdAzxsYB4lb2BCyttC3obdhtyG34bahtmG2IbbhtaG1YbUhteG0obRh9ELQZ0GZBd3dEPg@EU@eFVi5BxZ8cJC0AAF1ekA9mu5TsagH7jDlYc9yFgg1wbh6ubpIgER3Z6XrCmh3ie47BrwAwLnjvrghvkX5IWeL0csWoGxZ2aFc3uDbXLANqGaIxiuMjL2jnvoM2U/evXPT6Vg8Tp7Z8QruVvHiibA8oTzYgQylqVf1SfG/njpOYKgJltfZYsnrcEghGf0ltKVvnczOFKghSF9UrwK8TnBqwAdpOVEBblA@i2QUvg@sHsB/pGAUCKJ/WvkGfzzs9UMEFKRsF2vWgFBfY2iZXgb1Rh5soO6ZJJMmHxo1dtijpGkVpNT9tF7ZQLhWx1SdQE44yNMkMFUPW3rTz/Vv@7@/XF6vb27e3b598v7ph2efnn/8wecfHvjIkY8d@uixeBXLXSazyWXH892SBchp6z15yICcDCyrzheuwYRKdgTQJZ9CenAm0TCO9RDki1BVcPyFROFoifXTxCPE@qIgfy1MFkboUKJeZ1mMv1TTAj0seLM3FN7sgRa8zZ4qQmzM74h@CgUiygJkjVXX92SnuKYExeQkHqsa440MQ2uNETShpoDyRRKH80KbZ5c9QBs75VqrJwXaw5y@zH/AUKNqQG7470KwpFatnmDQXnBPA6tTKjhNGG2YQ@hg9Qk/DGk11ZMagGFyFTNF8@JdcBTdTODeXECNsAXSbMmy5FeqTyyQSYS4V01Qz10TuiQGCtIADJhO0KwRolf4@dEh22GTdZQ@C0pOfFlTUGDm24k59Q5IrgghwKpBXyXuWbtTvwNWO4xD@NvTlZ06Jhc7WdAqMUiQlgVj1Do8VJikPBWtMF0skBMFEolgplB9RKRaIcwU1o3UJBVs1UCEgqXAUgIQlrCRIKwQlD2kAcsp21a4kfBwIFaSbdP3MLEzCG7rUlmHUqfTIeqyvq43RTnb6IpHB0VvajCOuQKv4JiCsAz6VNPvBBOxC4FXJblVRuvBGVTgvpB5WBnUQAYVBtgZVCd4QyGb4QyqbkAG1TZvZVCDM6g99OQMqiC9A26t6iRvvzKoJIC7ZE0N76Gj@2@qhPQJjgG7PGVfkdZGAgjI5L4XaESphSm@DgNhaVYkVMFcaRhHFSJu@E0svhaKEExRhHqlK7q03eGoYvaxigwK3J30TBFoS0ChMQtUV5TGEGxiU9RWoP5AUY0chY18gmGX2IHwZlcoqeezlZnOq1MWAIqiviFHB0wIVryktiqpreDUVndqCzZXgY9TW3WltqJTW6TRTfZvqa26UlthT22FLbVVV2qraY621FZ@ntrSNFxSW3VPbWmmpuCHrJATt9IuqOF6WNmu65BM/jhLELcsARPiRD6sreZY5tLFAiTpcwTpNI1/ZQmaswlSJ2cJpDNjsCrOEsiqOEtAip0sQbKFl/1mbZ0lCMOlHVozmEhJU1hKmDAHKA5ZAgXedWUJkJctSyAFmitLIIuS55Yl0BjiIT4fXjGoGVaGE7k1Oo6HocJFdmBkAxgylJngXbpmyiM2r4rmlSQIyTFh6jrAaII7FVnMILliWiApmMWjSB2iywxk3chTSvGHuizgXW1AWIvWjEUofmiT/FGXDdTEuqgkIqzQZHDfukp2XGOQMQ8CjPVwGVwn7MDeMBPED7hEJ09weAaUwxCsYdTVUwxQrQZwUuq8xLNC16RVGyMhsY@TYZHLjfKR0iotlpRwmuzoyXetyNVFCusiZfSl@qGx5oobhAUjLWA/laVPg54J/hRNd5mH4YQiVFjfygyDa1yCY5bqKGaxjc7vAE7ThgQJoEwEEz1NB1PdMRRZH0dewwFXcaY7OuxqRr6rqHQFRMNxkLowHRx1x0SZKCku3nM4wipAYzCy2SOQcjrQiAtdKJYqxqTBgLo5Opt02JUVeaM9LRgLO5e6YeZxwcnoRTLCrQvKoh4lHRb9nZ/cwiUMn2y/bu3XDZPDz9ftPqRkePYnhq0xp8lBQSQRlu3@bVcwcKRsipE8SWHZ1AkulpvBRU4ccMqheWELycAqq@vkqWzFELqgmEveY670gkSCbsg0SjMqaVbdU7aFbqUsmUIV9FnWrtmySlbCEEwHQwRBCYEXPIgsrpBZIXUEtAlN/leYzxGwTMZs6pxjdvWmOe2j9Reya@qr0Ed01ZWrpJzscHqdNOsJdwRB1l3Sxj@n8c1VBtt/rEiwq8VaDMmqHWp1hRi2A5oY@1koZWJhqjPB2Zx4L7YdUJXEIXBqWKG07KjUxjUpPoLR1JiTybJQrPbdK4XiucIgbGHZFn5dwivSvazQADdnnLyeUA8AQHTE9kQ61I0qlv2CZEC4oRM686gnmpfJjZ2Mb3SuvOnJCdLATc2l@vbRFDxf5IW5MTL4XXC75oJ3xmUlbyMBbQwYV60KvUQSQqha@zDsW8i@dTUnY8MCaLookPCp8jdwjhC9XbKoaQ14E0Er9Q07rvtIguRwBSAqpjbsyYRLqSCrsVM65nOueRHTNVuI3HbWpe8ES7f16NiNle@omxKCueeW2yhbwJy3XMbYgmZUGozUVpUkHtyB81Z@gIkDkO8GYUudrmC5bYaBAoQ9o@X8BrYsu0gkkBmDS5aZpWsUXskIruqlpClxhwW2KzW90jlFNw5mhqB2dZJUkQXBhFEtKkvcMfS9pCI7Zpgy/@D5QGpYMyvMIsUlLyJ/QcTQPSxnmAVA5DQbmU0hnkCCPDnxWgH8Q1YF34PVyzITionVQ8E1fK8QXXcc0eYqNosGAjIzUupCTV8mtpFrEr4Vggij7BUQZcthjH2hy1YZuWofV7GjgairGFe6MWxlIDVsFaMQcfZHKDV1Rth/W13LwcrTpnVk5aMM121NxvZ@LBuMydqXHHTVXAKyiQAk41gi4GrU/djah7AXuM4bfnKlKi/kZNprw9pWGJbDDSe5JyY32b6wkc@oyMVDXkjIxUBeEpCLfrxwjxfi8RnruCjHC9@4yMaNabysTd2WBJI0bSk/0rc4OVQkOeBkOXDjoznNsiAXuSWJ4eT/YEWH603WiyS@E86pFfxcU3TAjPBKXZEgJiUPvIJghfWp4gjXNyQAhWriSgVSJUX5RyfqCbfvoos/hmsXeNtcZ9Cq5J2wZWzL5iKcvBXgZkd0FWaKeZt5yQfsUJ1L5aOr07R8rFy1JyquU2NlNP/UVJFd8iSDaBFBbAZ3j4uqcgH2qmEATNnl41hcvVbIujfXsbmgl8pc36lObteDyxolHmD5Dg0gmXa0EG/K@xydJsOqajGI9m5OL60K77ncKCVFoN0OERgg6xLRKpG9DHJf/ZHdmPAkVEZT8OIMG3zFyOhQcJ12ItiGh0vm4Zp5OOf/kKKIJsHDuaKJrFmGh4SHM8BYPAaGmBirLx4uH27GY1tQmd5Na9vhdsTDMDuYpqM0GTDdF5ojG0Bh2UTUoQLUF1cOO2UprIDpV0wFvTkNtYNr7qawMC5hUiAGEanQgFYJW12dnvMMZkNgRSAiqt7Uuur95AGai1rxkBRyASIy8zcoUoJeAWMgyx2qQMicClyZjSa5rVRb9esI214RvqCsQ/dVCsDMhb3cPxgeUphijS1h1dDXcnVkvWwl/8UWDRIiuVqd59hRLVEudAWljyfqi5Pr6gbYagkPRW2uSWfmy6rJrxS6sc4wOmhGWNpBgqXt67Xvacibxcc@xn1bQ9t3NqRrnmbL0JS9CMKFq1s@5tYI9j37svIuba@DSLZ6zrJc7V1feyPCTSVEv6mAwMmCGPqaTKOFdEUMaVwGs@pqGGmlC3Mj3tlRQWEtUWEw/NTNTWCljfcK2BPXU1WtWeEsmTj1HbJ6Mse6vVfRKGEYgOdVdgfCVwDXcRWD0hs5XYk/RAm105SPL20SRkFhBCwB6gLdVE4rbgysrmumcnRokFc5falCwvHGnniAySVB1dUkEFCL96TqQF4Enox6AqwtRB6ECYIWYAuiqzJhHtZGgG4irywiLy0iry8iLywib5jIYwodh4@NyBsbkdc3Iq9tRF7Ziby4E3ltJ/KuzmwNAoYT30iAh2hTLjAxed0ldaQFXO@cMLrCOhJDTQdlZx3KJAJxMPtCPAhcKWDLRJo9m0ggW6ToplAgOoV1KVrH1MiOQCJEeFsEdGIwGJ8WuXZIIUfeeC0ZmKRQztQjVSuxLgeqrqo72HMdJibZTf5lfIbI1DRHJ30YDSTVTMat2JdM@hLMEswTTIiIXHE/rQVbVPWQ8BaLxJ3kkrValWmiRrJ62mSc4WTVWQRLCL8FVxrOgPHEMcoXJoA5ezIoT9CVAdJG8e0kgmLjh0S6djPBCiX4RCTBuGT4Dk9HVUFDrtTuNjzVsgWnrx4ILwUwDqJeQNFCFQWz6FhG2NUlugUiCcnEUGoZg6nnAVucYfVQHTKBZoYCjBhgTQOradHPjV1IAs1aqJxWjVF32FzlWSolnG2aOllML6VIvc7DjQ6ZISgGp5iHxFYjGSZ3BceaoaxbsucLrv2lUIOKlkQ96DBNYP48aTVxnDpmNym3wtonq07p2b6NkhAoXc05/Cu7trQ6Dh8ljcH8VqYGZ2IIKNsJxXbVpa9QCaGw98N7pQJOnXJTIl3JtfS6PbUQds9lcT8In4xddU4Nize92YHS3q1gDOa4VW8VM81FvMh5BWGXWyQ1IPgILU3FDkiHhMMkIK6Kj8a8iMjYBX/NLLAJ6dR03cws/DjpPq@tZzZ5ZiGAejD4p0yTme1rZlFcz2xYM2uMqZmtwTOblzRjrcOaWUg1z@zAkzCzc@2hY2bBVmtmXVi7ZtY5Mc8sFTZrZhu5zG3T7M0IXRVYVwCjO@hcAl1L/LbdobIDQ@LbjX1cW2p@pBUXZ@4lx7MuitKTXuHpofozoFXTPefS9zoXQdUEd@DOqLyFOynkNeoi/wlZga2R5NAwMKXSnZ0QMg2lsLGDfNR0DRIUKcC79D1ackF/tts2y4Ir9645IE6wpGmOB6EWvGgxLzrMi7bFi6bFi5bFi46NF20bL5o2XrRsvOjYedG286Lplp1fvOi48KLtwoumKy9arrzoIAiSvekYpCEbOl3vfRFL7wlyeEkhOjwNAKebxIHjbqTFFKuYAOyB/ZuSbKfqB/y05jATV@l@0fnoYndDhlGYX@6xQpeS9WK7TIRCIbIph6vcOOh0F4wXpHzLGeH1MHP4GEXz4AUn0ZIiLHJwZCXRnBSJeYrgcXM5nuXUTlgxkGZvetuK98bIvSWnVDQ4cjwsoekedjJUag3JBHnH6SpNQ97lEzRSZ@oo/xdAgJ/gBgSE6oMMhOm/uPMA3TUFeyDv7E0yHIWPMS1IwISsBBfju@i0O3@TXGdQTZ3oX68mJ9MKzzJe07CouZiO@QTSEPoP3pnpczm/NyGYCjTX6MrJnsx6OgXojVTQFXgWK12q152wXpTsPZeU1TMSlrQNb@oBZypq7q559PYliTK7TyRZcjIOY6v3qWGfsJJMffBeINQZixpYMhncCXgAsQAlJHzsjyUaDiThhlFntWEDaMj@NhIkgxoLqW6kLLAQtm3KGh15NO@1YcOGBU6iYdvivVeyZiuZRndzN38l5adYVAtNEYXzQVjMk6GMEQ71HJ34Q0gEZeCqJmEJJMHMUUuvMEpWis6EEmEXBVeK6L1LlTyiDmD4hUjk8vAxhLdsGZXkqol4VctV7e5KFPwFwY3EA0VeO4NYYOSDDROsiebRFZVh2@OmIQejvMTGDgz6CTpM4MgctSxPcHQPuc4mDqMe2VUqmJM3aWjhB2zddPQktCr4jmYt0lk@TmMXRGKLHWKhuaTkE3MkFKmgkX1Ipp8DPdHyatFlsdNhLwFcacNrldXz9x@rIvvUOZ9qJ/yEc37s2v2v/Fg72wYwL5pzYYtcSVZZOb5MvnlSYzu92SuRRiBSSzhmSEGZdhKXkJ3s/nIhetP35jaIo3AHuNKGq@iabm81EZ6TfR5gSQF5CkGotoCymYrJA/QoVeskP4RN5DwTW5hZtkq/5BIUXV1FziUQphWD9ycJzgDOXSTNYppFDLIdUmnzzFVeJ3bbm8rdAsi9T5NOoVKMIDMg@aZ4O7O3XX5vNtAsSRicpDAxyAtIlyQdZCe9@6ng2XUTqS/yJMgpc8wWMm/L7AByjZCMKLGI/BOeQSrtUmQ2wctkVpKb4DWBdXY2SWrl53HOh3iKz5YyfVJU9r2cf8/54W@cXz7R/vPry08V6esitpMtH5X2xT8ZkOwRXKPhF3BYHew4POHfsnf/UbiAtrJxkIoOEk@odtZqMdOcI5EReqRaaTrvVyml0OrwiwQ0Qal9IG5XjEbFx@jsNpRExozem@jUDSvWILFf25seM2erZyTowM/e5jgCHr47w9epvWJP42Hf0RC23Zn7XKYb9UyXWSs3z6czvPh83o2bo@XZnJeb2S8fWdH9eHnWzniyvuWmP@nmuN97RLDxFxJ022G5EaBkXaEE7SXKqmqEYPa2X5BW3Nhc4uJmrAA3MeeFqwUr4MBSXyEpZFglEOBdMxMEZBtG7Z2so9uoBqOkphbZacdiJAJFIn1174xNGuVY0IJhiyHrxpmVm1/OYMeUubH2sd/@mE9Tz31LPe@k4J7dWtu/nXqmuMCEoEsotzQ3yCQvytub2EBcTCoJXbij6B0a2T8bAJ2QLwSgqxnYTRuIvan2CZffA7oMaVVRJXNn1ewSTJt5U2BrcIYUmosMaNfr9L5dhuH8Nz8IQIaZHxPg1gRqeOqKkW/g2gGZIXPofGJykGhk3SlQxAFYhfk9EzY7sPN7ulS0mKLO3koTqTGgrJZweVrAnopt@RuGrvxd54e/cX75RPvPr//phi54Pea2nQjhcl1GdWap98Urb4lTgkPwnH86hihjLl2qafu5GACsSU3X@pVQ10/ENOo8KGOhCIQiCeg2Ure6QyAvxOZtCFvCculbYJdwhT4yAHMlIsQsjGyvaycZFWAItWn@vhJS0WWVFQKRlEk0lLaGCTBsxsFlOaZLIIudE/YvSiBCdBGSH7dsWsn7XvGBzZsHnJWjEFZiI02jP8G1a3mZCDLNrrWyTEJgB2/xpfKZYnEDFygadcwblql6oDqMxLuArovBI9l@tcFMw3v6d3aoNpBQBioGqPIqdRsOg5tmaLsLY9iU6a2szg6duoN2U2hwElg/NcKvTlDQR2DY@xbXOwFeXPxEPwppvi3cjNTuSS28XuyuUoQRHFA5GQcjSA0LId0izwpgzb@1QfEVOyt63xL8ddt6vDZqkKTK228TzfU7RNid0Z1UQLshFEHiEEQ4XfCYeefmbWjeTN6syK4KZi95ckqC3wmqpkNgl/2rPpRPUPzh3WnURuS9erxavv27P3FSULyZh@hyxujfXoAowNfDYSlgurI1HtReo@PfbqkOSNu0hK4ftSBjF5k4Rzou@O@BH/JI3oomz@zxU04MrQ8PJjRIuCukVx0JAzlJDVOBSUY3jVXOqziCX@NI/MyEq4MlHtTZSc46pTTE9Iqq1@zAkiYzv1qmRpKfvJlcD8UdL168OHxzd//V49fHz4/hwM8@fvP2/o6fevzLLz@8/@bt48sX/3H/wj8UefmpxM@P375@/9K/4MjJ@3mnF69e6bR33z3@1/uHd189vP5WZ9782KS@2271D5/z7uXNma8O7x/U4Mt1wqvv/w8 "Python 2 – Try It Online"). If the program outputs an auxiliary file (I'm not sure how this could help, but it might come into play), then follow the part of [this ruling](https://codegolf.meta.stackexchange.com/a/4934/68261) before the horizontal line. Lowest score wins, as usual. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~15604 15329 15204~~ 944 + 14168 = 15112 *Saved 2 bytes thanks to @Neil* The main program expects an array of BigInt's. Each generated program expects a 0-indexed integer and returns the **n**th term as a Number, a BigInt or a string. ``` a=>eval(require('zlib').inflateRawSync(Buffer.from('lZRNb9pAEIZ/CxHYO94PbFfJwWKxVNpKPbSXHh1LXn8IUicTBDRKheG3d3ZtCKW5VELGO/vO+JnZ185Qz0NBF7bUtZ7XnsdwUs8i4EtWywiAcY4wCFo9x3RJkVag1H1GO5GypmANST2LgbUASQsshiBQt50rzUc4FGAoWo1AWVLSk1aaGVHSskxXrBRmUkJibBGSWQD7RwseOYDIXXhfC7nvQxbmQ2wSuxvPbSLn8sjQAnB163Lj4MzwX01cc4/aDmdhGia2BAWlGxTKlkiTiFih6xynH/lq06wbszvzUx1Dz5aSUjND7JwdjyaLc88zWZSDtKsozoVSyuQ0CZIAszsnin5YfQUaF7fjAhaKYT48DoJTl9h3KSXSQcQoCRJ4hEmMwD4+LL8icYFLo/Odsm9mt1KfZQxd+P6YVq6i541WDD10xhiGFF3hHd/jk9GFSFQXXVRWx6tBeerlrBT1X9q6V/P6rD9lXPRO6MfW2YvWI+w6DIjaMSNM7W0ctDCljJZWzmltvzuf98XIO9HJvRjQCX4g+RWXaK7IGhEHDa9lReVLaS4JRQy52j4/NeyLnhvVvDSb34y9CGupF63ZQn+xbADpgnydFPSk8b7UoVjoIhvvjXoya0bB77+eymZjj9L3tcYUEz989Tmq3fOP3eYBCUVHd7SLPqifzw9YiOKQF6JMF0nW+6+v97ZnXfpoqoZNWTob3dedBKYE7O/EQbFU33+C6VJsqfOt3r5pBQXpBYQsDvO0IMOGr+P94KstvOEQzMG+qkViRTfj/fZwU9Ckje576hsiIy5ZH6j0XLI1/XRF0bUOgbo57ay55pUL+pcJg/wftdSD2M5+s2ODQY16bHC5W8lyuLHfkUOGefEH','base64'))+'') ``` [Try it online!](https://tio.run/##7V1rVxRJtv0@v4JvyqKrjffj3uXcpSK@sBERQWfNB1BQEEGBRvHPzz17n4isrAIde/p@u71WVZlkZUVGRpzH3uecCA93LnbO3pwefDqfHJ@83fvX/u1/7dz@@97FztHN073Pvx@c7t288e3oYPfG4q8Hx/tHO@d7z3e@bFwev7l59/f9/b3TX/dPTz7evHH0@vlvu/XTnfuPXt@69/Xhq7Uanu2u7D/@svXk68vfPj15trux/fC9Xd0@Lo82D968uLv8/Mn7vQf@rX99fu/JVnx5f/XB2q2LtaXHx69tievfzG93V/Lu5vnrvH189vbL5lk5CPfPty6/HNx58yp8ubdyUr/6548/vNx5Zx/aB2vxweWnj3d@23jhVt/tbt7ZWD87e39wd/08mtNvm2/CyoM7J1sn9s7Wy9WND3Zn58HLhxtnH75un959/nHzw@OD3bsPNrbWl/PzL2d7a6@WH21vv9@/l48v1r/uflx3XzZ@/3ohj7B6XM4O1@8c37XJrx6Gp9@@bBv75k24tbP88e37Bwc77u6draMHX188Ofpw8OJg5eB9@np5/PDW0WeTvuyefbv4tvnVLn@LOxubh78t58df3h5e7qy@KeXb1uuN5fMnZyffTl5uXP6@bu69fnTn7NvZ8cFxfLW/vrmzkvcP77zfefLqRSjLJ49fHNX3/snG9sb6m/WTe88fh/f3Pz79shyWVlfLwZtXK6snt9benn2sH8/tk/3X61/fLj1Lr15@Tgcx2K3lZWu@vj94sLLi3z98e@vwQ32wsrGyvr398vnW13R@d2/v9Oj07gu7XT@nl7eepdPlerT97Plaerq/5V5dbD1a@pKWHx3uPN347WneMm/Ol@8dHT5@vfXt49H5xbff92vZfrRWHz6@eH64fm87vFt6vrW98yQ/evD@/sPlnXr0fO/l6s5GePx8/TK6w3Drt73L1eP3Fy8vljd2fbis9x78/mkl@dfrx0tfd@8sf3p3fPl25dnGh7KbN09eHp48en9xcbh9crljdu/mvLR3@fH14WFd9edvXm3e/1ZLffHxs99fe@b3Xt29t/ny4du8sfrs88H@ty/11cHak/WV9PjpijneWkpLFzW/Pt7e/3Ty@eT1b1svTnb92723d5@8up/Xbt1f313Z9H7pXnr5@Ozz/tq5P42f7q5vf7r7av1s@WLNPHq69uB06VkNT87OL9bur397@mDp84eXB89f7B/e2n/9ZbPe@3C4F3N6f3bw6DK@fpgOzfbqI3tr@/mK2d1ce7d7EvPOZYyfNleXPr15/O7Wl/3ztxvL7mlcOnNry@uvbNp9eC9ulaPL31cf7n/YXHuwt3//4Y1fbuzunO2lcGNxcenGjcV//fc//mGOf7H95UafkQfD8XDehtGp8UV2@EMO9KJ2qb368/Yr/SP1i6c3HBoabtWat358S98bw49THt90fGz6Zb6fSsNtert6NO1n@8dM@/bPX/5hxzcfjdfcgZ09cFfO/ODiHzf4vdZ@/lc/c9M/3@D3H1lH0X7nJjpHbpjT0YHO3fjYcR59Pwija0I/M3wlr9KvGc7E0cVp9qD0n9d@vozaKWyn9JO5fwV5SaOrIw@0xdpPtouCSlmZvenQZv@dDJhc/9frj7zGqupHMhRmRceN5GA4k0ZyVkYilfqZ8TU6rW4kGeNrBhHEjPuRiLnRJA83s4O0py5R47uVqxfNfGG6OLerwmynrBtpRRikb@hoHXW9TLV0GMOxakW@0uiV@6uMXrW/aEXn33bu7a55@2veYe4dv/NOP3jna97lylsH4S99@hMqOJag0KVGxWSY9D5ZkEBcDGWE4sn3HvImzQX8vKrDjjCMsLlyPsPQQmAhbWjTQCIoFg4y5vGBBiwxQMIHfmcLPiruZPCBix0udgF/4jqXcVShuLjE4xIf0KcIp5PlIXyFTkEoAzsaoX/oUqgZsEc6FEOa8XhXB6M0degjUdoooH1cCguR0FB7avyk9id1BFH4SPgt@uN0DGFkKjqKp/d4jBDQH8sRxK1TQWvyRUG7FcNoLTWMzy/NUlvYuYIJcgYtyDDBxkQ06SoNm0MDPmFigsGjh4jWIucgZjxS8vmKURl75zQ4xmaXUjciVg2MbX81S@eareoj175yzTUb/Z3r/7ZGfWuIfycVLdpFp9fiPFoOzU7085gIfBfbrUK7Fu3hlrH30@i9cR6/Ca2Lqf8drhmD0G0le@Z5lYxXn11KYMKI8EFtYp8ogxWCni3EzvrEm8VQeN8MgayO0m1zqgbX@xwrxahGTwsbUsGNXDDRoc8h@URZKVWaM9QW7@UIYu9jKQ7NpmhNMYkt4HKjwxOD3A99Dzn7KDeDU3ElZ5eiqlxJOXlIlY8uyAW1mHk4@P/@9T35oNA38cLkYyJpxTwEL0LVramUeSi2L7go80uLkYZVcxkt1grxrTFQO2RKMZNeTBYlOEsrnNlqSua8lhhp3bL8jnZWjIvn/bKISaGRguAUyka20gClyxsxurFQKsVClEprKc1KczY1WKvPambNo9pGGh7yOlXEjFFQUQMkh6EuNH0x4ZcVd4pyfw5EwSmxP7jSBjxIsRYnxQdYSKaMTEY7ydXqqWwxGbgGF220Cb7GhEq7Z@UXIujU5Rh8zGw0GRcc@xAwLhwPK2MU8Jg@GueLhQsR/ZSxNR4QIyS5NsPIDgB1cAUDfKojTNQxzzx2qc1d@rl3bO/c3lXfdKW2OZR89Q23NvP27Z3n3rW5YT/3rte/MTF8h9E7T9@YrJm3v8ZZqnewzZRT/l2Tf8yryn8ZyX@Yyr8rM/JPm97ln5ZoJP/Rz8l/pBMdyb/n3M7If8y09WP5hzCEq/IfLS3sWP4HcDk8aOOHqbkleDPCGKoAnRVdDzUzJ3VHRALR2HKdcyktYhLVrRQIE4MrGJjoaVjYcA2UDUeJDfQomUqUkiOYiZmu15hK4ZMnBinIlZKdBQrRyAfoB25YnLO8R3SuKGAp0kVIL/XSQZ1lHESjMUSiKzLeKuNGpsZifr2otgkhU02NjC@xjbhFW6VtwpBgki2ejxByMEGcpAjq3DjEztGzqlXt5Hqg9s4N4KN0Uqc/aWA0N3Q2nSPXOZqbtmBHvLFjGTMiiY18mf63H9HAOmKhVe@kX@Sgc5i1sTzETMwgLOGqrpAZxXFAIo1iLKPOMSIzDsFM8RabLgpraDStQhP0IvIaY7rC5czOZVzmFGfI5OD7EhJFxylQEPhcFV8DYlDTklGoYWvFgUi6mPjEGbWJvqSI2RT8QJ2TdnBVEhHyKaWxzjlxPgKQCI5EIYO2V51cGh0ORb6la1axYBXhrUBSc@LSJiA3YxMatYDukAAkqkfjDFAO8UVyWuwEmUwotLhFDWCmvbY1Z9prQcwQrShgCrNbBDWpIcsOcwzUFA3RucmevsyJZhpi2@jhSwzphQx3kYblwIsC0yXIVcajC8JNQhYABgMoLkpaoEUT3RDcZZRe5Sz6HDJdZhI3Lu3mqUue88ctOmDUWdCkwjQERzvsyTngBZzjwCQ@iYkU2lBoc8RLFlKkQm8tFE3uSPQstplMzok7bpfKfCYqtCmVIieyE8ViRU6J2NykdgqDKpaEjlmMe5DGaNWEiHlbPY1YqT6JQ49E6zJEqXrgap3yiT7ixA1kg9Qj0m7Bvoi5dvzHkuNIny0di0yyg8knBBGsHTnC4v7FFhkVdwHdOQAKKy8RW1bFxokrgMYXsa7wDSIYuE1JSZQEJ0Qp1AiGJE8TgFlEUej4RIqjDKf4Ky8KU6AgCcMjgEJUSOC5uDc6HjmQx4ypRLGiAnOM9H5exvMIUaIhjJVST0sSB1WmwpMfZGIr79RdKC3JsFC@GIysKGKhdRRhhRrmXDzJr2mmP0LiiZ/E@0FjDDQHZqNk6wlxYsDNSN5EFUh7ZFTlidSyJh@8GhdXpLVEmiP@WB4fKiFSFrNRg5K9DGNNlvEDYSypihjBTEgLXi4fKfxEjfBE41sThWETtYCTTssnHYpN6L0MfkZ4iYOsQYoJvSF@RbKOrwiMCporCl4njFRUthzaeE@sI8ajMEaaAh5mOll0hjPCsMTEkfvhq4nn6AceAqx6mKhJCLTY6EaEu4qRj2MVmMhhxtkM6DUpaLLyaWqmOAQ@tA3k0gNVvRq7SVNAZkdxuhaLKw2iugZRjY4UoxK@@RWjqL6qbyVCNYpQGU/wOqaUmNBQKgSjXUeE6hpCDe1cUoTqWlSQkYeW4YnttgzP4O@sE0MDbRpCbVEA1X9l7ESpcH@1BZssp/h7w1Kmoc5rhmWA7uX6cWHoIeq4ELrPDQxd52hgCDtHAxOuGRjMcB8YzCqh@9zAQOYwMLR53xkY2ABC9x8MDBGpV7RC2oNByQ1bjElOHVGbEZ2ZGYPxc@drni2PaEhofR/3ufXxSt@giAB/VpGwumDVSdgbmNRKVaAkEif5HmpjJMXwW4own4OT7YeQI@ed4J0aUHoEkpKtpDg2OC8OYF6S0gDXbZlKNWkvpcKpwcXYs3mNVkUODuFoM8Ke@pUJGqJwIgCYVNlhccPUMCEkMBgpR1uKYrASGRirwgFoRMQFZ7J98cxqVsVYFEa4QgKEczQqURCURlrF/VidQXHlkc5R3GeF5y9TaPFdvfnhy/3w5X/4Cj98xR@@0g9f@YevMvO6fq7DyAWbLlqYER@pd3R9cBvOaqzZUq2s4jnjFGtD/F1gbKYWjWzTzUm7IWNKkiBAkkXxh@CJMkcFcIlQ0jJgVGPJkb8V2CA@hkg9g@uWAWuX1oIA58QouVBc8gKBrOL5KfAVTI5RoYFW@M6lqPfNrkGHiTDoFMApPUxhhA6V4DWiych8Zk9gsjIFkl7PRuqYuCkGc0QcaaMM/abxhAcCfTJDQxm0FKZDJJgRU5MCuyOIk8UJIJOVOie/ZZBDMGlhF4nRVKUFPBPsGgFbjs7I@yJ4znVgyL4LHBEl9U3ip3lr2ntSZHpbqyjRBLIVdFn1yEqbRSO6MVQBzcQEwqJN0givgJ4C@EiCnJJosvwywzoJtpJHkqmQOYM1k0mTQZQxCA0XFcE/QbqcARXpT@SMXCBKX1wh8hCLkKvgRaEPIiNGYwPC2mEVTBEIWn0VaEnjLBLoXJXZJiINFkHmQcz/@vzpzzna9dfnH/kcAMZgrSfTDKO5mjqezOd8Jx2NTQYoRthd24dTuI0PcIGOvSYAJhNo9QRGgbB/AgWdQI0J/idQ44lCcDN8oCUAqklKw0chNMcHegj7MCHKh2mZwKlPCvkDzsEyT5C5nMAsTcgR@GHNldEYDcN1kPTfwdGfhaJ/EIb@xxD0j8PPKeQzLVHcYV/UQAaQ1AwERHgQYQ2vIWYMdIeFlQ62jfFfKf4/URUwccq5QbgnnWqTZlM9JwO1Jq1W3aJGpU6jlUIre1birJxZ6bIyZSXJyo@VGisrVkKsXFhpsDLgxn0ngtQbHddmyd0dQ1IT55P2TW0AIb/YBCql5r6lt1X7G1TfDW9ZgdwmAieo0owCyjO0/iNwwqepkc8WYpnV5TwiTWPCVEckyU7JUc/JUHvykFtRTfBN2qdExw/MpnY@QwKjtIVHjEgr7sIHzjFFzZrLzG7VFha0lR@@BTCI7ZylbWGoEBaFhtUza4Uj9N1FfuBbxpwwawJgZgJXs4MR1VyRKDk1H3l4KB9bzNp5ZgdpoyIpCSwKBqVqQoOsn4grZhZRKBEiwTZkS6xgCDHRRkHuEhOPRZGosYSrziu603hnpkQJzPJ8IIPOCmIqNJeeRR0yyUyf2cygusNkCR9DH0Q@vHLOGDUakxkbEjSvYy30IPaR4Vs/2mf/Z/h3ejA6Gh/OHM/@MffX/J9X/r564poz15269tz1J@0V5Rgphm9JR4085ibMBOep/clKI0NpLHRo@K0gcTosSKnQYahIDbw/Q/Mix5xLoTeWkXzmlgNLfUpylAGZMCqTfBko9clUzqoQIqherKHlmsWoqF4VFfSaEy0Xg58QnVSzi1Qi0m2NPFbhOdQk4RiJ4iPXoJyDvwzGBYbIBbk7DZaLjUsp8eGSIH9DG2FR4FPnM62@F6syX9hqr2Js48iwrqaP4YUNXSLtAdkpU6WBwQ65ndoTUrAciCoKLWuIJCJCQorGPzMJbkVekJH9iq5GA6IBl12d1URqDoVDj4Fjz8CSGN8UewT1EYURu0VG7ZG0194moTXaZaFUjFcY0T0aa7lIhpqRwYgEb8nM0yKZ6I1WdQl9qoQbSTi1JkNZ9yL9JXEVhm2QjGB43@H@MWsVWEGG05SZEoefHGHfSstYdlUpIxES5pgvCjSwKTNcbyrLlHKmRGh2JGhSIkejqRh5CopuCgwpCQW0LMgPtMAFcmpUxFQMwREh1yjQicwOZeMKM01iuAPvK2zRMDwhZluuYZ6sGuGkaEHsWIhVs/HyNAE5yKsV39ORCG0kqsI8q8VctQdAjNJ0hkmY2iqllVQwQMAASGR5RygpGy15ImMWWmtayZNhyRNTdyx50uotE5hFZ8kTboiSJ7XkWvJktOQpm@y05El4sYbiRFgqiwO15ImFXVmEWm4xG@dpz9iiuszm03HSISF@SRdqEqsWiK718QLTOKKvmkvJDHWqPpngI@G6Kwq5A0NySDbR98nEMxQiPF36jB9mMVEaR3KhllbtGJAhgS1w8ntHTFxqYGLAigIjOkS7KI0aFkImwU8uq4tzyKyKtJMm1BzEoAb73VmurQSvKOinPHJqbGyViJZGcqjbiKzbMFq3kbVugzm4CplF3UZsdRtW6zZYYccccK/biK1uwwx1G6bXbcRWt5Ewqq1uw1@t2wjVT@s24lC3gaGtggvFsGr1lKg/UntxWqV/5cFboFpzyHbIIXMkteSPObcQ6CG09JBVfN4SnCYZrpZDTppyLtBDZNSgzKWEoIMqaAlDgxwyi@@QQ3bq8cSRUV6YQzZFS1RFBJgDEtk1zU44WDRqNHLIvqbYcsiQxp5DFs2uLYcsptHXnkO2xdp5@R8PQmigs6hiwlh4fS46Ypb5wogVr9CS5TwewTpYAo2N2qSzKxPDRDrqP0DjYiHqFjwaKf8eCD1oTNBlwwCezF@xWqooRpw1PWK0SoAcyUjQCHJOU1IQiJrKVFm1kMXcy2xoYayFjjDkj0yn/LRk0lhxZ8ZbRWYzI5CVMNN8cuxIc4kqNB9PuKD8oSh0TnRw8hi0qjEqDBcr5JtGRAZ9XasFFkFUhCC2ESjGCtKArsusl0RYLwYxO@1JhARPhT62sK58j77JiPhIIIEgPrLH6s@9aHlhbwWHBpmkQAxRen2NBvHzaE2OaWW7pnHs2Lh3T8G0YgIyEjcF9YwPtHwdYwO1xQtyixF4jR0w1lBafCG06jTb4gypsaG@yqzz@9I4fSCXV76fG8f3yv1tTx2VFksIypzIolrYmmxKs@phWrnLsvXQ6IhpHCy16ETVp9VKTT9kj1Q0O9EKcaBXZcynqMdOKU/spIYaHdiLnvb0VzugxY//7uZxuHkcuB1TuXHoBusFjPblWmufdA5dY6GWBR5ecZoaVpp9FhcEJYks3BIXVMmgChyQoJRKVOS8SSpugTUxUTyV1h2JeSwG0yIgTbxybelrEVd2UtyGqHdkmZJ0Qmwqe@28iD21Wc6IB0jqfUSUTRGKR9hnBP4J@qQ3Fr8kIDyg4oHw1CSBQoL0NZYkFrIm6atGzaRriSUKEDyB8kn6LqDRDlXvrQpdk@um4T3W6NDNM7afdc0CP7VKT5M1Rh0o7aZRsEPTWKBVimeiVvLTVuaqpYK8RWXRo3g0o4lIRUdBjSUzNqC6TA/QBLvmZcQAaJWsnqRDkdFxGvk3YWrjcptxr7EG0l8zxBCGKMGI/bOSilNdyLg8YRg@GCEkB6COq1WFNcgNDDabzgggVZAxvswJwQdNimc9CD6g2fhZDYzfKdyi@DPtpL2zmk7lt77xN1pbwiHyQRlKHisgD37m6QkaC/NUMu98HEidMVGkzBR13qhEydK82F7Mqow5ain1YnHoSMEga5ZFBWR6DPy0AGnpMtyg3FKkVYCPwL0I32Rmk8fjNSRBDdgQxG0B3Jk8egvKDmGiNAqk5lGwNDejmdVYtpR4HMwHWVwdMt9hCBz5IctdhugRTRTxcOpLcYi3NIQ0lBjSE5DuTU3eUJnUYkZpMH4sM5ytydDst5p6r0WphlUfTN6J6@JDoHQdLqMVdjsZX306IXWRa@nEXggBV7ZdhNJFrUMSegs6q9QIRocEuMglIodeCWsVFwsCaVijJdMlWFRMD3Pn4phBVrM@POu9BFEKikmsDhI8a1DH5rTCKYJjFrGTcPU0/F4sXvZRuitwnZBIUH0mg021FfFbQjcxm2KWAldqeLBsQQLChgT3mRJmqx7DKCldRoIUputo@vqYvhZG@Upb19IrcMy0YDSa6aIlRvIbEqCFcupp8@CSmsS1wijXT/faB@WFajfL8GfpTorWeipWxNZJ60YHUWOio3RR05VS0y9Gq7vHK7PqXOakF/KMsyZuVHufpnX33sxlSkYFO4MijjMk12VHemZknBXpGZFxQU7PhowzIeMsyHUZkJ79GGc@etZjmvGYk5I4FQyme9xQ2MICKkIParvTYAwFgiCtJE3JN5jOogVRmMp/CoWsaJ1r@1cUNTOYIS0SdiShshxhHLCIWggMyyVxQK4kpBTVoWZ8hOIWgbu21bmgnpzFpRlE3sweWpaWFq10xHHSSsQURU9BusuMnLRKYT9dVeZbMCManSWMfvVdYhnUjbUbOKtrAyAvFJTYwEDQlQKcfMwsC9BZuaCTRiJFbaHFZA9tCz/rYsdWB0kArriNTl1XDwQW1iVdSaBL1rjITDsQK7uRjS5ygYCSbmYG3KCNA9W18@szWjTHNSAemwhaxR6hwUldaFk79GG9NKlXZubAMH7vGOJhRE0cXu7dFiNaGdfkKkPW5GrpB0OIxdM6GF0S6RjKQkTeaUQ@aURea1cowpYWAhF5LeNmLYdnQgMReUWQLcBIp4bgQm4Red@A9/jpm2GMRT1qM1RpXmpso0ZkYaYF8LlYj7QvN0LAJCxr9StVkyE56bKuodPSHIGFdLQ@sI1YlRoaXSxRhbHRB1eU1zOZIUyX90DsR9ePel@NhjERz2SEMMpRjG3ZhrjZpOupgGJY8Q606Dn@BbXZiI8SUELRMiN1QiexPgwmM4lKRceKnflxSKOFl508tVhZr@zj8JvROl/TqAULaNX6BNPXwcYwAy5yGBb7huYAGCB0uoiUH2VEpRA3YkyRK19gzVljxaNCEN5Fl2sIdHEoJzL0tbaRiwsoVgzZUqFN12omxtOsQIzWQ/up06WDsaM10Wm0LtrNpt6HlHsYVUe2lVJDan3eeeRRCr2nztOoQtI1R9FS5DMOIvf11ma2SDLPlkYSMhEv5j5fChXdDF50ZX48evkwBy5qZ@uQieTCbS7@YuDFKA1CFzXq7YawuaGh1Vr1CKEJvFpcA56YibjK@ZQeqiQpPizKGX1bLkGC6oWL0GkXVhcLxIL2JqbkiiX@qM1MCHal@gujIccUrsi1hTZ6Q/nSknRvleL6ti42RCFq9hoD20bEtero2ApXGa9uaRmWEMKXM/jOokDHFFGg/KdMfTAM@VldrYNAYlv1mzVpEFrSwLWkQW5JA9OSBkWTBpwExstKTxqUnjTIPWmQetIgDEkDOyQN0pA0uAIx@rM6FWs6OmbeYmjL6ys9RNZVEcye6jo/Rz8mEBkqImPJhQGZUVILbEwnK1iZChACKY1DNZzXoCCT@kLvA5cVVWFhXCIKgyt2lAFBi9QTlabCWnIcRIBiZryYMTICCbGxLuegiRDUyNrYMI48gfSPHlK@APme9agz49BIHJfu2ZaC5xMztF2dUieaW8/qGaJZoxG/ygijj0QAKRn1RfIEjCLBULMTObBmJnJosWAm6miLo2NKSZ6HwiwkNRldYFIN/Axxi8AURyqJ1dwsO5QGDEO3ttiKaAIXj4texayZLaHF@JOsGM8vvuE6GejLFn1ftpib6Y0qyUx/mkxeawh0qXqBxE4gY6D/UOIuHErXhwVGm6ESdCkiFkZzbIWZMI/8AdUaRSAaNjaIqxPky@NH17JsiTsuCJOTSfeulUdnDUpFcdqRC31SZcy0patQSZ1jnSmGbg/bYnehkSKaOccNFWCGtZMEPZ6JuuQUhRhdhMbSTZTCOq4lKhq902yiE/kgnJHTilzEd1OunCp0yF4RBepFmZeSiUPaiHtdyDxruEU0wGiA3KPAt9KOoTDYBPU0XFjFsJ4JWAOuu0UYwC@sW2L4SFRKDFD6joVrACr0eDClHXY9ajUErXvVRctcXNYr6ZkSS1F33dBQOYIrvDxQ8QSfMJsqhIP5N1QEE9cidVsZaIrOIes/J4llpIV9coicqRsY6ZnJYbKQpRwUHJ0cp5PDAHA2ylq5ogeTk9vk0NJwckybHKUpMjnR6OT4plXwXqZNDmP2nJxCD4zJqW0XE0wOMbVOjq7o0snRWgZOTmIumJOTWMQy3nBqfija6ozY2bkznFgGjlT7hvXJkQuqRYmyYltdpqSBzhR0oc6wOq7GlkHRyYvIYzIr6sl@ZNZqbXYq1hasToJkGXTHEjAGQQNyxbHlSRHiIfWxyNkXZTVY/skFy2LWQuCSbZQMVJZEM58DphfybDygrYX1DTlp2JSYSvcjIXw1KuOYo8L4AnI4QXM4RXM4qeVwXMvhhJbDKT2Hk3oOx/UcTug5nDLkcNKQw3GziUvN4ZRpDidNczhulMMJoxxOIWMXo5lpW4t4i6rrGecUoW05oOEXLsRk1JUANWtklsm9xKoG4dSaR8iGW/eIdmn1WGEyTkbfMywg3bBa3BTokllTIlxTQEZkKgeVClxEbxH/BA8P83UVYVieqp2LbXl7ts15EzbQltMhe1cJ2bQYwnnx1YDFqEqhJjtLjh6EWiVdokAlUYQjpB3DXrlcXRfICzRwmraWIUCSndLAOC6XCkcs0UA6Xrcg0ip86pw4ShkOrb3AulnBY4gT8k6IdUiHYNSGDIIdxd5yK3mbBso0Z@4aS2EgVRMM5PgURZNaqoHriLJmzl2rhYsa4cRnjpr/cD3S4AlBFMMmXVzAKSHWZJSt8FjTBbocVhf4alZBExm6OCU7zbRoqYdu4cBAIj2wWgQXr@yb1KbZt81xuCSVD0@hSUX3AyDJKCLouqJE90gQneLqcZFr8cwa24m6JwcML3wDJ9JwNwEaIHgTQzEQj1MB4YgiAelE6LmBEiJFBmUVRSlGpNUm5BP3k5CCLiwaFENjsaAiMOowNiy2cd@U2vxFp@NKlqg2Und/EIvdSiL4ID5ruFpMF5fviChlMk@k6C0NCYGmIlBULWbyXoGEUE3@NolUmkiDgUCx6D1NLFU0Yx4YewqmIBKm2w6hbETO0AMKLhS4AB/MeA62/BF9kXbsFdvRF3xqPSbdKAk25K8yF8VdASgzlD8sXuZ8ytDr4hXTd@iQYTGK1B0WXFfKC0LiAl01wyYG1GggDPlCrK1WOCouBOvenC6dFgEqiN5XJfJCSoTYQdFbgkxggQyOwFduFgLxkkHHUhsaVSEEUYbDGT2BHShkjATjVngoN93dY7yB3NWy8e@d@XGB@c/86mfuZf6jX/18y@NX@AP3Gm9I0aRHyx96MNSpURKw4Vn7VLnAququEw7ZWEYaHKASUw/iIFn1gtQL9qHQ5ZRJLtEII3g@PCuBTILjzTLhusRcoLw4tUJWIcQQxZOoPmSctbqImk9RelgE5JQFVgpkcdwoC@IT0UvxrUL8r2hFKwHUzIXRjQ58IAwJutoO8qUZCiOmUgyVZsyiOHSb1cxG3N@A/@WqsWQTUXYnBk50kqsCPfZyE3hRE2gOst0EJEKbgKkB4J1ILSpZdDOFAIgltxI7BEkXyiE@C1tY6KY3GUROHhxlNGC74uzhS8Uw6QI17PUmriOiFAYoXDgetkUQnRKoRTA0DMS1kuB@TjLHW@f8@XbMH2wn/ER/vtd@@FNaOS9FScOjUReSBt2Wz6kb1lpH/ktcHosLmob0zuuWKCjsgxHjniooj0QRAY2eF3HBPPMyEWMhG6g/rloEElF5KOKB3f/YDhaQGkS6kmAcJvQy9mIRXbEeNlHzK3LjCFPpsFGYbhDj8QPpJCoyQMp0O5higMsy6zoy6qux78vMxq6uD6a7MjXuisFxsyMfrnxeO3dDalT/LFcuCN@Z1nBllsMPZWx8TfjOvcp1gheuPJe7ck0/Mwye5jfH6Zphp5shU8M6IGYg1L2HvkSD2TXdLYqw3Q65KoaZUkOPDBrWOkpBET0SkLjcgjkMpEdyWR4njfeSDxQlmpnVLdpiVDbE0oSWlVFsoHCVQU0xaNp/xbCJ5dzISZiZuEucxtzD3K6bus2DxtTTD/YcrVfrqfJQTzXNSkxLHvqWZVpPxco9TUjoUpGhtotA1vfcoG76QVjPyWItEoPHti2a9roHH4N9fpx80BpCbqVkGPaqmouY21J6ZkR6RbZrgffYQs2M22saiATLtBoexsRZm5NxVHVPJz6/ln1xez3HfQdc1dIfRjaI5iL9byITK4xIikvSWhansRaliZlLMeCh1aBx@1WsQOamZVXX0wTN3nldOm9ZvsdFTIhW1an4X6uB4Q96nfB/0Y75g@2En@jP99r/017HdDGp050LqDCt/jK2ioSce5JuqA9ixIb0RHffJV@v3bZEN2y3S9YWWuGO1@Bu7PvrJhZ5svCVpaAscGT4n0VMuLVh4QB3ImMaizE3GCLDvaoi49NKJ3Q5B7NUTE7l2DfVsE5BYcvC5l7JYHXdSmT6g3lyq/xSDQ8ifGMT2yp/NcaqOTYtmdJtJqkJfBhmYwnyNIKtGywRTCVdZKsFIlzC5EBKCwvpkP/PjQTqToCx1YerqjE5aHTDKa6Aw2JERcyM90rndXMtVi2i6p31bcL/dIGhZbWdNMepQ3pH9zp2jB4KomX9HorVQ5x5cg5Hbbmq3KpquT2P7pcUW@Qsa6xOw/uMWdLjSMPciJILHxjFyblH9bSeLGihNrsZWGvSA0aWSxzEFKg4cEMI4e5GQxtaBYKUBstaEwPaDOwHsgrdvBOl41yznPO40C5O98zqy6NZ5eCHjaZr30@aJrzklhKm7WOahFyWAWkiM7IITdgl3XtDd1NLauR0PRg3U3OaXuZezlEDqczJ6T7LLIVk1aduzYHyRj9djBhVCXU/Zlu5rKybUqvLRaxup4gAInEiI@oFKjYXDW7jMCrz1Z1oY4szpaqq07a9ZOGI5RRoyEGXrGbDHUKdbsMhEE9HjuvKkF5lqF5IDuNaQl@iRr7ArVguhWUwrGVypS3iEu7OjTwd9pjUxWEilVySIIKeUYnL4F4JuY0pUkROc2My/SkZzVuLHWDx5vE///m3v/26f3J6f@fN@5s3d35ZOF5cuP33hTcnx2cnR3u/7p2enpzevHHnxsLSws1j@bCLv56fbJyfHhy/u7n466edtxvnO6fnN9MvC2ZRvr7xXwu89GjveOH2ws0z@di/ubO4@KuceHf@/vofe/5yYffyfO9sYaINnJ@c7xwtLN1ekB/@srDz697F3unlzZsXvYMXo5YWbt9e4P/IdLZ483hxceF/Fm6sPbmxIF1ZufNo9f7yjcXFXxa0wdvSzb/9rT/d0cm7mzde8Avt9/64f9pldk3frU9yfFs7ef3lvGxx8V//Cw "JavaScript (Node.js) – Try It Online") ### How? Most sequences are stored as arrays, using several compression strategies: * Large integers are stored as BigInt's in hexadecimal notation. ``` /* before */ 805381710463762432000n /* after */ 0x2ba8ea9e9255100000n ``` * Spread syntax is used on lists of at least 7 consecutive single-digit, positive entries. If there are more than 20 digits, the string is turned into a BigInt in hexadecimal notation. ``` /* before */ 1,0,1,0,1,1,1,1,1,1,3,1,3,1,3,3,3,3,3,3,6,3,6,3,6,6,6,6,6,6 /* step 1 */ ..."101011111131313333336363666666" /* step 2 */ ...0x146626ecaafee6bfa04ca8cean+'' ``` * Positive or negative delta-encoding is used if it turns out to be shorter. ``` [...].map(c=>p+=+c,p=0) /* or */ [...].map(c=>p-=c,p=0) ``` Dedicated functions are used for a couple of easy sequences: ``` /* A000004 */ n=>0 /* A000005 */ n=>(g=d=>d&&(n%d<1)+g(d-1))(++n) /* A000006 */ n=>(g=k=>n?g(++k,n-=(g=d=>k%--d?g(d):d<2)(k)):k)(2)**.5|0 /* A000007 */ n=>+!n /* A000010 */ n=>(g=(n,k=n)=>k--&&(h=(a,b)=>b?h(b,a%b):a<2)(n,k)+g(n,k))(n+1) /* A000012 */ n=>1 /* A000027 */ n=>1+n /* A000030 */ n=>(n+'')[0] /* A000034 */ n=>1+n%2 /* A000035 */ n=>1&n /* A000037 */ n=>n++-~(n**.5+.5) /* A000038 */ n=>2*!n /* A000040 */ n=>(g=k=>n?g(++k,n-=(g=d=>k%--d?g(d):d<2)(k)):k)(2) /* A000041 */ n=>(g=(n,k=n)=>!k|n<0?0:n?g(n,k-1)+g(n-k,k):1)(n)||1 /* A000042 */ n=>'1'.repeat(n+1) /* A000044 */ n=>(g=a=>n--?g([a[0]+(~~a[2]&&a[1])-~~a[12],...a]):a[0])([1]) /* A000045 */ n=>(g=(a,b)=>n--?g(b,a+b):a)(0,1) /* A000051 */ n=>1+2**n /* A000058 */ n=>(g=n=>n?g(--n)**2n-g(n)+1n:2n)(BigInt(n)) /* A000062 */ n=>++n/(Math.E-2)|0 /* A000069 */ n=>(g=k=>n?g(++k,n-=(h=n=>n&&!h(n&n-1))(k)):k)(1) /* A000071 */ n=>(g=(a,b)=>~n--?g(b,a+b):a)(0,1)-1 /* A000073 */ n=>(g=(a,b,c)=>n--?g(b,c,a+b+c):a)(0,0,1) /* A000078 */ n=>(g=(a,b,c,d)=>n--?g(b,c,d,a+b+c+d):a)(0,0,0,1) /* A000079 */ n=>2**n /* A000085 */ n=>(g=k=>~k&&(h=n=>!n||n*h(n-1))(n)/h(n-2*k)/2**k/h(k)+g(k-1))(n>>1) /* A000093 */ n=>n**1.5|0 /* A000096 */ n=>n*(n+3)/2 /* A000100 */ n=>(g=(a,b,c,d,e)=>n--?g(b,c,d,e,2*e+d-c-2*b-a):a)(0,0,0,1,2) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score ~~20925~~ ~~11038~~ 10270 (110 + 10160 output [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` ÙgiнëW0‹iWÄDU+}¬_iÌ2U}Z>©β®X)I‚εNVεƵ0ƵÿŸyåiƵ0-₅B‘Ƶ‘ìë₅Byт‹Y≠*iyëDg<i‘Ž‘ìë‘•‘.ø}}}}YiJ')«ë`'вsXi\ë'-}J}}éн}„IèJ ``` -768 score thanks to a tip of *@JonathanAllan*. Takes each input sequence as a list of integers. Resulting programs take an integer \$n\$ as input and output the 0-based \$n^{th}\$ value in the sequence (although outputting the first \$n\$ values instead of \$n^{th}\$ value would be the same byte-count by replacing the trailing `è` with `£` in all output programs). [Test suite to verify the results](https://tio.run/##3Zxdq@3XVca/SshNra4l8/1FrKLkxl7oja2tbdFUD/FATdQkQoRAKCoIfoDqhYggtKQoCJF6UYVs2xuh1K@QLxKf3zPnf@3/3uckTS7N2Wvts/Za/5c5xxwvz3jGmOu111/@5tMnH/75b/7Ki7/x6p@8@cYLrz/50zefvPoHT174uV@7@6/P/9ILL/7qW1946cO7v3vl6U9/ePfu74QP3vmPp79z95cvfekX3n7/@7/39O5v05fe/t1fef97P/m39//lK59/64N3/v4n7/3ml3/y3o/fCz9@7@6/fvSDt@7@@an@uH7w7b/69Q/e@c6P39Ovu@/fvcvfb/3vt3W9r37wN//480/funv3pVd@@ak@/dEPj0Pe@c4H7/yTfv/i3Q/e1r@vPv3i5z7//rt37/7@5376b69/5enX79793PXtL7799t33fvrDtz945x9@4@67X/zwxd968w1m8id/9torf/byHzOFL7z0yv/89fH@t56@/gZvvvSj//zvv/7JDzS8r7919693777/3fe/@4tffvsLL4brN19@/ckfvhDDG3/0wpNvPfnjJ6/6hN@@@@7l/X//1filb7z426@98fK3XnhtXfCbb73x5PoHr73po97/19@6fPi1r4VL9E/az6rf6//1dyz7j@ODuF7UCx/4w3g@1AfxovnjfbF1xrqQLxDzcbnsk3Rk68cFj/@DP8qX43K6zDqZ//Y9/Suse33j8rV4XHZP6P53vP1Op9fPfvq8sx6f83HHfNTVPs1Zz4zQM4uProFo0pLd/o2ojv@TRJb9u@z3i1@vd8pl@P31uu5P2@338JHTf499/NDxw391vyOxt/1x1W9Om/7LHxTWZtwut070UZpMuHxmfm5Kl/cilJv40xbuet324oy9HM2vj/eRXdqCPt5fyyVp5r0yaQtxXSiuZW9ejuNK4/zB7Y3gJfYn5XaTmLZKlLVY65Zz335snVtTOzSo6qftn@6fsX@mfzDF8yOeHunhIz98lNOjPvNoz3v0h49xfnj04bP182BFilcC@W/ZLilp@fS5dE5qFi9ZaxYuRUdPvGeV/cl6w6XLbLXEWjWdHiRxpJ60XllPnRHxvU1PHRuHnlNXDHrqmKRjUtFrfZ66/p9SUH2W9VkuumeV4@n9kqf0SytbGESV/ummZXbFi3Gppd1c2nk6w0qzJjM8E11HH0vlm07y6HXUXINOhBo9m47WzZJnLiuZGoAmkTWwUnSzyMx1@TZ0drgMXWVq@jGid0xDV0GjuPeQEFPQWZqmLKbqGmligkln5SYJlqBJlKoLVERWu0bacj/by@Fl23KGtq5mK4kYTvQrm2Wysa05@71kP4v0/bZ@@@zss3jdWFFMN3GA3tEliu1hvSNx6c3q6xUfoHN11bpuzlrxjg4rvnNbr8uD4RcbNHfUymgeeQmblW6aCqONjdux1lPK06NWOObGNWsZXLxr3WdCa2JvM@jA3OtkDWfNuIDShi6cSqhJAyotN1ZsTF0koHo564X0Kdcxki7WagwjNE7lyOCZ1qJ7aIil91x1BzmwNHpPrVpzR@tNSyelTEWfzhFOofT/0c8zq4PueC21AhIqRpq1vlW6H8NEeaTteejTzvuRuctkU9cF5pRizFpQMElWEs0yTLSj61zkO8PoSHfUivV2nYCzkHVlbtC1SAO7ZNEGS9OjzmRVc5Dv0IJJDWQxY@IEdDVdJjYHfqYRLveTqTZ58B8K3DUzr6ugh3zMwLxr07FTl6y6DbMb@lump0Ni0TBHlNXirqRnCKHr5JbmzGhtbUE@LNVYY5MPDGVi4VHHSokwgFpy7VyqhVQStyxMlllGzVvqJeUJKY8oXyc1l6RCVrQpTcdp2nkDgOXCVkScR8hboe0csKZddD49qh/dj8kDvx3t9vqDh3zr/SP70U@PaSefT4/5@CFB8ijHo@@HxHr/yA88M04s2hGha8m6Jplb18ZN18qha2mcdA2ftHUNG7zXtZof6FrFad/rWkbmZ12rHYd10jXWpzzWtRrxIiddW/F/TcKwtNlvysES6FA3HCk@EmXvzT6TwFJDHA/94XDCUvGFQwtKPqOJ1owdcpVZWK2EghT8YEdFm6xNMaJ2PH0Ik6XXJASm@kSFuiIkXqqggbr8SCly1ZrScIgbGoZ0xrqeZBmaloxD85UuSmhWqiDR6rJaEGl6kfSk@kFiIhjKZ8epSxLISmhxZAZbeglFLrz00xSrUX1HaadR@oL@Ka34NYxPOcTIojtAb6km48@0j44b466wFzauNcoMfpk3hp0bGE8uxBudFeXSgicrywlr0cpZEUGH9Ug92s6DjpuRJx3Z0Q60nD8uhjINUSuW6fqVz0JYmts7t@z6PDlASVb6aJTGwiXHGWGaabhDbEJnW3CIilNxCEWSw2pINjac4JBnUOxBeXW@jmhav9xau1feJIepEEr8lFoXX2cmHVZ1huyoaiTRgX9KW2Qj7bRallq3RRZDOCkl0KuhfAujSfXkQONFVgUwlCeWigz7gI4firN3HJHAjRa2KsZqDYbCqe27Jy0F0VT2JYQQesbzJql5AKPUjCMMwDkJb/SL/s@yBPybjghZ9xQELF0RWU5BblXnYuzSO0XiYHzauyyjdNx6UzzR9foOEPfhwelIwPnhV2RU0mu5oAzWk4NLifk2xhoqylMG5ikXPsCcg8ghaKtLA4HklYC@SfFhHaW1aNhDGBPN0FpXmXVFsPI5zfaMmGR9RAo5tKKrYPfCsznOjKmPmZuCSwVnae5tZq2A1@rKHK5p4T4QYMW4ZYxyUonfEUypwUVcp5Yo4eGIeYJOFXEpAMlmgxVRGKoXUI5Bosx9ygnI8cmahhwOflCLqquP1qS6/C1ttY8oTcMuREkpMJ5celYlK7njLEWW8KWg0eFMmi28Jc@Nf9X/mk9to8rDKK4Gjfikhf0AITpdkjBgj8DjS7etAe46YVs@Cz9pBCkHqVChqCv3pwsDvRVkdWAfmbwgLNdXUUmis7y5NDmg0LLU0WMmotbC5QHKUlRgqcSlIdsBtVyyjTkNXaWBRRVQNDkprNSj9mAb7lnymS2SJAldtiklkHnq3KxDD2u74rCu5L9XgvsVr3JdOcp1BfgrHjroQECJ/uskXVe8vI4ka9GbBOOhk5nB5UrmNblKsdCuMQET0JeK8fGiEyt0OwRKrnVNoG29e83Ir/BCcCbL9q@l4OJ0Mymh9ItBRkfJy1VWqrimd2TY8i4apdSZ3IlJxELCsYH/OaNsO@THI013Rj4MX5LhS2CqZFvZLjYA3iaBAfQCEDVpgU@6sIrFAEar5U9BL8nopfhP/KYzm8KFq2m@6guTNOp1R3h4rmD04tTH5nSxQ71IrJIFpq21bM9MZ2xa4uF0Nhwbj@dDQkVuazh2mhBB4JgQaOSYUHk4Icl5TUjCBY6dJqTF1YTwAc9MSJYCHHvehEAmOLYL6FPT6Q5xB9icB8o8wOX9DG4D7w/H2A@YWDyW2yh85wf3lLYKC0QQj4MDWitTk7eYKBGLTOjNKxknzwu8j0IwLkSeN7OA7EFfaNBYLANK4oTBeSOY6bRybSGuOLaGkBawJsnOQwLiQs59K3MDgyxnklHGTpCqQqYKjso8pyMCGimYKItpvcYxHMVHJamegm7YkKJBJ8tRiLCHkMUMEubSiP4Jm6qKxKZJ5CKjJa1wUnHbcuqTwDN2EHtGBZ/zk57zk5/zU57zU5/z057z05/zc3B247HIy@HPw1pIiUlCuxjUCL7LTEzqRBQxOp6HZNQkTRKC1zyVp4GHcaG6kNIzXVmhH2wtP6uFkMgGcRTwEElSZx29cpLCjFwcYKuD/seBmsY6VTioQToJ9YPlhEwUOVCnCRwmH93oLxuoYhi2X2k84QhfJQieZeaKa9LobL4CSqtzS5lpZ/VxrpGRSDGgrJSEBMwz4JNDJp4oFHZy0g50l1FJT2BAgqaLvs9BSQTYPdFfnURuJuwxGIrDtG1BQAgkExRxE64xK4VK0EpGBIxRIUvqnq1Rm93HVZEz4MejgUEooEiGZtWMuswwGaNUVTiIkKKUIjRzMwqFA7hAxtCU8QjbKSBW@DGNXCKV3GXiEryEo1mWFSuHomLR8DrQAE@oN/SxLGekQciSTfUpeCDAp/UNToqUu2BYYQhuzDwFJHBI0pmUlEM3g48iVTlc9mfkeQKxn5nnDjrLw1w37RwesPfXMxF/XVH1umMqSGb6mQxh9BR@WpH0qgB1lVpfZQvgpavU9CpFBjRdpcdXI5qwnzpVwfLa2n4OQI6eur8s4gpCkgVdFQuuA6ilv@VRrlN/y@iuYCqeysdPUzpm8wghfBQ8@Hhs8AmAwadABZ8IEhyhOpjUX9G6kjEpTN6HbWX2yp0yDI7EsaL4xGNbEp/FUskVJQO4XxdoB7GjptcN1EHpVjlUrS1kblhuSG44bihuGG4Ibvht6G3YbchtuG2obZhtiL3Q9VUAZ8F6Xwjsn8g4r0q8PAKrP@hItoCaurSgEU2PqVjhA3eYirhXhQ5Um4Rdo1xDJH1iuLMydKW893rdD2x4A4bzwINxI8FFEqJtiwPMVqNsjTkgXt6wbi44B4QzdON/uBtHSz31N2UCqvidm07n63HyzM5mCL/KKC@k7gkTwh9kSFD9rzGlylPvkzhKxIpBt2zzfkIUoYwKE1bT9zCzqwy6FFQxJlgBZBcYOCCF7J2cgbCoGEY5i1gIjg/gQko4ShWxQ61@g3UexgEhAhNSdsg1twAhoFm0zDiDRqOINjD7TJFKCwD1Gjs8U5JgBTV1P61ZNkSu1TlXJ9ETNrKgBLDqmicPP9ev/fv47/b//YvTq/PLB68f/vHor8d/PvP3s288553nvfXc9@JZOQ/NzCalnfV36xfQp63XVDMD2jLwsjpeWAd3Kg0SeJeWCgHCrUSDO9ZEUDBCa1EdKJQbR0usoYSPKuuDgha2MFkcoUYpfJ1l1QpkolbrYfWbvWH45hi06G32VFFl5wPO@qewIQotmNZYeX1OdYtzSlDeTvGy6mK8kINorTGDJiQVMMFI8XGe6PbsRgqoZpdua7VYoEdcDVAwCLhtTA4wDm9eSKZ0XZsp2LQXgtXA/5QKehNyG2YaOih@wilDcE2NpQbAmQLHTNF8ehdMxUYTeDgXsCScgixcGi0tlgsgS8gUUTyqJgDooQlzkiEF2QGuTAdIbqTxFV5/dEh6GGi9y5gFMCeRrSldMFvu0p5GB1RX7hBg4CC6Eves3SXkARMexq2M9LECyy5CU9OdLGqVKiRIzoJbah3GKkwKp8pkEBiL5BKD1CKYV9QoUatWSEOFgSO9TgWvNVCjYE2wpgCQpXAUGSuEZg9pwIrKyxVuJJwcyKPk5fQ5zO0MguE6VV6i1OlCioasj@uDVp89v@L5Qe2bSIxjrrQsON8gaYNw1RK4QEVeQ1pWKY6V0XpwHZZEQJg9rDpsoA4LZ@w6rAvFoVAHcR1WN6AOa@@36rDBddgeenIdVmDfKblWdtIDsOqwFJK79E0Xvk8tPQNTKpReCBP46Clfi842ykfAKI@@QDvKPEwIdngK67TypAoOS8PYqpCVw4fi/bVYJGjKMDQundFl9U5XldeP1bJQYPpkb8pQWwIejVmgxaLshmQU36JrBboZlPEoaNjhJ3h5KR@ob3almno@szrTNXqaDMBW9Evk6HQK9Yq30lilNBZcGusujcH/Ki1yaayu0lh0aYySvIsEuzRWV2ksHKWxsEtjdZXGmqS0S2P5cWlMgriVxupRGpOspgCJ/JHLv7IyyOS6m7LOkzJN5OpC3NUFhOKmAHheyVmu060HFPxzBP00SWBVF5qrEDIrVxdkO2OwMq4uyL@4ukC5nupCsreXL2d9XV0Iw80iWjeYS@lUWMaYcAwYENUFpeZ1VRfQmV1dkCHNVV2Qb8lzVxc0h3jSyNsEi4HOsFFcqM0xdOINXTPyCCMb1FDlzCT4sjkTI7F5ZSRbyicU14S26wC5CQJVNDKD74qpg6R0l/gis4huWpCno9YpFzA0aEHyalfCerRmdEIrRZvUnrr8oUTrNpWIykKpwZfrLPl0zUGOPQhG1lt0XdUhpw8RaZBbECJdeCEAGmgOA7OGi9dYcUa1GtbJvPNS0gqtk1a/jVTFMU8uRiE4KmbKurRgMsZpSqQn37WiXTddrIu80Ycah2abK2ERxoxygqNWll0NRiZIVCTwQkgcLklCm/XdyBjcNxOc0VTnOIuddG0I0Jo2PiS9MnlMbjWdanVnWFSMnJcNp2PFNfPopKwZEa/W1ZUuDWdJGsJ06tSdMWVyqLh40uH8qwCZwc5mmUDQLpGU3TxDG1YxVg2G2s3Z22TI7tTImyi1eixUXepG0@OGoLGPZORbF8TFTAo3WrR5fnATt0R85B3qvkPdeB1ev@47Uc7h2R@5uYZkk1OGSCktGxTYy@DuKPgU43zKy/KxE8yswEPYnATllEPzAhcKilVe2CVY@Y0hzEGrmOLJXKUJqQYDkaOUjVSKtbqn/AwDS1m6hVHob/m@Zj8rnQlDEB5kEQQwBGmIKPK/QmyFwhOAJzTFZGFBZ8lyH7NpcM7rNZrmopG0QIivaazCJHF3dLkDy6USl@op114IUNBp3S1z/HJLgNnN4HiARwkOv3iOIZ11kK3uP8OPQC7jTQtNUixOdUU5m0vvxX4EcpMsBQYOj5SWV5UBuc/F7@BCNetkai2U7QK6VwsjdL9C2InbTtBuCRhlY1ZpgKkzoV9PKAqgIdZi7yJr6sYay5tBRqDm0A4dWeqJDWaqaxfjHh2rCHtxmTVwU7Ovvn00dc8HeeFxHA6xGEwvafDKeK3k21xAIQOWVmvDONGHEKo0IAxHGyp4XReU62ERJDIaLnyoIhAsJfRwl0ZKtIH4ItCl0eHXdSfpkYKwYEXF9Yb7QsStHZE1Oegfcz/3VRVTOzuRbgdD0w8yptuXdLzIqpbUbY4g8rkrI2Wn1XlXQsZOrTFusFNbvZjEdafXu5kBhwdcP5zDLsCulLptJ0E7w31NzNURfFt240mgugYHLcfL4GjrklNcnVFJYvGQBcYrHcSyPuU/TneGoHh1sVWZB8mGMS/GS14y9Ll0IzunmAoI4P1AkVnSFZaRCVNVUQQho@iemGvVAiYKpI36qJBQoNieXMCtJARD/oVohA/MchjKnDVCATnisbBed57R5mpli4YHcjgy70LXYCb3UbAS9hWuCKPcd1SUXf8Yx2KX3X@5OixXS6VBqnslV9Ey7MaSGnZnKsSdIxTmTQcTEcE@2Lqw6r1pvbPqWQbz9itjvx7LI@O@jmUHdTU3lWw1gJQcSw3c9Xq8d@x/OFpp54nRXAXPG52Zjs6zttvOcjixmEd5c2v4jb98RF4u5vJGWy7O8lbGXITlja28UZWPeMpFUt4YykVPbm7ytD51LwvEatqFQwrBhD1MJTktZUkI7qO5SLPAGLUpKePk92BVh3tY1n/S@07Kp6sQ@ZqyB2TC//QrCX7SQsH/oFvlAvSFhPsXFBGFduIqJ9J/RUNJJy8K51fR7STDnRC8bO5aaFVaT1ozbkvn1p68m32zs74Kj4XsZl5aApdU5zL@6O43LSGrVx2ZivvgWB2tAd1aVKcsaNAuioj34P5xEVtu@F49EYAswwACjXvjChX85i45Nw/TA@w71cntenDrpFQEpN@hC6TZO5uIpwZC57DJgKtaGaLjnctTq6d8rsBKqxJYuEMdBsi9RE4LByD33NeI5EEmnAqd2DTRuEYHszEythTcF55IyuHtknm7Zt7ONUQ0KWJR8HbulKLulmEu4e0MOhbjgVMmC@uLt8vGXLcZ2StURLztt50W0u3khuHBxB6t0IDtvpAelQQa1yZKD22g8bhT2aVPIQhCgfIuSNFpKB7c1TeFlQkRk/YzyEslD1yV9NYd8TnPYO4EDgXSoupFraujUBGhuX2WmEmTGNAiI8NB@xNkDMgDne6QCkLudPvKgTTpb6WTq5/n2I4u9AV0neSv1gLkF45tBsHAkXYX224Jq3O/lvvQ1svealDs3yAskjvkeY4D85INQ23QXnmhmzm5b2@AuZYK0TTnPnhkX9ZOgEojHasN/4OFhGUllGfa/ZoduynyjgB4y3hsqGjHnop0X@fZFZ5ytFW4RXbXc84usR/Vm1W3aUdnRbIPdJXm3vv1tSsjnHor@qmngrALiuhLnEYQ6R5FpHGazurXYbaVQcxN2rObgyZessdgaKrbm/JKmykL@Bb3alWtW@EoOTyNHpp7ImcNwCtp5DAMz/Nq7AP/K83rhI5BS48CsYwAWoVebRrWl10JuWA4gpzAeEFyOrWVXQZW2P1YOTpxyKuJv1Sh5PjAt3iKyc1G1T0qUFaLLaWLQXEFbo3@BLwv5B/0CuoWYBaiez9hKdYGhG7yryzyLy3yry/yLyzyb5j8Q4jO2Mcm/8Ym//om/9om/8pB/sWD/GsH@XcOb2saMKPES9JAVJz2g4kD7G7ao6jg/uqEExYGkjJKJLS1dQiWCPQhDAgJoXalgDoTRfts0oF6k/KfQiPqFA6mUR6nI48C4RDhe1HTietghlro2iGRnKMTx@RqkpI9E5b0wsS6QqqGquHg3fU2Oct9CLjN0PCZDuroshHzgdaayZgWX5Mpg4JlgjmFCWmRKwGptWD/qjGSBuOduJfCtFasIig6MasFJ2cNl6vhol7C/y24m3EGHCmhUtExAdrZD0K7g84MUDzKgic5FptOpNi1m0FWosFf5BnMTE7w4cqtzvC8OsO7nVC1hlER0BiEowLYB5UvIGxhjYKLdLYjXOt24ALxhH7iNLWUwaT1gGfOMIGYEPVEM0kBDg0Qp6nVtIjrxj4oAWotVk6re6k7ua6KM5VG0TZNtCyGmCanXuetW8lTMZdQDFxxFIntTnJSHgzBNkN3t@RoGNxnTPMHfTKJvtNhQsHce9KKEkz1nkOnwgzrn2xCpWfHOtpMoIIld3hb9o5phZxiSieDGbFMb8/EJdAOFIp9rJtsoRxCYd@J92sFAj1treTD0m7Zd3vsKxyyy@KKUEE5vurKHN5vepsFbcS7IQ3OuVVvWTMxRk7JcQWlV6CksCBgCaFNJxAIiILFJG2uyp/GPCnKOAxgSRdAhZZKZCfpwq5TNvQKW7rJ0oUw6sHJAe2gSLcv6WLClm5Y0jX@lHRrsHTz0mp8d1jShYizdAeRBenOtZsP6YK5lnTdwruk67qapUvnzpJuoyZ628h7mqM7D@tKcXQPHU06bM3fGy0quz@kxt2IyF2s5lJacRPo0eA866I2LfgKy0@hIANoJfI5l@XXuQitJhAE20aXLzxLoS5SV@mAtBZIGykwDYNWuuvZgSEnUQqbSqhpTXc3Qa0Cy0u/z6e8jSA7lJuTIbx7/x7AJ1jjJOdBOgafWsynDvOpbfGpafGpZfGpY/OpbfOpafOpZfOp4@BT28GnpjO3v/jUceNT241PTfd8arnnUwdJkjxPxzUN@dPp/vKTcnpXkpNQmt9hdYA93ZQP/HijuKZsxqRhD@wnlYa79D/gtiXHTOalO0ZXt4vDD5VK5QQKmBWaldoZ23UidAu5TzmV8spq9fcgjCJkhis8EQdxekQd5f2gCBfjkrIwannUN7GgFMmKiqBzc8Of9dWBWVmSJDi9acY7cxTwkosymh51IpbR5BA7KCr9jFSTvAd2tb6h94oRmqsrfmw6EGiAyeAGJI0ag1zFpgzjwRh0dykcKb8rQMlQFfbGVCJJFRoTvAXA7a3dNaDkzoVqmkW/ejWlmVYKl4mjhkvN7XrIFKADSTB4ZXbQmwi8@cH0oflJ92f2ZK7UpURv5oLYINLY@FI97871wmTvAaWZn7mwsG14WxEYVNl1d2elt1BJpdn7Ig1T2HG6W71jDl@Fz0T8wbuRMGz8a2DZ5H4nkAIcA8CQCrJnl6w5UMwbxqPVTg74IW/cKLEM@jZkxJHWw0JqdzPb6Mykea8Pm0WseFIQ@xnvAJNvW0U5Bpy7@S45AtpStdy0ZriqhP@8GOIY@dAl0slPhE8wCs5qUplAMc3stiwMB2Xj6AiVTLwo/VLu732zVCT1BmFAOEVBkJhDEswmVumvLhHPBrp67N3hQvwg/ZGSYNRrbxLLjJawWYN1kSzduRn2bjtNOhj/JTaV4OAvEGgCTWa35YWCeQCIeTaQGA3Jy9IxnbxBRIs/4Pem8yshWYF7LGzR1Yp6mr2gE5v9UA1Jk9ZSXJPwpRJLdkKZuA6MREushZf/Tnuj3rFZ/9yJ9vj187rUPuqYj7pO@ATHfNy5x0/5uOvctqF54VxTW1RMsvEqFGbq15N@3uktZ4kyBNlcIlhDJMrVUwSFImUPmpvfmz43D0KmRXgguDZCR5fIvdFFSE/eeoAyBfNpMKGHA4JnKncPkKp0ylM8EWJROE1srWbpKuNSiFD@dVY8N1aYjAzeIyWYA3R3WzZLau4xyI/IuM1QV8Wh2O17KvcL4Po@TVKFSouDHIL0nHbxzM57RcLZQLqUcQibwssgMsBeko5Q6fQOrEK0101kxmiVwKicMxvZvE20A9c1R6qr5CqKV8QJmbYbn9miL/dZKZSC4wTl2Vsl3VXsJ1zvST9c0PSRCnPsLf00x4efcXz5iOs/Pr98UsU@L2S72AvS31/8pQbJEcK9H/4PfFYHux8vRLzsnYi0Q2C3bGKkU4TiFUaetWJIm2OkOMKV9EJN1w8rDRpaIb4zgUvQ4B/I75XF0UkyOjsfpZcx4wFMj@qGFb@Q2EnuDZiZozUyynxga2@5HIGY310n7HR2sb/y9hUsybJJJ3mmk6Gmm@TK6flQyqsWwKtxerc8kns5rUB5zqoe75dH1xkP1ricxpNO7/v1nhNM/o063fs9N21KBRcS0VGjrO5JqGlvRQaBxc0Ckz034wdYjDlvHC/4gYCW@kpbIc8qaQKvmlkjoNwwou9UL32NaphKcWtRpA4zRieQKbJbj854pdHuBZEYbnlm3RxbOX3DB/u2zKW1531LyXxYyO67kH3QiEeFbG1MdyGbhgVTiG7V3GVz0EpeZLk304HDECvFYZim6L0h2V9rAO2Qb5ShOyTY3xvI0OkkCqfvMLpNanVpJXNt1VwU3JzZVgBtcK0VWoxaatf/03uJmYir6XxhAfVqvuyAm5PKEbsrLr@BeAe0h1yjq5LJaaRRd6cNknBgU@a7V9hmwY706abUYnI7eyNPpG@BFl6S6rnV7KH6lp/h9MqnOj78jOPLR1z/8fmfxukFr8ncG5pQMfd7VFenel989C7BkkCC8/xVN@Qgc9lUTfvrbYC2JkLdUVhCXV9p0@gfoUGG5hIaL6DnKALrDoHKEpvKoXlJ3mV3gZ3LFbLJsMwdj9C58Li9rv1s9Jih2i4Q9FXSim7frFCOlFyiQbYtTRDi5ibc8mNqBZLZ9WV/7wWKxCApEBCoTUJ5Jy5RsXnTgmt7NN1KeWRxjCi4Py4vZ0HV2r1c1kyI7@Btx3Ra06BuMAOdo6F5GzWdFPSfUcgXBHb7eaR7QNdA1nCl/mYg@hekmoEOBLrISr1NiAlO87rdTTdsEvXmWleYLt3JvSk32As8oS7Dd2PQNkjq2PvO/11OL26uYiSFYuFOSSMdgjIPrxk7vJR/BCdcLunBIdIbQ9K3yLYChPN3gtDcxZ6O3m8NA3VviF6bRCh05f2NSnN9exI@aHSXJLBzSEhQOnQSYRicZr66eTuct7k3m7S7kNnlnlzQ4LuNqokTWGl/ExEtGbSUeJcc/Rb56Fiv1nJ/V1GcNDBvRxHdNhn97RAQCkR/GC8lVGdmx9M6un/8TTPVSWub1tT15RtU/iLCcybkjQY98JUjyVviFK0tAdqXKQnAmwklkhILAVZny4BRysz0elIdTmO1DyvL4FtDEl@F4W5kKQndfNK2TpMOmb9y7yUfmNVkvlhL1WgaoPKmUETDyDe@8eH1@upr12@9/Bdv/R8) or [try a single output program with \$n\$ input](https://tio.run/##AccAOP9vc2FiaWX//@KAouKAmG7DscK5wqLDgcOFUMO94oCZZMO3WsKrIuKAmcOpRsK14oCmwqXigqzFksO9w4figoIkLsOA0L3OsVpsw5LFksKowrnDs8OA4oCZeGs/Pid2w5LOsc62w7figoHDhs6x4oKGzrPiiI3Cu8Ozw6cnw5M5wqHDnCfCu8WgNmnCrMOZMsOuw7MrV@KJoMKmUmww0L3OmMa1xb05wqfCuMK4w4VDw6PigJ5o4oCixrXCqdCyMS1Jw6j//zEw) (which currently uses the first A1 program). **Explanation of the generator program:** ``` Ùgi # If all values in the (implicit) input-list are the same: н # Only leave that unique value ë # Else: W # Get the minimum (without popping) 0‹i } # If this minimum is negative: WÄ # Take the absolute value of this minimum DU # Store a copy in variable `X` (1 by default) + # And add it to each value in the list ¬_i } # If the first value is 0 (without popping) Ì # Increase each value in the list by 1 2U # And store 2 in variable `X` (1 by defaul) Z # Get the maximum of this new list (without popping) > # Increase this maximum by 1 © # Store it in variable `®` (without popping) β # Convert the list from base-`®` to an integer ® # Push `®` X # Push `X` ) # Wrap all three values into a list I‚ # Pair it with the input-list ε # Map both inner lists to: NV # Store the outer map-index in variable `Y` ε # Map all three values to: Ƶ0ƵÿŸ # Push a list in the range [101,355] yåi # If the current value is in this list: Ƶ0- # Subtract 101 from the value ₅B # Convert that to a base-255 string ‘Ƶ‘ì # And prepend a "Ƶ" ë # Else: ₅B # Convert it to a base-255 string yт‹ # If the current value is less than 100 Y≠*i # and `Y` is NOT 1: y # Just leave the current value as is ë # Else: Dg<i # If the length of the base-255 string is 2: ‘Ž‘ì # Prepend a "Ž" ë # Else: ‘•‘.ø # Surround the base-255 string with "•" }}}} # Close the inner map and three if-else statements Yi # If `Y` is 1 (thus the second map-iteration): J # Join all individual compressed strings together ')« '# And append a trailing ")" ë # Else (thus the first map-iteration): ` # Dump all three values separated to the stack 'в '# Push "в" s # Swap the top two values on the stack Xi # If `Y` is still the default 1: \ # Discard the mapped value of `Y` ë # Else: '- '# Push a "-" }J # After this if-else statement: join the stack together }} # Close the if-statement and outer map é # Take the shortest compressed list by first sorting on length н # and then pop and pushing its first (shortest) string } # Close the outer if-statement „IèJ # And append "Iè" at the end of the string # (after which the generated program is output implicitly) ``` This will result in one of the following programs: 1. `abвIè`: This is the base program template, where `a` and `b` are both a (compressed) integer, in one of the following forms: 1. `d`/`dd`: A hard-coded integer, where `d` is a digit (when below 100) 2. `•...•`: A large compressed integer, where `...` are three or more 05AB1E characters (when above 65024) 3. `Ƶ.`: A small compressed integer, where `.` is a single 05AB1E character (when within the range [101, 355]) 4. `Ž..`: A medium compressed integer, where `..` are both 05AB1E characters (when within the range [356, 65024]) 2. `abвc-Iè`: Similar as above, but `c` is a (compressed) integer as well. 3. `dIè`: Where `d` is a digit. 4. `abc...xyz)Iè`: Where `[a,z]` are each compressed integers in the form of 1.2, 1.3, or 1.4. And we also use compression method 1.2 instead of hard-coded 1.1 integers, since we join everything together at the end. The third program type is used for the two sequences of the same integer. I could have also just used `0` instead, but the generator program would increase by more than it would save in that case. See sequences A4 and A12. The second program type is used for sequences that either start with a leading `0`, or contain negative values. Neither of which can be compressed by the 05AB1E base-conversion list compression I'm using. See sequences A1; A25; A30; A35; A36; A39; A45; A65; A71; A72; A76; A93; A94; A96; and A100. The fourth program type is used for if that method is shorter for the sequence than any of the other three program types. See sequences A11; A14; A18; A21; A22; A23; A24; A33; A42; A49; A50; A55; A58; A60; A63; A75; A78; A80; A81; A83; A84; A85; A87; A88; and A90. All other sequences use the default first program type. See sequences A2; A3; A5; A6; A7; A8; A9; A10; A13; A15; A16; A17; A19; A20; A26; A27; A28; A29; A31; A32; A34; A37; A38; A40; A41; A43; A44; A46; A47; A48; A51; A52; A53; A54; A56; A57; A59; A61; A62; A64; A66; A67; A68; A69; A70; A73; A74; A77; A79; A82; A86; A89; A91; A92; A95; A97; A98; and A99. [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) for a bit more in-depth information of how the compressed integers and compressed lists work. [Answer] ## Javascript (Node) 40 + 21058 = 21098 ``` z=>`i=>[${z.map(x=>x===+x+''?x:x+'n')}]` ``` Takes inputs as arrays of strings, outputs a program which outputs an array containing numbers and BigInts. ## Javascript (Node) 14 + 20852 = 20866 ``` z=>`i=>[${z}]` ``` It seems to be acceptable for the generated programs to return an array? ## Javascript (Node) 17 + 21152 = 21169 ``` z=>`i=>[${z}][i]` ``` I'm not sure I entirely understood the challenge? Given an array ([1,2,3]), it outputs: ``` i=>[1,2,3][i] ``` ]
[Question] [ In the description of this challenge, the following board will be used as a reference for positions: ``` ABC DEF GHI ``` For instance, in a game of ordinary tic-tac-toe, `B E A C G D F H I` describes the following: ``` -X- -X- XX- XXO XXO XXO XXO XXO XXO --- -O- -O- -O- -O- OO- OOX OOX OOX --- --- --- --- X-- X-- X-- XO- XOX ``` --- # Quantum Tic-Tac-Toe Gameplay In [quantum tic-tac-toe](https://en.wikipedia.org/wiki/Quantum_tic-tac-toe), players' moves are superpositions of moves in classical tic-tac-toe. Players mark two cells per move instead of just one, and those cells become *entangled*. Each quantum mark is given a subscript telling the number of the turn in which it was placed. [![single move](https://i.stack.imgur.com/KNhoc.png)](https://i.stack.imgur.com/KNhoc.png) In the above board, `A` and `B` are entangled, and so it is said that X made the move `AB`: `X1` is either in `A` or `B` but the true position cannot be known with certainty until later in the game. Consider the following board, made with the sequence `AB BE DE AE` (X makes the move `AB`, O makes the move `BE`, X makes the move `DE`, O makes the move `AE`; note that the relative positions of quantum marks in a cell in the image do not actually matter): [![triangle with dependencies](https://i.stack.imgur.com/jkZ5l.png)](https://i.stack.imgur.com/jkZ5l.png) Here, there has arisen a *cyclic entanglement* between cells `A`, `B` and `E`. Consider the following image, in which a line represents an entanglement: [![loop and line](https://i.stack.imgur.com/JS7rY.png)](https://i.stack.imgur.com/JS7rY.png) After a cyclic entanglement (which does not necessarily have length 3) is formed, *measurement* takes place, in which every quantum mark involved in the cycle collapses into a known state and becomes a *classical mark*. This includes entanglements like the red one above that are merely accessories to the cyclic entanglement, and don't actually complete the cycle. After one player forms a cyclic entanglement, the other player chooses which state the board assumes. Since X formed the cyclic entanglement, it is up to O to choose between these two states: [![state 1](https://i.stack.imgur.com/TrNeu.png)](https://i.stack.imgur.com/TrNeu.png) [![state 2](https://i.stack.imgur.com/biGMx.png)](https://i.stack.imgur.com/biGMx.png) There are only ever two possible states to choose from, because all individual entanglements only involve two cells. To record which state was chosen, the following methodology will be used: * Find the first cell (i.e. `A` takes precedence over `B`, etc) in the cyclic entanglement which cannot be removed without breaking the cycle (meaning entanglements like the red one above are excluded). In this case this is `A`. * Write the number of the mark that fills that cell. Since either `X1` or `O4` will occupy `A`, either `1` or `4` will be written. This would mean the above boards would be described by the sequences `AB BE DE AE 1` and `AB BE DE AE 4`, respectively. After measurement occurs, no more moves can be made in `A`, `B`, `D` or `E` because it is now known what lies in those cells. A single-cell entanglement, e.g. `AA 1`, is not allowed under ordinary circumstances, as that would mimic the behavior of a classical mark. This sort of move is only allowed when just one cell not occupied by a classical mark remains. A game continues until at least one tic-tac-toe is formed or until the board is filled with classical marks. Multiple tic-tac-toes can be made only if they appear simultaneously after a measurement; this is because the presence of one or multiple tic-tac-toes disallows the placement of any additional quantum marks. --- # Scoring The first number corresponds to X's score and the second to O's. * If neither player has a tic-tac-toe, then both players get zero points. * If there is only one tic-tac-toe present, then the player with the tic-tac-toe gets one point and the other player gets zero points. * If one player gets two tic-tac-toes after a measurement, then they get two points and the other player gets zero. It is not possible for one player to get one tic-tac-toe while the other gets two, nor is it possible for both players to get two, nor one player to get three. * If both players get a tic-tac-toe after a measurement, then the player with the least maximum subscript in their tic-tac-toe will get one point and the other player will get one half-point. For clarification on that last point, consider the board made by the sequence `AI EG BE EH DG AI 1 BC CE 3`: [![late game](https://i.stack.imgur.com/4OEUG.png)](https://i.stack.imgur.com/4OEUG.png) The maximum subscript in X's tic-tac-toe is seven, while the maximum subscript in O's tic-tac-toe is six. Because of this, O has the least maximum subscript and gets one point while X gets one half-point. --- # The Challenge Given a series of moves from a game of quantum tic-tac-toe, determine the score of each player. # Rules * Input and output may be given in whatever form is most convenient, but it must be explained if it differs from what is described above. Changes can be slight, like describing locations or scores differently, or more drastic. For instance, writing the number of the classical mark that fills the cell of the last quantum mark placed can be done instead of writing the number of the mark that fills the first cell alphabetically. * One must always be able to tell which score corresponds to which player. For instance, always putting the winner's score first is not acceptable unless the output also tells which player won or lost. If a specific player's score is always given first, that does not have to be included in the output (as seen in the test cases). * Assume only valid input is given. * Spaces are not necessary; they were added for the purpose of legibility. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the smallest program in bytes wins. --- # Test Cases ``` In: AB Out: 0 0 In: AI EG BE EH DG AI 1 BC CE 3 Out: 0.5 1 In: IA EG EB EH GD AI 1 CB CE 3 Out: 0.5 1 In: DE AB DE 1 AH CF CH CG BC 2 Out: 1 0.5 In: AE BF EI DH AI 1 Out: 1 0 In: CE BD EG FH CG 1 Out: 1 0 In: AB AD BC CF AC 5 Out: 1 0 In: AB BE BC CE 2 DG HI DF HI 6 Out: 0 1 In: BC BE CF EF 1 AD AG GH DG 6 II 9 Out: 0 0 In: DI AE AB BF EH AH 2 DI 7 CG CG 8 Out: 0 0 In: AD BH EF CI EF 3 HI DG BI 2 AG 1 Out: 2 0 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~419~~ ~~371~~ 351 bytes *-48 bytes following suggestions from @ovs* *-16 bytes thanks to @JBernardo* ``` def s(C,l=[]): l=l+[p:=C.pop(0)] if 0==p*0: del l[~1];r=[p] while r:c=r.pop();l=[r.append(t:=sum(e)-c)or t if e*0!=0and c in e else e for e in l] if C:s(C,l) else:w=[a:=[sum(z.count(j)>2for z in[*zip(*[[k//3,k%3,k%4,6559>>2*k&3]for k in l[i:f+1:2]if 0==k*0])]for j in set(z))for i in[0,1]]for f in range(9)];a[[1,0]in w]/=1+([1,1]==a);print(a) ``` [Try it online!](https://tio.run/##jZPNcpswEMfvPMX2kA7C1BbfBI988WNodGCwSAgUa4CMpz701V0tiICdptOD0ezXb3f/ltSv4fXcBqnqbreTLKG3j27DuCCZBQ1rNlxl7LhVZ2VTIiyoSqCMKYfqMJxkAw3/7Yl9x7jSUbi8Vo2ELitYN9aQvWZ121wp2Z7sIWP9@09bkh8FOXcwIE069BujeXuCAqoWJMim1x8odYJETzN1PWbjZMQaE7IL43nGOOKu2@L83g72Gzn4WHXVVdy5Vsp2OK93u8Ctn/AXunEUPR8OvlN/DwRm1iOfV1m58TJfTLvVDhVkDL9huJeDfSUE7QrB1PXEGC0x2uXti7SfidjnnHsuFdp3ETvmbWxteoKxnOxVV@nxcnIr8l72wIBrpQC4ZoGGuYuVChd46EKMp@dCaOwEz8D4TV46pfjo8qfU8IOlg3TNCrHTihW7EDywfJPyiRWYOahJMHY4uRJTE5lztucVcD5vvaNnWIG4XyAyfrTpp4JZjMeNV7okRr/AsIydfrDm2pk1Nw2nM1rNRQ0zvtdemyjtPTYwfemDTt6CT8QiVjLhsCRYSWXOeL35LFGymhIT04epV5vPss//Kv0L1v/PW4Z5/oLDze9vRryMQr9gUaPiP26ssCx8T/g48EmNjyQbO/Q2GsS6/QE "Python 3.8 (pre-release) – Try It Online") Takes input with `A-I` translated to `0-8` in tuples. The collapse choice is represented by the cell the last entanglement collapses to. ### Massive Explanation ``` # Take input C # I(k) <==> move k is a collapse, not entanglement <==> 'imag'in dir(k) <==> isinstance(k,int) <==> hasattr(k,'imag') # I have a feeling that collapses vs entanglements can be encoded in a much more byte-efficient manner I=lambda k:'imag'in dir(k) # C: list of moves, where a pair entry (e.g. [0,1]) is entanglement (e.g 0-1). # and an int entry (e.g 1) states collapse of the last entry, (e.g. [0,1] collapsed to 1) # l: be the list of entangled/collapsed states, built up with recursion # pair (e.g. [0,1]) represents an existing entanglement, and int (e.g. 1) represents collapsed state # the owners alternate XOXOXO in the list def s(C,l=[]): l=l[:] # clone l for array operations if C: # deal with end condition: only recurse if C has any mvoes l+=[ # append the first move in C to l p:=C[0] # assign p to be the first move ] if I(p): # if that move is an int, collapse: del l[~1]; # delete the entangled move before r=[p] # r will be the list of location to remove # start by adding p to r: no entanglement can have the location p anymore # I have a feeling this whole while loop can be replaced with a recursive method while r: # while there is still a location to remove: c=r.pop() # take c to be the first location, so we will collapse all states that contain c for i,e in enumerate(l): # for each state e of l: if (1-I(e) # If it is not a collapsed state and c in e): # and it contains c r+=[ # add to r: sum(l[i])-c # the location besides e of c ]; l[i]=r[~0] # replace e with that collapsed location s(C[1:],l) # recurse without the first move and with the modified l else: # end condition: all moves have been processed # for case 5 (begins [[0, 1], [1, 4]...), # l=[0, 1, 2, 4, [3, 6], 7, [3, 5], 8] (most states are collapsed, except for [3,6] and [3,5]) w=[ # w will be a list, supposing everything is collapsed as soon as it is intered, # of how many 3-in-a-rows each player has after each move a:= # this is a for loop, so `a` gets set to the *last* 3-in-a-row count (the final win state) [ sum( # take the sum of: z.count(j)>2 # the number of directions that have exactly 3 (more than 2) identical entries for z in # for each of the 3 directions (rows, cols, diags) in [*zip(*[ # the transpose: [ k//3, # floor divide maps items on each row to the same value k%3, # mod 3 maps items in the same column to the same value k%4 # mod 4 maps items on the main diagonal to 0 6559>>2*k&3 # k on antidiagonal to 0; 0,1,7,8 to negative; 3,5 to 1 # (k in[2,4,6] doesn't work because it also maps all of 0,1,3,5,7,8 to False) ] for k in l[i:f+1:2] # i=0: every even state; i=1: every odd state # states limited to from the first f moves if I(k) # only consider the state if it is collapsed ] )] for j in set(z) # take the count for each unique value in the direction ) for i in[0,1] # do this for both player i=0=X and player i=1=O) ] for f in range(9) # for each count f of moves from 0 moves to 8 moves, calculate the 3-in-a-row count ] # now a should be [0,0],[1,0],[2,0],[1,1] or the opposite order if[1,1]==a: # [1,1] is the only case we have to special handle a[[1,0]in w]*=.5 # subtract .5 from the second element (O's score) if X got the point first, otherwise subtract from X's score print(a) # finally ``` ]
[Question] [ ## Background Suppose that there are `2*n` people to be married, and suppose further that each person is attracted to exactly `n` other people under the constraints that: 1. Attraction is [*symmetric*](https://en.wikipedia.org/wiki/Symmetric_relation); i.e. if person `A` is attracted to person `B`, then person `B` is attracted to person `A`. 2. Attraction is [*antitransitive*](https://en.wikipedia.org/wiki/Intransitivity#Antitransitivity); i.e. if person `A` and person `B` are each attracted to person `C`, then person `A` and person `B` are not attracted to each other. Thus the network of attractions forms the (undirected) [complete bipartite graph](https://en.wikipedia.org/wiki/Complete_bipartite_graph) `Kn,n`. We also assume that each person has ranked the people they are attracted to. These may be represented as edge weights in the graph. A *marriage* is a pairing `(A,B)` where `A` and `B` are attracted to each other. The marriage is *unstable* if there is another marriage where one person from each marriage could divorce their partner and marry each other and both end up with someone they ranked higher than their former partner. ## Goal Your task is to write a complete program or function which takes each person's preferences as input and outputs a marriage for each person such that each marriage is stable. ## Input Input may be in any convenient format; e.g., weighted graph, ordered list of preferences, dictionary/assocation, etc. You may optionally take the total number of people as input, but no other input is allowed. ## Output Output can also be in any convenient format; e.g. list of tuples, minimal [edge cover](https://en.wikipedia.org/wiki/Edge_cover), a function which associates to each person their partner, etc. Note that the only constraint is that each marriage is stable, there are no other optimality requirements. ## Notes 1. You can find more information and an `O(n^2)` algorithm to solve this problem on [Wikipedia](https://en.wikipedia.org/wiki/Stable_marriage_problem) or this [Numberphile video](https://www.youtube.com/watch?v=Qcv1IqHWAzg). You are free to use any algorithm, however. 2. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. 3. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer (in bytes) wins. [Answer] ## Mathematica, 28 bytes On would think, this is cheating. I for myself like this: ``` Combinatorica`StableMarriage ``` * Needs to be called with the weight matrices of the preferences for men and women. * Returns the direct indizes for the coupling. (Yes `Combinatorica` is deprecated but it costs fewer bytes than `FindIndependentEdgeSet`) --- **Example (GoT-like):** (To be fair - i guessed the weights...but i'm okay with the results) [![enter image description here](https://i.stack.imgur.com/S750X.png)](https://i.stack.imgur.com/S750X.png) ``` m = {{2, 4, 3, 1}, {1, 2, 4, 3}, {3, 2, 1, 4}, {4, 2, 1, 3}}; w = {{2, 3, 4, 1}, {3, 2, 1, 4}, {3, 2, 4, 1}, {4, 1, 2, 3}}; result = Combinatorica`StableMarriage[w, m]; MapThread[ UndirectedEdge[Show[#1, ImageSize -> 130], Show[#2, ImageSize -> 130]] &, {names1, names2[[result]]}] // TableForm ``` [![Blockquote](https://i.stack.imgur.com/izkIb.png)](https://i.stack.imgur.com/izkIb.png) ]
[Question] [ [![Three dice in a clear cube](https://i.stack.imgur.com/uB3Aa.png)](https://www.youtube.com/watch?v=xHh0ui5mi_E) **Given three dice rolls** (integer values from 1-6) in sorted order (so as to be indistinguishable), **convert them to the sum of two fair dice** with an identical distribution. The answer for three to one is summing them all, modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die). It's easy to do this for three-to-one, by summing them all modulo 6. The end-result is a perfectly flat distribution, where each of the six numbers are equally likely (just like a single die). Your challenge is to do the same for three-to-two. Inspired by [standupmath's The Three Indistinguishable Dice Puzzle](https://www.youtube.com/watch?v=xHh0ui5mi_E). A follow-up ["solution" video](https://www.youtube.com/watch?v=hBBftD7gq7Y) was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. `:D` ## Instructions Write a program or function that accepts three **sorted** integers/digits, 1-6, and outputs or returns a single integer, 2-12, such that, for the 216 possible inputs, the outputs are distributed as: ``` 222222 333333333333 444444444444444444 555555555555555555555555 666666666666666666666666666666 777777777777777777777777777777777777 888888888888888888888888888888 999999999999999999999999 AAAAAAAAAAAAAAAAAA BBBBBBBBBBBB CCCCCC ``` (I've used hex to keep to single characters; decimal output is fine) **Because the dice are indistinguishable, there is no intrinsic order to them, hence the sorted input. You cannot simply "drop the third" because that would be ambiguous.** ## Details * Score is the length of the program in bytes * The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent. * No "rerolling" by getting entropy from another source ## Example (and test) Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (6³) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases `1, 2, 3` and `3, 2, 1`, ... are presumed indistinguishable and are (arbitrarily) converted to `1, 2, 3`). An example answer (extremely brute-force and inefficient) and test suite is provided below in Python. Hopefully the test bits are clear enough to port to your language of choice, though doing stdin/stdout would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful). ``` # 6x6 lists of numbers with digits sorted LUT = [ [[124], [133, 166], [346], [223, 355], [256], [115, 445]], [[233, 266], [125], [224, 455], [134], [116, 446], [356]], [[126], [111, 333, 555, 225], [234], [144, 366], [456], [135]], [[112, 244], [235], [334, 466], [145], [226, 556], [136]], [[146], [122, 155], [236], [113, 344], [245], [335, 566]], [[246], [123], [114, 336], [345], [222, 444, 666, 255], [156]], ] def three2two(rolls): look_for = int('{}{}{}'.format(*sorted(rolls))) for i in range(6): for j in range(6): if look_for in LUT[i][j]: return i + j + 2 # fair distribution of the sum of two dice multiplied by 6 (because each should be hit 6x) expected_counts = { 2: 6, 12: 6, 3: 12, 11: 12, 4: 18, 10: 18, 5: 24, 9: 24, 6: 30, 8: 30, 7: 36, } d = [1, 2, 3, 4, 5, 6] for i in d: for j in d: for k in d: ijk = sorted([i, j, k]) result = three2two(ijk) expected_counts[result] -= 1 for key in expected_counts: assert expected_counts[key] == 0 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 6ṗ3Ṣ€ṢðQ€L€Ụịḷi’:6d6‘S ``` [Try it online!](http://jelly.tryitonline.net/#code=NuG5lzPhuaLigqzhuaLDsMSg4oKs4buk4buL4bi3aeKAmTo2ZDbigJhT&input=&args=WzEsIDMsIDVd) or [simulate all 216 outcomes](http://jelly.tryitonline.net/#code=NuG5lzPhuaLigqzhuaLDsMSg4oKs4buk4buL4bi3aeKAmTo2ZDbigJhTCjbhuZcz4bmi4oKsw4figqzhuaJzNkc&input=). ### Background We map each unordered triplet of dice rolls (listed with respective multiplicities) to an ordered pair of dice rolls in the following fashion: ``` [1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3] -> [1,1] [1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4] -> [1,2] [1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5],[1,2,5] -> [1,3] [1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6],[1,2,6] -> [1,4] [1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4],[1,3,4] -> [1,5] [1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5],[1,3,5] -> [1,6] [1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6],[1,3,6] -> [2,1] [1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5],[1,4,5] -> [2,2] [1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6],[1,4,6] -> [2,3] [1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6],[1,5,6] -> [2,4] [2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4],[2,3,4] -> [2,5] [2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5],[2,3,5] -> [2,6] [2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6],[2,3,6] -> [3,1] [2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5],[2,4,5] -> [3,2] [2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6],[2,4,6] -> [3,3] [2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6],[2,5,6] -> [3,4] [3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5],[3,4,5] -> [3,5] [3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6],[3,4,6] -> [3,6] [3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6],[3,5,6] -> [4,1] [4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6],[4,5,6] -> [4,2] [1,2,2],[1,2,2],[1,2,2],[1,3,3],[1,3,3],[1,3,3] -> [4,3] [1,4,4],[1,4,4],[1,4,4],[1,5,5],[1,5,5],[1,5,5] -> [4,4] [1,6,6],[1,6,6],[1,6,6],[2,3,3],[2,3,3],[2,3,3] -> [4,5] [2,4,4],[2,4,4],[2,4,4],[2,5,5],[2,5,5],[2,5,5] -> [4,6] [2,6,6],[2,6,6],[2,6,6],[3,4,4],[3,4,4],[3,4,4] -> [5,1] [3,5,5],[3,5,5],[3,5,5],[3,6,6],[3,6,6],[3,6,6] -> [5,2] [4,5,5],[4,5,5],[4,5,5],[4,6,6],[4,6,6],[4,6,6] -> [5,3] [5,6,6],[5,6,6],[5,6,6],[1,1,2],[1,1,2],[1,1,2] -> [5,4] [1,1,3],[1,1,3],[1,1,3],[1,1,4],[1,1,4],[1,1,4] -> [5,5] [1,1,5],[1,1,5],[1,1,5],[1,1,6],[1,1,6],[1,1,6] -> [5,6] [2,2,3],[2,2,3],[2,2,3],[2,2,4],[2,2,4],[2,2,4] -> [6,1] [2,2,5],[2,2,5],[2,2,5],[2,2,6],[2,2,6],[2,2,6] -> [6,2] [3,3,4],[3,3,4],[3,3,4],[3,3,5],[3,3,5],[3,3,5] -> [6,3] [3,3,6],[3,3,6],[3,3,6],[4,4,5],[4,4,5],[4,4,5] -> [6,4] [4,4,6],[4,4,6],[4,4,6],[5,5,6],[5,5,6],[5,5,6] -> [6,5] [1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[6,6,6] -> [6,6] ``` This makes all outcomes equiprobable. ### How it works ``` 6ṗ3Ṣ€ṢðĠ€Ụịḷi’:6d6‘S Main link. Argument: D (three dice rolls, sorted) 6ṗ3 Generate lists of length 3 over [1, 2, 3, 4, 5, 6]. Ṣ€ Sort each triplet. Ṣ Sort the list of triplets. ð Begin a new, dyadic chain. Arguments: A (list of triplets), D Ġ€ Group each; group the indices of each triplet by the the corresponding values. For a triplet [a, b, c], this yields: [[1], [2], [3]] if a < b < c [[1], [2, 3]] if a < b = c [[1, 2], [3]] if a = b < c [[1, 2, 3]] if a = b = c Ụ Grade up; sort the indices of A by those 2D lists. ịḷ Retrieve the elements of A at those indices. This sorts A as in the previous section. i Find the (1-based) index of D. ’ Decrement to get the 0-based index. :6 Divide the index by 6, rounding down. d6 Divmod; return quotient and remainder of division by 6. ‘ Increment to map [0, ..., 5] to [1, ..., 6]. S Sum the results. ``` [Answer] # CJam, ~~25~~ 24 bytes ``` 6Zm*{$e`z}$q~:(a#6bW2t1b ``` This is a port of [my Jelly answer](https://codegolf.stackexchange.com/a/80223). [Try it online!](http://cjam.tryitonline.net/#code=NlptKnskZWB6fSRxfjooYSM2YlcydDFi&input=WzEgMyA1XQ) or [simulate all 216 outcomes](http://cjam.tryitonline.net/#code=NlptKjokOjopOmAKW3sKICAgIDZabSp7JGVgen0kUX46KGEjNmJXMnQxYgp9ZlFdCiQ2Lzpw&input=). *Thanks to @jimmy23013 for golfing off 1 byte!* [Answer] # Pyth, ~~41~~ 27 bytes ``` JSSM^S6 3+2sPtj+216xo/JNJQ6 ``` [10 random testcases](http://pyth.herokuapp.com/?code=JSSM%5ES6+3%2B2sPtj%2B216xo%2FJNJQ6&test_suite=1&test_suite_input=[1%2C+1%2C+2]%0A[2%2C+2%2C+4]%0A[2%2C+5%2C+5]%0A[3%2C+3%2C+5]%0A[3%2C+4%2C+6]%0A[3%2C+5%2C+6]%0A[4%2C+4%2C+5]%0A[4%2C+5%2C+6]%0A[4%2C+6%2C+6]%0A[6%2C+6%2C+6]&debug=0) [Confirmation of validity.](http://pyth.herokuapp.com/?code=JSSM%5ES6+3L%2B2sPtj%2B216xo%2FJNJb6jcSyMSM%5ES6+3+6&debug=0) ### Conversion table: ``` 2: [111, 222, 333, 444, 555, 666] 3: [112, 113, 223, 224] 4: [114, 115, 225, 226, 355, 366] 5: [116, 122, 125, 233, 244, 445, 446] 6: [126, 133, 144, 146, 255, 266, 455, 466] 7: [134, 155, 156, 166, 246, 334, 335, 556, 566] 8: [123, 135, 234, 256, 336, 344] 9: [124, 136, 235, 345] 10: [145, 236, 346] 11: [245, 356] 12: [456] ``` ## Previous 41-byte solution: I need to golf this... ``` JSM^S6 3+2f/@co,/JNNJ.u+NY*R6t+S5_S6 6TQ0 ``` [Try it online!](http://pyth.herokuapp.com/?code=JSM%5ES6+3%2B2f%2F%40co%2C%2FJNNJ.u%2BNY%2aR6t%2BS5_S6+6TQ0&input=%5B1%2C1%2C1%5D&debug=0) ### Conversion table: ``` 2: [111, 222, 333, 444, 555, 666] 3: [112, 113, 114, 115] 4: [116, 122, 133, 144, 155, 166] 5: [223, 224, 225, 226, 233, 244, 255, 266] 6: [334, 335, 336, 344, 355, 366, 445, 446, 455, 466] 7: [556, 566, 123, 124, 125, 126, 134] 8: [135, 136, 145, 146, 156] 9: [234, 235, 236, 245] 10: [246, 256, 345] 11: [346, 356] 12: [456] ``` [Answer] # CJam, 37 35 bytes Probably not golfed well. ~~But beat Pyth.~~ ``` 8aq~\;[_2$>8+@7+@:U2+1$([8U4$7]])er ``` [Try it here.](http://cjam.aditsu.net/#code=6%2C%3A%293m*%3A%24%7BS*s%3AQ%3B%0A%0A8aQ%7E%5C%3B%5B_2%24%3E8%2B%407%2B%40%3AU2%2B1%24(%5B8U4%247%5D%5D)er%0A%0As%7E%7D%25%24e%60p) ]
[Question] [ This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). In this challenge, we will be writing programs/functions that solve "[Knights and Knaves](https://en.wikipedia.org/wiki/Knights_and_Knaves)" puzzles. **Background** You find yourself on an island ... etc. ... every person on the island except for you is either a *knight* or a *knave*. Knights can only make **true** statements. Knaves can only make **false** statements. I don't want to rigorously define "statement," but we will say a statement is anything which is either "true" or "false." Note that this excludes paradoxical sentences. For the purposes of this challenge, you will be coming across groups of islanders; they will make statements to you. **Your task is to determine who is a Knight and who is a Knave.** **Input:** You will be given (in any reasonable format) the following information: * A list of the people present. They will be named with uppercase alphabet characters "A-Z". The limit on the number of people imposed by this will not be exceeded. * The statements that each person makes. See below for important details about this. **Output** You will then output (in any reasonable format) what each person is. For example, if there were players `A B C D` and `A` is a knight, but the rest are knaves, you could output ``` A: 1 B: 0 C: 0 D: 0 ``` **Important details:** * Uppercase alphabet characters A-Z refer to islanders. * The characters `0` (zero) and `1` (one) refer to a "Knave" and a "Knight", respectively. (You can any other two non A-Z characters, as long as you specify) * Each islander present may make any natural number of statements, or may choose to say nothing. * The normal **logical operators** can be used in statements (**IS\*, AND, OR, NOT**). On top of this, **De Morgan's Laws** and **Conditionals** may be used. The following are examples of how they might be presented in a spoken puzzle followed by how they might be input into your program. (\* on a more technical note. The "IS" operator is really used as containment (which isn't a logical operator). When I say "A is a Knight", I really mean "A is a member of the set of Knights". The true operator used would be 'ϵ'. For simplicity's sake, we will instead be using '='.) I use the following (you may use whatever, as long as it is reasonable and consistent): * `^` AND * `v` OR * `=` IS * `~` NOT * `=>` IMPLIES * `X:` Person *X* claims that... Person *Z* could make any combination of any of the following types of statements: Person *Z* says that... 1. Person *A* is a Knight. `Z: A = 1` 2. Person *Q* is a Knave. `Z: Q = 0` 3. I am a Knight. `Z: Z = 1` 4. Person *A* is a Knight OR Person *B* is a Knight. `Z: ( A = 1 ) v ( B = 1)` 5. Person *C* is a Knight AND I am a Knave. `Z: ( C = 1 ) ^ ( Z = 0 )` 6. Person *R* is NOT a Knight. `Z: ~( R = 1 )` On top of this, input may also use De Morgan's Laws 7. It is NOT True that both person A and Person B are Knaves `Z: ~( ( A = 0 ) ^ ( B = 0 ) )` 8. It is False that either person A or person B is a Knight `Z: ~( ( A = 1 ) v ( B = 1) )` Finally, conditionals and their negations may be used 9. If I am a Knight, then person B is a Knave `Z: ( Z = 1 ) => ( B = 0 )` 10. It is NOT True that If person B is a Knight, Then Person C is a Knave. `Z: ~( ( B = 1 ) => ( C = 0 ) )` **Notes on conditionals** Check out [wikipedia](https://en.wikipedia.org/wiki/Material_implication_%28rule_of_inference%29) for more info. A conditional statement takes the form *p* => *q*, where *p* and *q* are themselves statements. *p* is the "antecedent " and *q* is the "consequent". Here is some useful info * The negation of a condition looks like this: ~( p => q ) is equivalent to p ^ ~q * A false premise implies anything. That is: if *p* is false, then any statement *p* => *q* is true, regardless of what *q* is. For example: "if 2+2=5 then I am Spiderman" is a true statement. **Some simple test cases** These cases are given in the following fashion (1) how we would pose the problem in speech (2) how we might pose it to the computer (3) the correct output that the computer might give. 1. Person A and Person B approach you on the road and make the following statements: A: B is a knave or I am a knight. B: A is a knight. Answer: > > B is a Knight and A is a Knight. > > > Input: ``` A B # Cast of Characters A: ( B = 0 ) v ( A = 1) B: A = 1 ``` Output: > > > ``` > > A = 1 > B = 1 > > ``` > > > > 2. Persons A, B, and F approach you on the road and make the following statements: A: If I am a Knight, then B is a Knave. B: If that is true, then F is a Knave too. Answer: > > A is a Knight, B is a Knave, F is a Knight. > > > Input ``` A B F A: ( A = 1 ) => ( B = 0 ) B: ( A = 1 ) => ( F = 0 ) ``` Output: > > > ``` > > A = 1 > B = 0 > F = 1 > > ``` > > > > 3. Q, X, and W approach you on the road and make the following statements: W: It is not true that both Q and X are Knights. Q: That is true. X: If what W says is true, then what Q says is false. Answer: > > W and Q are Knights. X is a Knave. > > > Input ``` Q X W W: ~( ( Q = 1 ) ^ ( X = 1 ) ) Q: W = 1 X: ( W = 1 ) => ( Q = 0 ) ``` Output > > > ``` > > W = 1 > Q = 1 > X = 0 > > ``` > > > > *There is a [similar challenge](https://codegolf.stackexchange.com/questions/5419/code-golf-solve-a-knights-and-knaves-logic-problem-by-parsing-english) from 3 years ago that focuses on parsing and does not contain conditionals or De Morgan's. And therefore, I would argue, is different enough in focus and implementation to avoid this being a dupe.* *This challenge was briefly closed as a dupe. It has since been reopened.* *I claim that this challenge is, first off, different in focus. The other challenge focuses on English parsing, this does not. Second it uses only AND and OR whereas this uses conditionals and allows for the solving of many more puzzles. At the end of the day, the question is whether or not answers from that challenge can be trivially substituted to this one, and I believe that the inclusion of conditionals and conditional negations adds sufficient complexity that more robust changes would need to be made in order to fit this challenge.* [Answer] # Python 3, ~~450~~ ~~342~~ 307 bytes Edit: it turns out I forgot an import... My first solution takes advantage of having flexible naming for queries ``` from functools import* def g(c,r):c=c.split();l,y=len(c),range;d=[dict((c[i],n>>i&1)for i in y(l))for n in y(2**l)];return[n[1]for n in[[eval(reduce(lambda x,y:x.replace(y,str(d[i][y])),d[i],')and '.join(['not',''][d[i][s[0]]]+'('+s[2:].replace('->','<1or')for s in r)+')')),d[i]]for i in y(len(d))]if n[0]] ``` You can call the above one with ``` g('Q X W', ['W: not( ( Q == 1 ) and ( X == 1 ) )','Q: W == 1', 'X: ( W == 1 ) -> ( Q == 0 )']) ``` The next one here uses the same format of queries as seen in the OP, it also doesn't have some of the modifications I made to the first one. It is 417 bytes because it converts between the two formats. ``` from functools import* def g(c,r):c=c.split();l,y=len(c),range;d=[{**dict((c[i],n>>i&1)for i in y(l)),**{'v':'or','^':'and','=':'==','~':'not'}}for n in y(2**l)];f=lambda r,c:reduce(lambda x,y:x.replace(y,str(c[y])),c,('(0<1'+''.join([')^ '+['~',''][c[t[0]]]+'('+t[1]for t in[s.split(":")for s in r]])+')').replace('=>','<1or'));return[dict((o,j) for o,j in n[0].items() if o in c) for n in[[d[i],eval(f(r,d[i]))]for i in y(len(d))]if n[1]] ``` And it can be called by: ``` g('Q X W', ['W: ~( ( Q = 1 ) ^ ( X = 1 ) )','Q: W = 1', 'X: ( W = 1 ) => ( Q = 0 )']) ``` They both return ``` [{'X': 0, 'W': 1, 'Q': 1}] ``` Ungolfed Explanation: ``` from functools import * def knight_and_knaves(cast,rules): # turns 'A B C' into ['A','B','C'] cast = cast.split() # gets all numbers that can fit in len(cast) bits bitmasks = range(2 ** len(cast)) # for every bitmask, apply the value for a bit to the boolean value for each cast member. # This returns a dictionary of all possible outcomes. d=[dict((cast[i], n>>i & 1) for i in range(len(cast))) for n in bitmasks] # Split rules at colon rules = [s.split(":")for s in rules] # Turns list of rules into one python expression, joins each rule with ')and ', maybe a 'not' depending on if the hypothesis has the rule as a lie, and '('. # Also replaces '->' with '<1or' which is equivalent to it. Also starts with '(True' and ends with ')' to resolve missing parentheses transform_rules = lambda d, rules: ('(True' + ''.join([')and ' + ['not', ''][d[rule[0]]] + '(' + rule[1].replace('->','<1or') for rule in rules]) + ')') # Applys transform_rules on each outcome and evaluates the result, storing it into a list of lists where each element is [outcome, value] outcomes=[[d[i],eval(reduce(lambda x,y:x.replace(y,str(d[i][y])),d[i],transform_rules(d[i], rules)))] for i in range(len(d))] # Filters outcomes if value is True return[n[0]for n in outcomes if n[1]] ``` Also, the second solution needs 3.5 (not 3.4) due to the use of [PEP 448](https://www.python.org/dev/peps/pep-0448/) [Answer] # Mathematica, 80 bytes ``` F[c_,s_]:=Select[Thread[c->#]&/@{True,False}~Tuples~Length@c,And@@Equal@@@s/.#&] ``` --- **Explanation** The function `F` takes two arguments, * `c` is a list of all characters' names, * `s` is a list of statements, each of which contains two parts - who says what. For example, there are three characters, Q, X and W. ``` characters={q,x,w}; ``` And they say, ``` statements= {{w, !((q==True)&&(x==True)) }, {q, w==True }, {x, Implies[w==True,q==False] }}; ``` where `True` and `False` means Knights and Knaves respectively. Then ``` F[characters, statements] ``` will give `{{q->True, x->False, w->True}}`, which means there is only one solution that Q and W are Knights while X is a Knave. If there are more than one solution, the output will look like `{{...},{...},...}` --- The algorithm is very simple. `{True,False}~Tuples~Length@c` gives all possible combinations of Knights and Knaves among the characters. Then `Thread[c->#]&/@` construct an array of rules based on these combinations. In the case of two characters A and B, the array will be ``` {{a->True, b->True }, {a->True, b->False}, {a->False,b->True }, {a->False,b->False}} ``` Substituting the statements with one row of these rules, we will get an array looks like ``` {{True,True},{True,False},{False,False}} ``` The first column of this array is the identities of the speakers, and the second column indicates whether their statements are true or false. A valid solution requires the accordance between speakers' identities and their statements. The array above means that this combination is not a solution, since the second speaker, a Knight, makes an incorrect statement. ``` Select[...,And@@Equal@@@s/.#&] ``` does the substitutions and select those combinations that satisfy the condition. [Answer] ## Ruby, 128 This is the same algorithm as everyone else, try all possible combinations of knaves and knights and see which sticks. I have another that I'm working on, but I think it'll be longer (though more interesting). The statement inputs must be: * `&` AND * `|` OR * `==` IS * `!` NOT * `>` IMPLIES * `X:` Person X claims that... I also require each statement and sub-statement to be in parentheses. The only problem with this version is that it goes through at most 2^26 iterations, and if they're not all knaves, **at least 2^(26-n) iterations**! To put that in perspective, that means that if there are two people, and at least one is not a knave, it will take **a minimum of 16,777,216 iterations**! To limit that, I submit the following at 168 bytes. Sub in `26` for `#{o.size}` to cut it back to 161. ``` ->s{o=s[/.*?$/].split i=0 eval h=o.zip(("%0#{o.size}b"%i+=1).chars).map{|k|k*?=}*?;until h&&o.all?{|t|!s[/#{t}:(.*)$/]||eval("(#{t}<1)^(#{$1.gsub(?>,'!=true||')})")} h} ``` But if I can instead use an array of people and a map of statements e.g.: ``` c[[?A, ?B], { ?A=> "( B == 0 ) | ( A == 1)", ?B=> "A == 1" } ] ``` Then I get it down to 128. ``` ->o,s{i=0 eval h=o.zip(("%026b"%i+=1).chars).map{|k|k*?=}*?;until h&&s.all?{|t,k|eval("(#{t}<1)^(#{k.gsub(?>,'!=true||')})")} h} ``` ]
[Question] [ There are *n* boxes, numbered *1-n*. Each box is locked, such that it can be opened by only one corresponding type of key (also numbered *1-n*). These keys are randomly scattered in the boxes (one box may have any number of keys, one key may have any number of duplicates), and then all boxes are shut. A treasure (numbered *0*) has also been locked in many of the boxes. You have hired a locksmith to retrieve all the treasure. He charges for each box he cracks open. There is no charge for opening a box for which the key is already available. Input is the contents of each box. You can decide the format of the input. **Output the minimum cost required to get the treasures.** *Notes* 1. Your algorithm may take a long time, but that is irrelevant. 2. Shortest code wins. 3. No need to bother about invalid input. **Sample data** Here line *i* represents the keys present in box *i*. Input ``` 2 0 3 4 0 5 6 0 6 0 ``` Output ``` 1 ``` Input ``` 2 0 3 0 4 0 6 5 0 ``` Output ``` 3 ``` Input ``` 2 4 0 3 0 1 0 6 5 0 ``` Output ``` 2 ``` Input ``` 1 3 4 2 6 5 ``` Output ``` 0 ``` [Answer] # CJam, ~~59~~ ~~52~~ ~~50~~ ~~49~~ ~~45~~ ~~43~~ 42 bytes ``` qN/ee::~e!{_0+{0a&}#>W%_{1$|(z@-},,\;}%:e< ``` *Thanks to @MartinBüttner for golfing off 3 bytes and paving the way for 4 more!* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2Fee%3A%3A~e!%7B_0%2B%7B0a%26%7D%23%3EW%25_%7B1%24%7C(z%40-%7D%2C%2C%5C%3B%7D%25%3Ae%3C&input=2%200%0A3%0A4%200%0A5%206%200%0A6%0A0). ### How it works ``` qN/ e# Read all input and split it at linefeeds. ee e# Enumerate the lines. e# STACK: [[0 "i0 i1 ..."] [1 "j0 j1 ..."] ...] ::~ e# Apply ~ (bitwise NOT/evaluate) to each item of the pairs. e# STACK: [[-1 i0 i1 ...] [-2 j0 j1 ...] ...] e! e# Push all unique permutations of the resulting array. { e# For each permutation: _0+ e# Push a copy and append 0 to it. {0a&}# e# Find the first index of an element that contains 0. > e# Discard all previous elements of the array. W% e# Reverse the resulting array. e# We now have a (partial) permutation that contains e# all treasures and ends with a treasure. _ e# Push a copy. The original (which contains lists, but no numbers) will serve as accumulator. { e# Filter; for each list in the array: 1$| e# Push a copy of the accumulator and perform set union. ( e# Shift out the first element (bitwise NOT of 0-based index). z e# Apply absolute value to push the 1-based index. @- e# Perform set difference with the former state of the e# accumulator. This pushes an empty list iff the 1-based e# index was already in the accumulator, i.e., iff we already e# had a key. }, e# Keep the element if we did not have the key. , e# Count the kept elements. \; e# Discard the accumulator from the stack. }% e# :e< e# Get the minimum of all results. ``` [Answer] ## CJam (53 bytes) ``` Nq+N/:a::~:A,_m*_.&{,}$_{{_Af=e_|}:PA,*A,,^0-P0&!}#=, ``` This is rather too slow for the online interpreter. ### Dissection ``` Nq+N/:a::~:A e# Parse the input into arrays and store in A ,_m*_.& e# Generate (with duplicates) a powerset of [0 1 ... n] {,}$ e# Sort by size _{ e# Create a copy and search for first index satisfying... {_Af=e_|}:P e# Store in P a block which does a reachability expansion A,* e# Apply it n times (no path can be longer than n) A,,^0- e# Invert to get the unreached nodes (except 0) P e# Apply P again to see what's reached from the unreached nodes 0&! e# Check that it doesn't include [0] }# =, e# Look up the powerset element at that index and find length ``` [Answer] # Haskell, 173 bytes `l` is the one you wanna call. Not sure whether I shouldn't use a pseudo-`Map` instead (`[(Int,[Int])]` instead of `[[Int]]`). ``` l=o[].map(map read).map words.lines o[]b|0`notElem`concat b=0|0<1=1+minimum[o[n]b|n<-[1..length b],b!!(n-1)/=[]] o(n:k)b=o(filter(/=0)(k++b!!(n-1)))(take(n-1)b++[]:drop n b) ``` ]
[Question] [ Write, in as few **characters** as possible, a program that takes zero or six command-line arguments ``` menorah menorah YEAR MONTH DAY HOUR MINUTE SECOND ``` (Both forms must be supported. The zero-argument version shall be equivalent to calling the six-argument version with the *current* system date and time in the local timezone.) and if the specified (Gregorian-calendar) date and time falls during [Hanukkah](https://en.wikipedia.org/wiki/Hanukkah), then output an ASCII art (or Unicode art) nine-branch menorah with the appropriate number of candles lit. If it is *not* during Hanukkah, then output a single newline. For example, ``` ~$ ./menorah 2015 12 7 0 0 0 * | * | | | | +++++++++ | -+- ~$ ./menorah 2015 12 9 0 0 0 * | *** | ||| | ||| +++++++++ | -+- ~$ ./menorah 2015 12 14 0 0 0 * ****|**** ||||||||| ||||||||| +++++++++ | -+- ~$ ./menorah 2015 12 15 0 0 0 ~$ ``` On the Nth day of the festival, N+1 candles are lit: The central *shamash* candle, and N of the 8 Hanukkah candles, placed in right-to-left order. Allowed variations in the output format are: * Unused candles may be drawn unlit instead of omitted. * You may use non-ASCII characters to make the result more aesthetically pleasing. Like `🔥` (U+1F525) instead of `*`. Or box-drawing characters instead of `+-|`. For the purpose of this challenge, a day on the Hebrew calendar may be assumed to start at 18:00. Results must be correct for Gregorian years between 1900 and 2239, inclusive. --- Hanukkah begins at **sunset** on the Gregorian dates ``` 1900-12-16 1901-12-05 1902-12-24 1903-12-13 1904-12-02 1905-12-22 1906-12-11 1907-11-30 1908-12-18 1909-12-07 1910-12-25 1911-12-15 1912-12-04 1913-12-23 1914-12-12 1915-12-01 1916-12-19 1917-12-09 1918-11-28 1919-12-16 1920-12-05 1921-12-25 1922-12-14 1923-12-02 1924-12-21 1925-12-11 1926-11-30 1927-12-18 1928-12-07 1929-12-26 1930-12-14 1931-12-04 1932-12-23 1933-12-12 1934-12-01 1935-12-20 1936-12-08 1937-11-28 1938-12-17 1939-12-06 1940-12-24 1941-12-14 1942-12-03 1943-12-21 1944-12-10 1945-11-29 1946-12-17 1947-12-07 1948-12-26 1949-12-15 1950-12-03 1951-12-23 1952-12-12 1953-12-01 1954-12-19 1955-12-09 1956-11-28 1957-12-17 1958-12-06 1959-12-25 1960-12-13 1961-12-02 1962-12-21 1963-12-10 1964-11-29 1965-12-18 1966-12-07 1967-12-26 1968-12-15 1969-12-04 1970-12-22 1971-12-12 1972-11-30 1973-12-19 1974-12-08 1975-11-28 1976-12-16 1977-12-04 1978-12-24 1979-12-14 1980-12-02 1981-12-20 1982-12-10 1983-11-30 1984-12-18 1985-12-07 1986-12-26 1987-12-15 1988-12-03 1989-12-22 1990-12-11 1991-12-01 1992-12-19 1993-12-08 1994-11-27 1995-12-17 1996-12-05 1997-12-23 1998-12-13 1999-12-03 2000-12-21 2001-12-09 2002-11-29 2003-12-19 2004-12-07 2005-12-25 2006-12-15 2007-12-04 2008-12-21 2009-12-11 2010-12-01 2011-12-20 2012-12-08 2013-11-27 2014-12-16 2015-12-06 2016-12-24 2017-12-12 2018-12-02 2019-12-22 2020-12-10 2021-11-28 2022-12-18 2023-12-07 2024-12-25 2025-12-14 2026-12-04 2027-12-24 2028-12-12 2029-12-01 2030-12-20 2031-12-09 2032-11-27 2033-12-16 2034-12-06 2035-12-25 2036-12-13 2037-12-02 2038-12-21 2039-12-11 2040-11-29 2041-12-17 2042-12-07 2043-12-26 2044-12-14 2045-12-03 2046-12-23 2047-12-12 2048-11-29 2049-12-19 2050-12-09 2051-11-28 2052-12-15 2053-12-05 2054-12-25 2055-12-14 2056-12-02 2057-12-21 2058-12-10 2059-11-29 2060-12-17 2061-12-07 2062-12-26 2063-12-15 2064-12-03 2065-12-22 2066-12-12 2067-12-01 2068-12-18 2069-12-08 2070-11-27 2071-12-16 2072-12-04 2073-12-24 2074-12-13 2075-12-01 2076-12-20 2077-12-10 2078-11-29 2079-12-17 2080-12-06 2081-12-26 2082-12-15 2083-12-04 2084-12-22 2085-12-11 2086-11-30 2087-12-19 2088-12-07 2089-11-27 2090-12-16 2091-12-05 2092-12-23 2093-12-13 2094-12-02 2095-12-20 2096-12-09 2097-11-29 2098-12-18 2099-12-06 2100-12-26 2101-12-16 2102-12-05 2103-12-23 2104-12-12 2105-12-02 2106-12-21 2107-12-10 2108-11-28 2109-12-17 2110-12-06 2111-12-25 2112-12-13 2113-12-03 2114-12-22 2115-12-10 2116-11-29 2117-12-19 2118-12-08 2119-12-26 2120-12-15 2121-12-04 2122-12-23 2123-12-12 2124-12-01 2125-12-21 2126-12-10 2127-11-29 2128-12-17 2129-12-06 2130-12-24 2131-12-14 2132-12-03 2133-12-22 2134-12-11 2135-11-30 2136-12-18 2137-12-07 2138-12-26 2139-12-15 2140-12-04 2141-12-23 2142-12-12 2143-12-01 2144-12-20 2145-12-09 2146-11-27 2147-12-17 2148-12-05 2149-12-24 2150-12-13 2151-12-03 2152-12-22 2153-12-11 2154-11-30 2155-12-19 2156-12-07 2157-12-25 2158-12-15 2159-12-05 2160-12-23 2161-12-12 2162-12-01 2163-12-20 2164-12-09 2165-11-28 2166-12-16 2167-12-06 2168-12-24 2169-12-13 2170-12-02 2171-12-22 2172-12-10 2173-11-28 2174-12-18 2175-12-08 2176-12-26 2177-12-14 2178-12-04 2179-12-24 2180-12-12 2181-12-01 2182-12-20 2183-12-09 2184-11-28 2185-12-17 2186-12-06 2187-12-25 2188-12-14 2189-12-03 2190-12-21 2191-12-11 2192-11-29 2193-12-17 2194-12-07 2195-12-27 2196-12-15 2197-12-03 2198-12-23 2199-12-13 2200-12-02 2201-12-20 2202-12-10 2203-11-30 2204-12-18 2205-12-07 2206-12-26 2207-12-15 2208-12-03 2209-12-22 2210-12-11 2211-12-01 2212-12-19 2213-12-08 2214-12-27 2215-12-17 2216-12-05 2217-12-23 2218-12-13 2219-12-02 2220-12-20 2221-12-09 2222-11-29 2223-12-18 2224-12-05 2225-12-25 2226-12-15 2227-12-04 2228-12-21 2229-12-11 2230-12-01 2231-12-20 2232-12-08 2233-12-27 2234-12-16 2235-12-05 2236-12-23 2237-12-12 2238-12-02 2239-12-21 ``` [Answer] # Mathematica, ~~376~~ ~~338~~ 334 bytes ``` a=Rest@$ScriptCommandLine;b=CalendarConvert[If[a=={},Now~TimeZoneConvert~0,DateObject[FromDigits/@a,TimeZone->0]],j="Jewish"];c=Floor@DateDifference[DateObject[{b[[1,1]],9,25},CalendarType->j,TimeZone->0],b][[1]];d=If[#<=c,"*"," "]&;0<=c<8&&Print[" * "<>{d/@{7,6,5,4},"|",d/@{3,2,1},"* ||||||||| ||||||||| +++++++++ | -+-"}] ``` Runs in a script. [Answer] ## R, 467 bytes With a little doubt if using a library for the Calendar conversion is allowed or not. ``` library(ConvCalendar) f='%Y %m %d %H %M %S' g='hebrew' s=' ' if(length(n<-scan())!=6)n=format(Sys.time(),f) if(n[4]>17)n[3]=n[3]+1 d=strptime(paste(n,collapse=s),f) h=as.OtherDate(d,g) i=OtherDate(25,3,h$year,g) j=round(difftime(d,as.Date(i),,"days"))+1 N=ifelse(j>0&j<10,(1:9)[j],0) if(!N)write('')else{l='**||+|+' z=matrix(strsplit(l,'')[[1]],9,7,T) z[c(1:4,6:9),c(1,6:7)]=s z[c(4,6),7]='-' if(N<8)z[1:(9-N),2:4]=s z[5,2:4]='|' write(z,'',9,,'')} ``` Example for input 2015 12 07 00 00 00: ``` * | * | | | | +++++++++ | -+- ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 193 bytes Prompts for input from STDIN and prints to STDOUT. Uses box drawing characters and an [actual lamp symbol](https://en.wikipedia.org/wiki/APL_syntax_and_symbols#Miscellaneous)! ``` ⎕USING←'System' →3×(c←+/i≥((⎕NEW Globalization.HebrewCalendar).(ToDateTime 7↑3 23 18,⍨GetYear)i←⎕NEW DateTime(6↑⍎∊⍞'⎕TS')).AddDays¨⍳9)∊⍳8 ¯5↑'⍝' '⍝'@(10-r+5≤r←⍳c)⊢9↑s←¯5↑'│' 9/⍪'││┴' s ' ─┴─' ``` `⎕USING←'System'` Use .NET `⍳8` first eight **ɩ**ntegers `(`…`)∊` Boolean for whether the following is a member of that:  `⍳9` first nine integers  `(`…`).AddDays¨` for each, add that many days to:   `⎕NEW DateTime(`…`)` a new DateTime .NET object with the value of:    `⍞'⎕TS'` STDIN and expression for current **T**ime **S**tamp    `∊` **ϵ**nlist (flatten)    `⍎` execute (evaluate) that (gives six- or seven-element numeric list)    `6↑` take the first six elements (Y M D h m s)   `i←` store as `i` (for **i**nput)   `(⎕NEW Globalization.HebrewCalendar).(`…`)` in a new HebrewCalendar object:    `GetYear` get the (Hebrew) year of the input    `3 23 18,⍨` append these (3 month, 23th day, 18th hour — one night before Hanukkah)    `7↑` take the first seven elements, padding with 0s (minutes, seconds)    `ToDateTime` convert that Hebrew point in time to normal DateTime object  `i≥` Boolean whether the input is equal to or after each of those  `+/` sum the Booleans  `c←` store as `c` (for **c**ount) `3×` multiply by three `→` go to that line (3, i.e. next, if Hanukkah; 0, i.e. quit, if not) `¯5↑'⍝'` implicitly print the last five characters of the lamp symbol (padding with spaces) `¯5↑'│'` last five characters of the middle-candle symbol (padding with spaces) `s←` store as s (for **s**tem) `9↑` take the first nine characters from that (padding with spaces) `⊢` yield (separates the above from the below `'⍝'@(`…`)` implicitly print with lamps placed at the following indices:  `⍳c` as many **ɩ**ntegers as count of begun Hanukkah days  `r←` store in `r` (for **r**ange)  `5≤` Booleans for those larger than or equal to five (to skip the middle candle)  `r+` add to the range of indices  `10-` subtract those from ten (to begin at the right) `⍪'││┴'` make this string into a column matrix `9/` implicitly print nine horizontal copies of that `s` implicitly print the stem `' ─┴─'` implicitly print this string ### Example run: ``` menorah 2015 12 7 0 0 0 ⍝ │ ⍝ │││││││││ │││││││││ ┴┴┴┴┴┴┴┴┴ │ ─┴─ menorah 2015 12 9 0 0 0 ⍝ │ ⍝⍝⍝ │││││││││ │││││││││ ┴┴┴┴┴┴┴┴┴ │ ─┴─ menorah 2015 12 14 0 0 0 ⍝ ⍝⍝⍝⍝│⍝⍝⍝⍝ │││││││││ │││││││││ ┴┴┴┴┴┴┴┴┴ │ ─┴─ menorah 2015 12 15 0 0 0 ``` ]
[Question] [ Given a positive integer *n* output the sum of the first *n* decimal digits of the fractional part of *πn*. Example input and outputs: > > 1 → 1 > > 2 → 14 > > 3 → 6 > > 4 → 13 > > 5 → 24 > > 50 → 211 > > 500 → 2305 > > 5000 → 22852 > > > Built-in functions computing digits of *π* or evaluating either power series or continued fractions are not allowed. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. Input/output can be in a convenient format (stdin, stdout, function in/output, etc). Shortest [code in bytes](http://meta.codegolf.stackexchange.com/questions/4944/byte-counter-snippet) wins. [Answer] ## Python - 191 Bytes ``` t=i=1L;k=n=input();f=2000*20**n;A=range(n+1) for k in range(2,n):A=[(A[j-1]+A[j+1])*j>>1for j in range(n-k+1)];f*=k while k:k=(1-~i*n%4)*f/A[1]/i**n;t+=k;i+=2 print sum(map(int,`t`[-n-4:-4])) ``` **~4x faster version - 206 bytes** ``` t=i=1L;k=n=input();f=2000*20**n;A=[0,1]+[0]*n for k in range(1,n): f*=k for j in range(-~n/2-k+1):A[j]=j*A[j-1]+A[j+1]*(j+2-n%2) while k:k=(1-~i*n%4)*f/A[1]/i**n;t+=k;i+=2 print sum(map(int,`t`[-n-4:-4])) ``` Input is taken from stdin. Output for *n = 5000* takes approximately 14s with the second script (or 60s with the first). --- Sample usage: ``` $ echo 1 | python pi-trunc.py 1 $ echo 2 | python pi-trunc.py 14 $ echo 3 | python pi-trunc.py 6 $ echo 4 | python pi-trunc.py 13 $ echo 5 | python pi-trunc.py 24 $ echo 50 | python pi-trunc.py 211 $ echo 500 | python pi-trunc.py 2305 $ echo 5000 | python pi-trunc.py 22852 ``` --- The formula used is the following: ![](https://chart.googleapis.com/chart?cht=tx&chl=%5Cpi%5En%3D2%5E%7Bn%2B1%7D%5Cfrac%7B%28n-1%29%21%7D%7BA_%7Bn-1%7D%7Dc_n) where *An* is the *nth* [Alternating Number](http://en.wikipedia.org/wiki/Alternating_permutation#Related_integer_sequences), which can be formally defined as the number of alternating permutations on a set of size *n* (see also: [A000111](http://oeis.org/A000111)). Alternatively, the sequence can be defined as the composition of the Tangent Numbers and Secant Numbers (*A2n = Sn*, *A2n+1 = Tn*), more on that later. The small correction factor *cn* rapidly converges to *1* as *n* becomes large, and is given by: ![](https://chart.googleapis.com/chart?cht=tx&chl=c_n%3D%5Csum%5Climits_%7B_%7Bk%3D0%7D%7D%5E%7B_%5Cinfty%7D%7B%5Cleft%28%5Cfrac%7B%28-1%29%5Ek%7D%7B2k%2B1%7D%5Cright%29%5En%7D) For *n = 1*, this amounts to evaluating the [Leibniz Series](http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80). Approximating *π* as *10½*, the number of terms required can be calculated as: ![](https://chart.googleapis.com/chart?cht=tx&chl=%5Cfrac%7B1%7D%7B2%7D%5Cleft%5B1%2B%5Cleft%2810%5E%7B%5Cfrac%7B3n%7D%7B2%7D%2B3%7D%5Cright%29%5E%7B%5Cfrac%7B1%7D%7Bn%7D%7D%5Cright%5D) which converges (rounded up) to *17*, although smaller values of *n* require considerably more. For the calculation of *An* there are several algorithms, and even an explicit formula, but all of them are quadratic by *n*. I originally coded an implementation of [Seidel's Algorithm](http://en.wikipedia.org/wiki/Bernoulli_number#An_algorithmic_view:_the_Seidel_triangle), but it turns to be too slow to be practical. Each iteration requires an additional term to be stored, and the terms increase in magnitude very rapidly (the "wrong" kind of *O(n2)*). The first script uses an implementation of an algorithm originally given by [Knuth and Buckholtz](http://www.ams.org/journals/mcom/1967-21-100/S0025-5718-1967-0221735-9/): > > *Let T1,k = 1 for all k = 1..n* > > > *Subsequent values of T are given by the recurrence relation:* > > > *Tn+1,k = 1/2* [ *(k - 1) Tn,k-1 + (k + 1) Tn,k+1* ] > > > *An is then given by Tn,1* > > > (see also: [A185414](http://oeis.org/A185414)) > > > Although not explicitly stated, this algorithm calculates both the Tangent Numbers and the Secant Numbers simultaneously. The second script uses a variation of this algorithm by [Brent and Zimmermann](http://arxiv.org/abs/1004.4710), which calculates either *T* or *S*, depending on the parity of *n*. The improvement is quadratic by *n/2*, hence the ~4x speed improvement. [Answer] # Python 2, 246 bytes I have taken a similar approach to my answer at [Calculate π with quadratic convergence](https://codegolf.stackexchange.com/questions/47912/calculate-%cf%80-with-quadratic-convergence/47925#47925) . The last line takes the Nth power of pi and sums the digits. The N=5000 test takes a minute or so. ``` from decimal import* d=Decimal N=input() getcontext().prec=2*N j=d(1) h=d(2) f=h*h g=j/h a=j b=j/h.sqrt() t=j/f p=j for i in bin(N)[2:]:e=a;a,b=(a+b)/h,(a*b).sqrt();c=e-a;t-=c*c*p;p+=p k=a+b l=k*k/f/t print sum(map(int,`l**N`.split('.')[1][:N])) ``` Some tests: ``` $ echo 1 | python soln.py 1 $ echo 3 | python soln.py 6 $ echo 5 | python soln.py 24 $ echo 500 | python soln.py 2305 $ echo 5000 | python soln.py 22852 ``` The ungolfed code: ``` from decimal import * d = Decimal N = input() getcontext().prec = 2 * N # constants: one = d(1) two = d(2) four = two*two half = one/two # initialise: a = one b = one / two.sqrt() t = one / four p = one for i in bin(N)[2:] : temp = a; a, b = (a+b)/two, (a*b).sqrt(); pterm = temp-a; t -= pterm*pterm * p; p += p ab = a+b pi = ab*ab / four / t print sum(map(int, `pi ** N`.split('.')[1][:N])) ``` [Answer] # Pyth, 33 ``` s<>j^u+/*GHhyHy^TyQr*TQ0ZQT_y*QQQ ``` [Based on this answer by isaacg](https://codegolf.stackexchange.com/a/40251/4162). Could probably be golfed more. Slow. ``` s<>j Digit sum of... ^ u Evaluate pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...)))) + / *GH hyH y^TyQ Except we generate a large integer containing 2n digits, rather than a fraction. r*TQ0 Experimentally verified that 10*n iterations will give enough precision for 2n digits (# digits correct grows faster than 2n). Z Q To the nth power. T_y*QQQ Get the last 2n^2 digits (all the fractional digits) and get the first n fractional digits. ``` ]
[Question] [ There has already been a [9 Hole Challenge](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge) (and another one [here](https://codegolf.stackexchange.com/questions/19163/9-hole-mini-golf-text-manipulation)), but that was soooo last year. And besides, [I](https://codegolf.stackexchange.com/users/29820/stretch-maniac) have only been around for 2 months (although it seems like forever). And it is considerably different. Leader Board: (note that weighting for holes are not established yet) ``` +---------------+------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+ |Competitor | Language | Hole 1 | Hole 2 | Hole 3 | Hole 4 | Hole 5 | Hole 6 | Hole 7 | Hole 8 | Hole 9 | Total | +----------------------------------------------------------------------------------------------------------------------+ |Dennis |CJam | | 31 | | | | | | | | 31 | +----------------------------------------------------------------------------------------------------------------------+ |Optimizer |CJam | | 35 | | | | | | | | 35 | +----------------------------------------------------------------------------------------------------------------------+ |Martin Büttner |Mathematica | | 222 | | | | | | | | 222 | +----------------------------------------------------------------------------------------------------------------------+ |Cameron |Python | 878 | | | | | | | | | 878 | +----------------------------------------------------------------------------------------------------------------------+ |bubalou |Processing 2| 717 | | | | | | | | | 717 | +----------------------------------------------------------------------------------------------------------------------+ |Doorknob |Python 2 | | |0.079711| | | | | | |0.079711| +----------------------------------------------------------------------------------------------------------------------+ |Vulcan |Java | | |0.6949 | | | | | | |0.6949 | +----------------------------------------------------------------------------------------------------------------------+ |Eli |C++ | | |1.42042 | | | | | | |1.42042 | +---------------+------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+ ``` **Other Holes:** * [hole 2](https://codegolf.stackexchange.com/questions/39872/hole-2-prime-quine) * [hole 3](https://codegolf.stackexchange.com/questions/40069/hungry-image-snake-hole-3) It's been slow around here lately, so I am here to kick off the next 9 hole golf course, involving a smattering of all that I have seen here in my (albeit limited) experience. This will entail: * Ascii Art * Graphical Output * Conway's Game of Life * King of the Hill * Kolmogorov complexity * Quines * Image processing * Math * Classic code golf. I am really looking forward to seeing what you can do! ## Competition Rules * You will choose **1 language** for **all** of the holes (that you participate in...see point 4 for more info). * For all holes - [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are (still) not funny. * The next challenge will appear when I see that there are enough submissions given a reasonable amount of time. King of the hill, for example, will take longer. * You **do not** have to participate in all of the holes. If you find a hole particularly challenging, don't have the time to do it, etc, you will receive 2 times as many points as the lowest score. Please do not take advantage of this rule by leaving 1 golfscript answer with 12 characters and taking 24 as a score. ## Scoring * Your score is based on the culmination of the scores from all of the holes * Lowest score wins (as per real golf) * The leaderboard will be placed at the top of this page I will try my very best to make sure that no questions are duplicates, all questions have objective criteria, are well written, and that they all have (relatively) equal weight in the context of the whole contest. *However, Please be patient when I fail.* And, without further ado, the first challenge! ## The Plasma Globe A [plasma globe](http://en.wikipedia.org/wiki/Plasma_globe) is everyone's favorite toy: ![enter image description here](https://i.stack.imgur.com/oUbu2.jpg) Your job it to draw one. You must draw a base: ![enter image description here](https://i.stack.imgur.com/OLqN2.jpg) a globe: ![enter image description here](https://i.stack.imgur.com/jtuqo.jpg) A tesla thingy (?) ![enter image description here](https://i.stack.imgur.com/WXxoS.jpg) And, of course, cool plasma shoots: ![enter image description here](https://i.stack.imgur.com/hNRrF.jpg) However, when you put your hand near a plasma globe (or a conductive object as Wikipedia tells me), it [attracts the plasma](http://upload.wikimedia.org/wikipedia/commons/7/71/Plasma_lamp_touching.jpg). Your globe should reflect that. To put it quantitatively, your globe has a maximum of 16 shoots (see above picture). An "object" on the surface of the globe (given by an angle in radians) will contain "conductive power", that is, the amount of beams it attracts. So an object with a power of 5 will attract 5 beams (a single line with thickness 5) leaving 11 to **spread evenly among the rest of the globe**: ![enter image description here](https://i.stack.imgur.com/JGcKZ.jpg) Note that 1. the black circle in the middle remains above the plasma 2. that in this example, the angle would be pi/2. You may have more than one conductive object, and in that event, it is not required that the shoots are equally spaced apart. However, they be relatively spaced out. For example, this is ok for 2 objects, 1 at angle pi/4 power 5 and another at angle 5pi/3 power 3: ![enter image description here](https://i.stack.imgur.com/NRNcx.jpg) You should be able to see each of the end points of the shoots (of plasma). However, given an object (or sum of objects) with power greater than 16, the globe will "break": ![enter image description here](https://i.stack.imgur.com/vhVZT.jpg) ## Notes * The globe's diameter is 1.5 times bigger than the length of the base, which is a square * When the globe breaks, the globe is on the right side. It is tangent to the right side of the base as well as the ground. There should be no plasma when the plasma globe is broken (why? safety features of course! No word on how it broke in the first place.) * The color of everything except the shoots must be black, and 1 pixel thick. The color of the plasma has hue 245 - 280, and saturation/value 100. Use [this](http://colorizer.org/) under "HSV" if you have no idea what I am talking about. ## Input Input can be through STDIN/command line args/whatever or through function arguments. There should be 2 inputs - length of the base of the plasma globe (include an axis if using vector graphics), and an array of objects like this: ``` [[angle,power],[angle,power],[angle,power]] ``` So for no objects (see first picture with 16 lines) the input would be ``` 100,[] ``` For the next (one object, power 5) it would be: ``` 100,[[1.570796,5]] ``` For the last example: ``` 100,[[0.785398,5],[5.23598,3]] ``` This is code-golf, so shortest code [in bytes](https://mothereff.in/byte-counter) wins. [Answer] # Processing 2 - 717 characters As processing is a language made for artists, and I am a very novice programmer, I do not expect to do very well on many of these challenges. That being said, I really like how simple it is to draw things in processing, and I have been meaning to play around with it some more, so these challenges should be interesting. ``` int j,m,b,k,d,l;float w,c,h,x,y,z;float v[],p[],g[];void setup(){j=m=d=0;c=z=0;String i[]= loadStrings("f.txt");i[0]=i[0].replace("[","").replace("]","");String o[]=split(i[0],',');v=new float[o.length];p=new float[o.length-1];for(String s:o){if(!s.equals("")){v[j]=Float.parseFloat(s);}j++;}w=v[0];size((int)w*3,(int)w*3);h=w*.75;l=v.length;noLoop();}void draw(){translate(w/2,height);scale(1,-1);rect(0,0,w,w);if(l>2){while(m<j-1){m+=2;c+=v[m];}}if(c>16){ellipse(w+h,h,2*h,2*h);rect(w/2,w,1,h);}else{ellipse(w/2,w+h,2*h,2*h);rect(w/2,w,1,h);b=16;m=1;stroke(#1500ff);if(l>2){while(m<j){p[m-1]=cos(v[m])*h;p[m]=sin(v[m])*h;strokeWeight(v[m+1]);line(w/2,w+h,p[m-1]+w/2,p[m]+w+h);b-=v[m+1];m+=2;}}strokeWeight(1);c=(PI*2)/b;k=b;g=new float[b+b];while(b>0){g[d]=cos(z+c*b)*h;g[d+1]=sin(z+c*b)*h;m=0;if(l>2){while(m<j-1){if(abs(g[d]-p[m])<.1 && abs(g[d+1]-p[m+1])<.1){b=k+1;z=z+.1;d=-2;break;}m+=2;}}b--;d+=2;}d--;while(d>0){line(w/2,w+h,g[d]+w/2,g[d-1]+w+h);d-=2;}}stroke(#000000);fill(#000000);ellipse(w/2,w+h,w/9,w/9);} ``` I'm sure this can be golfed down considerably and I may try to do that when I have more time, but for now I am happy with it. reads in a file (f.txt) located in the data folder of the sketch to get its input. I used Camerons idea of shifting the free beams until they don't overlap. ``` int j,m,b,k,d,l; float w,c,h,x,y,z; float v[],p[],g[]; void setup(){ j=m=d=0; c=z=0; String i[]= loadStrings("f.txt"); i[0]=i[0].replace("[","").replace("]",""); String o[]=split(i[0],','); v=new float[o.length]; p=new float[o.length-1]; for(String s:o){if(!s.equals("")){v[j]=Float.parseFloat(s);}j++;} w=v[0]; size((int)w*3,(int)w*3); h=w*.75; l=v.length; noLoop(); } void draw() { translate(w/2,height); scale(1,-1); rect(0,0,w,w); if(l>2) { while(m<j-1) { m+=2; c+=v[m]; } } if(c>16) { ellipse(w+h,h,2*h,2*h); rect(w/2,w,1,h); } else { ellipse(w/2,w+h,2*h,2*h); rect(w/2,w,1,h); b=16;m=1; stroke(#1500ff); if(l>2) { while(m<j) { p[m-1] = cos(v[m]) * h; p[m] = sin(v[m]) * h; strokeWeight(v[m+1]); line(w/2,w+h,p[m-1]+w/2,p[m]+w+h); b-=v[m+1]; m+=2; } } strokeWeight(1); c=(PI*2)/b; k=b; g=new float[b+b]; while(b>0) { g[d] = cos(z+c*b) * h; g[d+1] = sin(z+c*b) * h; m=0; if(l>2) { while(m<j-1) { if(abs(g[d]-p[m])<.1 && abs(g[d+1]-p[m+1])<.1) { b=k+1; z=z+.1; d=-2; break; } m+=2; } } b--; d+=2; } d--; while(d>0) { line(w/2,w+h,g[d]+w/2,g[d-1]+w+h); d-=2; } } stroke(#000000); fill(#000000); ellipse(w/2,w+h,w/9,w/9); } ``` Examples: 100,[[0.785398,3],[5.23598,5]] ![plasma orb 1](https://i.stack.imgur.com/GmpKH.png) 100,[] ![plasma orb 2](https://i.stack.imgur.com/2NEEc.png) 100,[[1.72398,12],[5.23598,5]] ![plasma orb 3](https://i.stack.imgur.com/0Ah72.png) get processing [here](https://www.processing.org/download/) [Answer] ## Python, 878 chars By no means is this golfed well, but I wanted to see an answer for this hole. ``` import matplotlib.pyplot as P from math import * L=len M=min Y=P.plot K=P.Circle Z=P.gcf().gca().add_artist f=sin g=cos k={'color':(0,0,0)} j={'color':(.16,0,1)} def Q(S,C): P.axis([-S,S*2.5,0,S*3.5],**k) Y([0,S,S,0,0],[0,0,S,S,0],**k) Y([S/2,S/2],[S,7*S/4],**k) Z(K([S/2,7*S/4],S/20,**k)) k['fill']=False A,B=zip(*C) N=16-sum(B) if N<0: Z(K([7*S/4,3*S/4],3*S/4,**k)) else: Z(K([S/2,7*S/4],3*S/4,**k)) if L(C)==0: D(16,0,S) elif L(C)==1: D(N,A[0],S) Y([S/2,S/2+3*S*g(A[0])/4],[7*S/4,7*S/4+3*S*f(A[0])/4],linewidth=B[0],**j) else: for c in C: Y([S/2,S/2+3*S*g(c[0])/4],[7*S/4,7*S/4+3*S*f(c[0])/4],linewidth=c[1],**j) D(N,J(N,A),S) P.show() def J(N,A): T=d=0 t=2*pi/N while d<0.1: T+=0.1 d=M(M(a-T-floor((a-T)/t)*t for a in A),\ M(T+ceil((a-T)/t)*t-a for a in A)) return T def D(N,I,S): a=I for i in range(N): Y([S/2,S/2+3*S*g(a)/4],[7*S/4,7*S/4+3*S*f(a)/4],**j) a+=2*pi/N ``` And some sample outputs ``` Q(100,[[pi/4,6],[-4.2*pi/8,1]]) ``` ![enter image description here](https://i.stack.imgur.com/Io6n4.png) ``` Q(100,[[0.785398,10],[5.23598,7]]) ``` ![enter image description here](https://i.stack.imgur.com/4RR8X.png) ``` Q(100,[[pi/4,3],[pi/2,3],[3*pi/2,2],[5*pi/4,2]]) ``` ![enter image description here](https://i.stack.imgur.com/z4py4.png) [Answer] # Python 2.7, ~~378~~ 375 ``` from turtle import *;import sys (s,P),A,B=eval(sys.argv[1]),90,180 n,S=sum([b for(a,b) in P]),.75*s;l=16-n for i in 'abcd':fd(s);lt(A) pu() if l<0:goto(s+S,0) else:goto(s/2,s) pd();circle(S);pu();goto(s/2,s);lt(A);pd();fd(S) def C():fd(S);fd(-S) if n<16: color('blue') for i in range(l):rt(360/l);C() for a,p in P:pensize(p);rt(a*57.3);C() color('black') shape('circle') ``` It reads its parameters from commandline argument. Sample images : (parameters=`100,[[0.785398,5],[5.23598,3]]`) ![tesla](https://i.stack.imgur.com/p1sXy.png) (parameters=`100,[]`) ![tesla2](https://i.stack.imgur.com/thU4l.png) (parameters=`100,[[1.72398,12],[5.23598,5]]`) ![tesla3](https://i.stack.imgur.com/uMhmU.png) ]