text
stringlengths
180
608k
[Question] [ ## The Task The task is easy: given an Alpha-2 country code, output the Alpha-3 equivalent. The input may be in any case you choose, and the output in any consistent case of your choosing. Here are the codes: ``` [["AF", "AFG"], ["AX", "ALA"], ["AL", "ALB"], ["DZ", "DZA"], ["AS", "ASM"], ["AD", "AND"], ["AO", "AGO"], ["AI", "AIA"], ["AQ", "ATA"], ["AG", "ATG"], ["AR", "ARG"], ["AM", "ARM"], ["AW", "ABW"], ["AU", "AUS"], ["AT", "AUT"], ["AZ", "AZE"], ["BS", "BHS"], ["BH", "BHR"], ["BD", "BGD"], ["BB", "BRB"], ["BY", "BLR"], ["BE", "BEL"], ["BZ", "BLZ"], ["BJ", "BEN"], ["BM", "BMU"], ["BT", "BTN"], ["BO", "BOL"], ["BA", "BIH"], ["BW", "BWA"], ["BV", "BVT"], ["BR", "BRA"], ["VG", "VGB"], ["IO", "IOT"], ["BN", "BRN"], ["BG", "BGR"], ["BF", "BFA"], ["BI", "BDI"], ["KH", "KHM"], ["CM", "CMR"], ["CA", "CAN"], ["CV", "CPV"], ["KY", "CYM"], ["CF", "CAF"], ["TD", "TCD"], ["CL", "CHL"], ["CN", "CHN"], ["HK", "HKG"], ["MO", "MAC"], ["CX", "CXR"], ["CC", "CCK"], ["CO", "COL"], ["KM", "COM"], ["CG", "COG"], ["CD", "COD"], ["CK", "COK"], ["CR", "CRI"], ["CI", "CIV"], ["HR", "HRV"], ["CU", "CUB"], ["CY", "CYP"], ["CZ", "CZE"], ["DK", "DNK"], ["DJ", "DJI"], ["DM", "DMA"], ["DO", "DOM"], ["EC", "ECU"], ["EG", "EGY"], ["SV", "SLV"], ["GQ", "GNQ"], ["ER", "ERI"], ["EE", "EST"], ["ET", "ETH"], ["FK", "FLK"], ["FO", "FRO"], ["FJ", "FJI"], ["FI", "FIN"], ["FR", "FRA"], ["GF", "GUF"], ["PF", "PYF"], ["TF", "ATF"], ["GA", "GAB"], ["GM", "GMB"], ["GE", "GEO"], ["DE", "DEU"], ["GH", "GHA"], ["GI", "GIB"], ["GR", "GRC"], ["GL", "GRL"], ["GD", "GRD"], ["GP", "GLP"], ["GU", "GUM"], ["GT", "GTM"], ["GG", "GGY"], ["GN", "GIN"], ["GW", "GNB"], ["GY", "GUY"], ["HT", "HTI"], ["HM", "HMD"], ["VA", "VAT"], ["HN", "HND"], ["HU", "HUN"], ["IS", "ISL"], ["IN", "IND"], ["ID", "IDN"], ["IR", "IRN"], ["IQ", "IRQ"], ["IE", "IRL"], ["IM", "IMN"], ["IL", "ISR"], ["IT", "ITA"], ["JM", "JAM"], ["JP", "JPN"], ["JE", "JEY"], ["JO", "JOR"], ["KZ", "KAZ"], ["KE", "KEN"], ["KI", "KIR"], ["KP", "PRK"], ["KR", "KOR"], ["KW", "KWT"], ["KG", "KGZ"], ["LA", "LAO"], ["LV", "LVA"], ["LB", "LBN"], ["LS", "LSO"], ["LR", "LBR"], ["LY", "LBY"], ["LI", "LIE"], ["LT", "LTU"], ["LU", "LUX"], ["MK", "MKD"], ["MG", "MDG"], ["MW", "MWI"], ["MY", "MYS"], ["MV", "MDV"], ["ML", "MLI"], ["MT", "MLT"], ["MH", "MHL"], ["MQ", "MTQ"], ["MR", "MRT"], ["MU", "MUS"], ["YT", "MYT"], ["MX", "MEX"], ["FM", "FSM"], ["MD", "MDA"], ["MC", "MCO"], ["MN", "MNG"], ["ME", "MNE"], ["MS", "MSR"], ["MA", "MAR"], ["MZ", "MOZ"], ["MM", "MMR"], ["NA", "NAM"], ["NR", "NRU"], ["NP", "NPL"], ["NL", "NLD"], ["AN", "ANT"], ["NC", "NCL"], ["NZ", "NZL"], ["NI", "NIC"], ["NE", "NER"], ["NG", "NGA"], ["NU", "NIU"], ["NF", "NFK"], ["MP", "MNP"], ["NO", "NOR"], ["OM", "OMN"], ["PK", "PAK"], ["PW", "PLW"], ["PS", "PSE"], ["PA", "PAN"], ["PG", "PNG"], ["PY", "PRY"], ["PE", "PER"], ["PH", "PHL"], ["PN", "PCN"], ["PL", "POL"], ["PT", "PRT"], ["PR", "PRI"], ["QA", "QAT"], ["RE", "REU"], ["RO", "ROU"], ["RU", "RUS"], ["RW", "RWA"], ["BL", "BLM"], ["SH", "SHN"], ["KN", "KNA"], ["LC", "LCA"], ["MF", "MAF"], ["PM", "SPM"], ["VC", "VCT"], ["WS", "WSM"], ["SM", "SMR"], ["ST", "STP"], ["SA", "SAU"], ["SN", "SEN"], ["RS", "SRB"], ["SC", "SYC"], ["SL", "SLE"], ["SG", "SGP"], ["SK", "SVK"], ["SI", "SVN"], ["SB", "SLB"], ["SO", "SOM"], ["ZA", "ZAF"], ["GS", "SGS"], ["SS", "SSD"], ["ES", "ESP"], ["LK", "LKA"], ["SD", "SDN"], ["SR", "SUR"], ["SJ", "SJM"], ["SZ", "SWZ"], ["SE", "SWE"], ["CH", "CHE"], ["SY", "SYR"], ["TW", "TWN"], ["TJ", "TJK"], ["TZ", "TZA"], ["TH", "THA"], ["TL", "TLS"], ["TG", "TGO"], ["TK", "TKL"], ["TO", "TON"], ["TT", "TTO"], ["TN", "TUN"], ["TR", "TUR"], ["TM", "TKM"], ["TC", "TCA"], ["TV", "TUV"], ["UG", "UGA"], ["UA", "UKR"], ["AE", "ARE"], ["GB", "GBR"], ["US", "USA"], ["UM", "UMI"], ["UY", "URY"], ["UZ", "UZB"], ["VU", "VUT"], ["VE", "VEN"], ["VN", "VNM"], ["VI", "VIR"], ["WF", "WLF"], ["EH", "ESH"], ["YE", "YEM"], ["ZM", "ZMB"], ["ZW", "ZWE"]] ``` ## Test Cases ``` US -> USA GT -> GTM VA -> VAT IN -> IND KP -> PRK ``` ## Scoring Because my soft drive can only store a kilobyte, and because this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. This is the reverse of [this challenge](https://codegolf.stackexchange.com/q/246777/107299). [Answer] # JavaScript (ES6), ~~582~~ 554 bytes ``` s=>("CCAPMSSS"[x="KYKMTFKPYTPMRSGSAXAQBYBJBAMOEEGWIEILSIUA".search([a,b]=s)/2]||a)+("YOTRYPRGLTLEIASNRSVK"[x]+"MMFKTMBSAARNHCTBLRNR"[x]||(c="E8bOUX3b11R1O1nadL2DIRG1ntTRlSdIeSo10M1L1RK2C2D2RL1U2i4L22N23N3RynL2ao1c3IEr2l1r11T39U9U5S15UlyNw1PN1MvEReM2uDP1l2Rw13c2O2KLSkuN2u1O1uN25I11rB10T1T1N1B1R4M6TnrGt4BrTg2GMuS1bl1E10Mr1gL1RRd2MUrL3hN1T3l10N1Ko1aoEV1ohRhL2I2BpMRPE14U4In3M3F11B7U1E1Ys9IPH24NIl1s1r21BR1rOuY1B2rBi1lnC1MM3u21G1DD3V1IN18N8NDT1rNL21Y7a1RN24N1ZMR8o4T2a10ON1".replace(/\d+/g,n=>"A".repeat(n))[parseInt(s,36)%774],c>{}?c.toUpperCase()+b:b+c)) ``` [Try it online!](https://tio.run/##NVfbchs3En3XV7BYtWWypJWNoRzbScmpuWKGA4AjADPUUNEDRdGWd1mkipSSTcX5g1TlZR93/yPfkx/IJzg86PaLVEfTODh9utGA/rX8cXlY7T89Pv1zu7tff/lw@eVw@X40TNO40c654c1/Lod1X2tf1E3vG22ddPF1fJX0yTSJ9SzP5bzKK@WqNh6eH9bL/ephdLM8u7u9PIxfRrefPy/Hp6NhP/O2b6xUXuVV7Ix1XX3kvj0dal3UXicujq0pU58oayy@fP48Wl0O87d3s/Z6cieEFTOxXd6rKKusFNsnbzfuvlq7nXilhRK2jtIoi6wSbfTpQkWRiSZmYn/eqmi5E6tJle@jjdgL4Sfv2nftaydet5ufzU@iMUL/mNu1jp6zRmwi@5OYrKJZVCv372cTPR@3Pf56XQmxT8QrL7wwIhH2Qn/jt3v5dJHs/cdI6mcn7jYiP4rZi49HOfY@0u1eTR7McceNeGVEvRPLXd6J3YN9UFEVJY/aNrm4aC@q7URPCiGSN@2RoT@8q5oyujDVRhzEPhKJFfvZcy@SaJ98EpttKrSePEdCiiybdKIy4q15azIv9kZFon@zFNYcl4uFtm93Fz5ailczI4bn@/XjZrlaj17@cH/68uPZ9vL9MA5/XS@fRtvx@OZxuT@sq@3T6HA2@Wb8jzdvLm7PVu9/@fX71fnTrn18XO/T5WE9Gp/efXt3uhqPv3x3c3IzjIvh2fGHHN6eHcE1gIoJqACSALLFEWQL/uLwxWkCGYDJCMwA5IxABVDxmisAz0AGwJtaAMtAB8DUc4BkTqAFaB0BH4AnAG3xIg8ggbakpLCkDMASgNBEktAkAbCUXNIDKA7LAXJFYBG@LAhMwxdDAEIT3RKAnMTzF3iQzJggBqhKAsgnmZMHSQfQUQqJDXLoSwd3OknaKrBVMw4zIYz3kSEfVo0yJgVTw/gkqwKo4UFdkqMpVKea1qTQlsbElkJO2nS0BoakPa8pQlgRgIeJPiUTU3RIWlKmqQmA2Mr6CMqaaqqRgo5TCkOLpdesIAVIawIIS9m3OgidsQIZALGlWQCsoA6ACWBiaintFB6kFeVT4ktpCaRopLQle1PKtCGAaqfcSBmoM0PUGUqfTYk6g7ZMk9cZVGcsNEc@eUpNkUN1LvsAHOx1ihRInAVprigM2nJWnaP5ckfVztFVuafeKSCnUCSnwKaFpWNWQFvB2gqkXVRUhcKGMBIqUUbZUhkbgKbnmoYR4AlINIWMyR2JTKVmAG0yp00zgCynTCVaTJa8DxTIitdAgbRUeqkCoALLLAAqo2wAFFVBtkEoOSrhgfQM4KhkR6UJ@1Cmch4c5U37QEBhJQhKT@6UyKfUtGmHTLuYvC7BVvIUK6GgbIm6wkCpHKmuEFZxWIUUqozDkGnFR7O6CoAKXOUBMAEUVJrDVKCms1BBaMUDcoqwaUxpT@HOtKE1U7BNc0puij6YzoigRvfWMc2qGmE1z6oaJakrDgNbY6mRaqiuvxLAxHpOhtTwupbEpmCViqn0Cq2sOhKqMEdVQvsoWKUch9nwhahVHwCpVpCjKjpmCmkrT42kYLxqr2lsoON1TV5ryNEZDxQI1XOqqQa17mng6y6E0THTsFcrDvMBUHIaDat5cGkUS3sqloZqbTkMcjRfOX0g6PkLppjOSWiBYhV8HeosKCB3NOaBTskQjd7RhlPIAyAPNHzT3Ac6DtOSAWqqZ1QFjX00D2@DMMMdYqDaWDLRoMCmoeQMPDCKb2cTrmpKwUCbSTkM@5gFA9THVHRoDYSanDdFFYyk5EwbwnhTzBBTUFfpJiRHx9mgRw232AwpzLj9GxS4iWlNg5o2iu76BoY0jtxp4hDGa6CgYRObPrQydVUDoQ0LbVDghgvcIO0mZQIY0vAt0/hAQIY0NgBqlytsesXDwYLa8rCzyMfOGMADyx1ikYL9er2r8HKg@jjIcXw31pBTGz4/qIJKuV2KUHoe0bDKNUTQIaxLSc4c7sy531wI46ZwyMd5Mt4hBReTUIdNHc8DCwLHjx8HatdTtZ0K1xQZ7@C1k8yGYuHZH0AVALG5JKxhNrjj@DpcQMGC85FhU0lWuQActWXuwqVH@yjso2oyxOEwOZ6wDvVxLWeKS89N2QN0r5vTKXF5AJRCWoZHCefTh0yJwKNYfk7UHmx@Ssl5sHl@6noQeL7aPNzxilLwcMfzU9dDta@pqzw88DOmRkm85zBUwfPF4m0ALEcHAsrHp@GRxZt2IYxGWotNWz6ALextayKI8/BwpkwlSiJ59rawt3W8Bvu0mpq8hSEtn58WabcLKmOHvu74fd2BuuPe6ZBCZ7gt0QcdXyxzdO9cUbXzMtSU3i49CPqcmwIKFvymWKAKCxTr5Pbk/MNuny@P/4CObgbLzePDMjqj35PB7Xhw@X7wy8lgsFk/Dfbrw@By8GFEQePvjn9e7baH3WZ9vtl9HH1deww7o9jLrzzfD1789cfvf/7vv8efLwbfDl78@f/fXoxPfh1/@Rs "JavaScript (Node.js) – Try It Online") ### How? The most common letter that needs to be added to an alpha-2 code to get the alpha-3 code is `A`. Therefore, it's the best suited padding character for our main lookup string, which is expanded by replacing all integers with the corresponding number of `A`'s. [Try it online!](https://tio.run/##dVDNbptAGLznKRAnW2kdz7e4sWWlUgnURWYXa4GornpZwwrcrhZrgaR5epcccsxppNH8af6oZ9VX7nwZPtuu1ter0YPXew@eH69PWfmTnQCJDFbVKUWJ3MEOhTR5nei8w5IjhdzTI0UkU5R0DlIiQUww@WpTUh0qlsSODBxQsE25KVc5VqV5FS84CPDnWGpOY3SAIfkCVlFG@zT/Owoap9oJVgngQiwLFBAIIQP@pbBuNwShKxra8THHySCexjg00xxZEy9dyloxNRosBfYdVBc/oWtlm1JC4YXLQ4ygDBLLOPsOhPfllHDsN8nhBwUiMejhCKGEy8YjQnLhGcY@gnM2EnaIIvaERGAt1iIq4ERKON4rSDHZ8YvLdRcUpLDMBPztzdur@t9F2VrX07n9wumLUZWe3f2ub@@aT/bhq//Nf2O1GmZ2Pt/eVJ3tO6MXpmtm79aF0bYZWu/W872qVU5Vg3a9/4F6vr1e/wM "JavaScript (Node.js) – Try It Online") The lookup function is a single modulo on the input parsed in base-36: ``` parseInt(s, 36) % 774 ``` If we get a character in upper case, it means that it must be added at the end of the alpha-2 code. ``` "AF" ~> "G" ~> "AF**G**" ``` If we get a character in lower case, it means that it must be added in the middle of the alpha-2 code: ``` "AO" ~> "g" ~> "A**G**O" ``` Similarly to [my answer to the other challenge](https://codegolf.stackexchange.com/a/246784/58563), the 20 codes that do not follow the above rules are hard-coded separately, just the other way around. [Answer] # [Perl 5](https://www.perl.org/) `-MLocale::Country -pl`, ~~48~~ 40 bytes ``` $_=country_code2code($_,,'alpha-3')||ant ``` [Try it online!](https://tio.run/##JZOxat0wGEb38xyBtJAsLV0CHSRZlmXpl3Ul2Y69hEsaaCHkhjQdCnn23qZ0OcPh8G3f88PL45fz@eLu6/3p19Pry@@7@9O3h0//8OHi7urq8vj4/P14/fny49vb8en1fFYdyqJ6lEN5VEQJKqEm1AFVUBXVUDNqRd2idrRCa3SHtuge7dAD2qNHdEQLOqEndEFXdEMv6BW9oXeMwhhMh@kxDjNgPCZgIkYwCTNhCmbGLJhbzIbZ6SzdSBfohG6i27EGa7EOO2ALtmIbvacf6QO90E/0BadwGtfhLK7HOdyA87iIE1zCZdwB915WXMPNuBW3MQQGYUgMhaExzPgOb/ERL/iEn/AHfMFXfGO0jMI4MWaCJTjCQPAEISTCuyyElbARdqIiaqIhemIgFmIlNuJMXIgbohCDdIhFesQhAxKQiAiSkAnJyAEpSEUaMiMLsiK3yPvCTlIkQ7KknuRInhRJEymTCmkm7UxCVmRL7smOPJADOZLffSIXciU38kreOCiKpUyUSpkpK1VRNdVQO6qlOupA9dSRGqiRKtREnaiFWqmNulA36k4ztI7W0xxtoI20QIs0oSXaRCu0RltoK21nVsyOWZgr88a8sygWw2JZHItnSSwza89a2SxbY1fswr7@OT2//jg9/TxfSzzdHx8fbm7M/3ecr58f/wI "Perl 5 – Try It Online") For some reason, the AN->ANT mapping isn't in Perl's list so I had to hardcode it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~435~~ ~~426~~ 422 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•4₆₆ÿ¸˜E¡´³*ιœýOóÖq₅;YpÂ-|ož®Ωg4∊₅“=à–ô9αA$ΔL,žÆE6óµQ£‚Ç\ΣN¬ÓóÑC∞\†ìвö—'‰ßÍ™¶HFü"í4·nÛZ0ø₅k{'¦Δ"¢h¦h)U–̱4ƒ¿¢ œ\a^»ãfzλ»Ï˜≠7>2e5Nl”SGed.iÉVó¸£₃l&C§ÚΣ6½+¢ å(₃L¦Ûā:vÊιOL†aëƵ₁fǝfVEtþΣ{õ-o¡ø4•u2ôD•46‰εcĆ2Zâæ¥ÙÚMт'•₂в£εN>.b«}˜ø.•1…¤θ30ËиʒÕf%γžBpéт(ĆVáä∞Kî%àôλ#KbɵC‘jÊα-zª+UΛGÙÀ"zFûÌιô#fиαL¸Λ¾o₄Ò{žwým«‚È3÷«εΩ)ØN÷U•u2ôD•Gò7¬ýà®vQ<ÑU•12в£ε€SN>.bý}˜áø.•Úù»ÔáÝâ|¹мœ4å)Çø{:вoÒaÿšмk*øW—Ã*‹Σc̉Δú¤š3rSwsJܲùη₅ĀPŽEf~:•u23S40∍£)˜DIk>è ``` [Try it online](https://tio.run/##TZF9T5JRGMb/71M0zRRNp0C6rNxK0UpCHdOWc21okqaFZekm1R4fDdF0TaBmgMWLUoa5eJOHENzui8e22M7wK5wvQof8p@1sZ@e@t3Ndv@uyzVpGJ8fL5SYuhfRcdoiDY1KKfgMFKUmJepZR3cj1IYGPz7j89ur9GciNr2xqng7Y3iM9d66JKZf81xHgkhvJKyx24wLzGC@peTgMrUhQaoDCXPJiZYSFTbQPt/hrs5M7P49wKYD9UhyHXPLUcuknvmCDL4fo8FY3jqrwQ0/pp/ANN0MRGlP2WoowTxWFJigyoRmsqK1TTH/iomMKnVPdI5YHlEXYusCy4n5f9PPVQFuHdvyyaZpL2@ae8YdNk1gdEo4UYUhemr7YSV/hZeFWyjVQ6Dx268TUSBH4Covtc1hjmT6jsGhB9CTF5UXr723rkOEF8ixsR6rRRkEoehHbSy2SXZX4WgUCS40VHNphhBChXXyC9@6pLNBCXJZLcQqzlKmjaZSir4t@KJXMW7gUoR2m6JrxrqT8ceGDtYYl1PzNGeydynUFxxCC2BFh9eKgBgEkWba6dxSrlOrk0tZjYTLWuEDfGwaZr0fISVUL3chinWWQrLaWFBYzksJ8lLdxeRkuu5qfR@4JRSt9OHVIU5Sl2J4GWyakB/9j6UG8TVSVQ4AO5gauYbOybNGeIXB531zBQK6CETwDgRcZEbtHvLcRekWZ0pHq1mNXgxUo9vZS3AaXBcdqsHQ0VQ/lnqgcS/VcyrDwGNYryXnwi3bUoO65eX72DvwUR4alRfEFqV/NGaxv2v/505n1zdy5QWFN0d91e6oD38rl3v6/) or [verify all test cases](https://tio.run/##TZNtbxRVFMff@ymaRYTyFGhXiKgk3dnd2e3OTKed2a2taFKUCoIWRSGhaJYFS0GIoa0G26LtLlSxSOzD0l1LS3JPFxObTJavMF@kzv7uG5Pm3/bec/4P59wZuTh06uzpnZ1DYbEcD0tj0Y@8ULXt2ZSaV6tqZV9Qb0zKRo@syE9fhKXv3h64IKWDV0cam@pp8PiTeDh@OzoNi7PvylxYnJTVt4KlrteDKetAY1PGUkdlRVV7VSUsTsvNk0HFUU9kMuK6Z4Tjv5wMi3PypLksz8Li1J6w@Jf8KnfDG2X1LJOW5zH5M67WPpeZwcNSizTOje5RC8FUTJXPqIUz7fmW2h21FH85oV6o8muNyZNDH6p1qQxfCdaj3z9sz4a35o6d6Dj9pnM@LD7wzNMfHzortwqRo1pkqHT9/BuG@k2mg8pRtbFfldvk0d7o1FILMrN17fgluR3Ue6zI4pAsvqyGpWvD/zwYLqS@ks2gMirVgyNqXmrxaGxfd8hqsjW@o1GEoPrR1ljHoJRlQT2Sn2XaflWKopXDUqm5rCpB1Tlx6JRa/GZ7VmqtmR8JiwvqYVDrPCzfN2v/TsiPw7uDlcZm4oI8flXauzVWkHl5GA0rJ093y5ysBuu7cqfklqoaYfH@p5HJpYNX1B/788GMGckVY1fSsi53grqs7hpu1oIlS9WCGbU5EpZuyMRoY/OybHymFlv7GO@UNbUYVIPH7XLfkbX8/7KYsnwsWtWGzKmnl3rfkXutyyMdOkJYeuK1YshGK8a8DiLTUo/GPhX9/0DKV1W9@bwxGZdH7XJTaqPHm8sjMjEkLxrzzefn9kmtP1q5XN8XFutB5SO505rclPytHjbmO7/0Ll/sllm1LPVgLVr8VtFtbKSGvz2Ov04vfjgcv6sq7duzyey5E/L7jtRibeHYRFtMNtT6zvuxrnTsQFus6z3QamFykL89MAn2gFmwFzTBPtAG@8E86IPwJOBJZEDYEglwAEyBurIbhC0BQwLdRBcIf6IAolvAQ1bXOCAnCRIlcJtD14DTgMeAIYe6QaWPK4PsBjyZXAttmA0mYxggJznNhpahe6k3cGWgm9F/Mw1Da5ExSWWSpEl4knCm4E/B6eHQZM4peFJMKcVM0jCk6UrDk0YxTaVJIlfnAk1Sm2iZ8CRBk8mY9Jq6lwmYJDJdEP8muibeTOZjsguTXBluM/AX0MroGdKbZftZTrIwZ9HKki6Lkyy9WdSzsHVz0o2Hbmq69eSZYY6TnN4vNTk4c7jK4dPCicUkLd6bhROLSgvnFgwWihZubb13GGzYbCpteGwc2tTbTM8mhQ2nDcOAvuXNpElhk9pmvzZzsPFv48fGp00um3qHEwdOh3QOul30OvA41Dv4d2Bz8OzgwWHvtu5lbj0wu6RzyeWi7qLl0uuS1IXNJZ2Loou6Sy4XV7109VHZB38fun36C6XegyEHg6Wz65ep3wkn/XjwOPHg92D26OrTt1R6mlN/HaTwyO6xWQ8Pg/qd6y4wpTeu69mCh3@Pr8Zjhh4pDNx6TMAnhU@NT43PrY8HHw8@nD66Ps59PPvw@yTyce7zcvJ05XHYpb8@nOdxmKc@j3oexQLzLFBZgLlA3n5mmMLPALeD9A72xz74Dw). **Explanation:** Step 1a: Create I/O pairs of all alpha-2 codes for which a single trailing letter has to be added for the alpha-3 conversion: ``` .•4₆₆ÿ¸˜E¡´³*ιœýOóÖq₅;YpÂ-|ož®Ωg4∊₅“=à–ô9αA$ΔL,žÆE6óµQ£‚Ç\ΣN¬ÓóÑC∞\†ìвö—'‰ßÍ™¶HFü"í4·nÛZ0ø₅k{'¦Δ"¢h¦h)U–̱4ƒ¿¢ œ\a^»ãfzλ»Ï˜≠7>2e5Nl”SGed.iÉVó¸£₃l&C§ÚΣ6½+¢ å(₃L¦Ûā:vÊιOL†aëƵ₁fǝfVEtþΣ{õ-o¡ø4• "# Push compressed string "dzaibwbrbfdmfrghitlvmdngrwknlclktzthtcugusalvgcugagmgiuzzmgrnihmhninmknlssazczlipsslchzwzaafarhkmnetcrdjerfjhtmwmlprumccnftjbebocoismhnpncnzphtkaskhdogugtnablwssosjvnyebtcafihuidirimjpkelbompashsdtwtovegelalsmctgttcystsgesbhbgcmcxjokimsmammnenopesmsygbviaumymurutlbviovakwmranqavcvubmecdeltnrrerosacihrluegggjekg" u # Uppercase it 2ô # Split it into parts of size 2 D # Duplicate this list of pairs •46‰εcĆ2Zâæ¥ÙÚMт'• '# Push compressed integer 5045888909142307005039435397419896531 ₂в # Convert it to base-26 as list: [21,8,2,6,7,1,4,1,9,0,3,10,12,17,6,4,0,16,5,9,8,2,0,1,3,1] £ # Split the duplicated pairs into parts of that size ε # Map over each list of string-pairs: N> # Push the 1-based map-index .b # Convert it to an uppercase alphabetic letter (1=A,2=B,...,26=Z) « # Append it to each string-pair in the current list }˜ # After the map: flatten ø # Create pairs of the two lists ``` [Try just this step, to see all I/O pairs of step 1a.](https://tio.run/##FZBtK0NxGMbf@xRa8mxpHROixPBiJomipYYNkZGHFx7qOJhNJLaUGeacTPIQtsNZs63ua5sXq3/zFf5fZP7qrruuF9f1uy7vqmtq3l0um7msSlzxiUOWjGLERneUoHg9S@aDSA8hjosVrhx0jC9Dadr25jP0yh5nJe4/EiqXI52IcjmIRBt7765iIXtjPgOfzYo46cOkcTmMQyfTHPSMoPA66@H@GyeXo3gufeCTy6EaLr/hFid8X6XPgT58m/Ai0dcSriaaYYiMha0airGQidQ5is3Vjf6nHdO7VDinLKkV@aDTNUkpaJ5NlhL/tBjhgWhrl8Xd4ljk8vVIv3vGPI/AmCAyBJCyt1jdQw8IM81K6QZSK3FfK1Q7xXCV223fwBFLDtkFogtPBZ0ru56fa8@YbQ0Zpm1Bb/LSHQxJzLZuQaL3fz6rqMD06ZzPMgEVMbrHJcKDv4qopnJFKX2QxnRHl3mKnnaKERjl8h8) Step 1b: Create I/O pairs of all alpha-2 codes for which a single middle letter has to be added for the alpha-3 conversion: ``` .•1…¤θ30ËиʒÕf%γžBpéт(ĆVáä∞Kî%àôλ#KbɵC‘jÊα-zª+UΛGÙÀ"zFûÌιô#fиαL¸Λ¾o₄Ò{žwým«‚È3÷«εΩ)ØN÷U• # Push compressed string "cfjmkzpkmfawlrlytdpnbimgmvmxsnaobdbsclcngnnutmbzsvfkgpmtpwsbwfaddkgqmemppgcgcdckkrmzplcvambbbnfoglgdiqpyptaeuyfmehagmqatgfgysrtntrtvskszsepfsc" u2ôD # Same as above (uppercase; split into pairs; duplicate) •Gò7¬ýà®vQ<ÑU• # Push compressed integer 5023299766197034891137684120 12в # Convert it to base-12 as list: [5,3,2,3,2,0,2,3,2,0,1,8,0,6,6,1,0,11,2,2,7,1,2,0,2,0] £ # Split the duplicated pairs into parts of that size ε # Map over each list of string-pairs: €S # Convert each string to a list N>.b # Same as above: get the uppercase letter based on the index ý # Join the inner list-pairs with this letter as delimiter }˜áø # Same as above, but `á` removes empty strings from the list ``` [Try just this step, to see all I/O pairs of step 1b.](https://tio.run/##AdMALP9vc2FiaWX//y7igKIx4oCmwqTOuDMww4vQuMqSw5VmJc6zxb5CcMOp0YIoxIZWw6HDpOKInkvDriXDoMO0zrsjS2LDicK1Q@KAmGrDis6xLXrCqitVzptHw5nDgCJ6RsO7w4zOucO0I2bQuM6xTMK4zpvCvm/igoTDknvFvnfDvW3Cq@KAmsOIM8O3wqvOtc6pKcOYTsO3VeKAonUyw7RE4oCiR8OyN8Ksw73DoMKudlE8w5FV4oCiMTLQssKjzrXigqxTTj4uYsO9fcucw6HDuP//) Step 1c: Create I/O pairs for all remaining alpha-2 to alpha-3 conversions (as a flattened list): ``` .•Úù»ÔáÝâ|¹мœ4å)Çø{:вoÒaÿšмk*øW—Ã*‹Σc̉Δú¤š3rSwsJܲùη₅ĀPŽEf~:• # Push compressed string "aqataaxalababihbjbenbyblreeestgssgsgwgnbieirlilisrkmcomkpprkkycymmomacpmspmrssrbsisvntfatfuaukrytmyt" u # Uppercase it 23S # Push [2,3] 40∍ # Extend it to size 40: [2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3] £ # Split the string into parts of that size ``` [Try just this step, to see the flattened list of all the I/O pairs of step 1c.](https://tio.run/##AX8AgP9vc2FiaWX//y7igKLDmsO5wrvDlMOhw53DonzCudC8xZM0w6Upw4fDuHs60LJvw5Jhw7/FodC8ayrDuFfigJTDgyrigLnOo2PDjOKAsM6Uw7rCpMWhM3JTd3NKw5zCssO5zrfigoXEgFDFvUVmfjrigKJ1MjNTNDDiiI3Co///) Step 2: Combine the results of the previous steps, and use them for the input to output conversion: ``` ) # Wrap the entire stack into a list ˜ # Flatten D # Duplicate this list Ik # Get the index of the input-string > # Increase this index by 1 è # And use it to index into the list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressions work. [Answer] # [R](https://www.r-project.org/), 74 bytes ``` function(c)`if`(c=="AN","ANT",countrycode::countrycode(c,"iso2c","iso3c")) ``` [Try it rdrr.io!](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(c)%60if%60(c%3D%3D%22AN%22%2C%22ANT%22%2Ccountrycode%3A%3Acountrycode(c%2C%22iso2c%22%2C%22iso3c%22))%0A%0Asapply(c(%22AF%22%2C%22AX%22%2C%22AL%22%2C%22DZ%22%2C%22AS%22%2C%22AD%22%2C%22AO%22%2C%22AI%22%2C%22AQ%22%2C%22AG%22%2C%22AR%22%2C%22AM%22%2C%22AW%22%2C%22AU%22%2C%22AT%22%2C%22AZ%22%2C%22BS%22%2C%22BH%22%2C%22BD%22%2C%22BB%22%2C%22BY%22%2C%22BE%22%2C%22BZ%22%2C%22BJ%22%2C%22BM%22%2C%22BT%22%2C%22BO%22%2C%22BA%22%2C%22BW%22%2C%22BV%22%2C%22BR%22%2C%22VG%22%2C%22IO%22%2C%22BN%22%2C%22BG%22%2C%22BF%22%2C%22BI%22%2C%22KH%22%2C%22CM%22%2C%22CA%22%2C%22CV%22%2C%22KY%22%2C%22CF%22%2C%22TD%22%2C%22CL%22%2C%22CN%22%2C%22HK%22%2C%22MO%22%2C%22CX%22%2C%22CC%22%2C%22CO%22%2C%22KM%22%2C%22CG%22%2C%22CD%22%2C%22CK%22%2C%22CR%22%2C%22CI%22%2C%22HR%22%2C%22CU%22%2C%22CY%22%2C%22CZ%22%2C%22DK%22%2C%22DJ%22%2C%22DM%22%2C%22DO%22%2C%22EC%22%2C%22EG%22%2C%22SV%22%2C%22GQ%22%2C%22ER%22%2C%22EE%22%2C%22ET%22%2C%22FK%22%2C%22FO%22%2C%22FJ%22%2C%22FI%22%2C%22FR%22%2C%22GF%22%2C%22PF%22%2C%22TF%22%2C%22GA%22%2C%22GM%22%2C%22GE%22%2C%22DE%22%2C%22GH%22%2C%22GI%22%2C%22GR%22%2C%22GL%22%2C%22GD%22%2C%22GP%22%2C%22GU%22%2C%22GT%22%2C%22GG%22%2C%22GN%22%2C%22GW%22%2C%22GY%22%2C%22HT%22%2C%22HM%22%2C%22VA%22%2C%22HN%22%2C%22HU%22%2C%22IS%22%2C%22IN%22%2C%22ID%22%2C%22IR%22%2C%22IQ%22%2C%22IE%22%2C%22IM%22%2C%22IL%22%2C%22IT%22%2C%22JM%22%2C%22JP%22%2C%22JE%22%2C%22JO%22%2C%22KZ%22%2C%22KE%22%2C%22KI%22%2C%22KP%22%2C%22KR%22%2C%22KW%22%2C%22KG%22%2C%22LA%22%2C%22LV%22%2C%22LB%22%2C%22LS%22%2C%22LR%22%2C%22LY%22%2C%22LI%22%2C%22LT%22%2C%22LU%22%2C%22MK%22%2C%22MG%22%2C%22MW%22%2C%22MY%22%2C%22MV%22%2C%22ML%22%2C%22MT%22%2C%22MH%22%2C%22MQ%22%2C%22MR%22%2C%22MU%22%2C%22YT%22%2C%22MX%22%2C%22FM%22%2C%22MD%22%2C%22MC%22%2C%22MN%22%2C%22ME%22%2C%22MS%22%2C%22MA%22%2C%22MZ%22%2C%22MM%22%2C%22NA%22%2C%22NR%22%2C%22NP%22%2C%22NL%22%2C%22AN%22%2C%22NC%22%2C%22NZ%22%2C%22NI%22%2C%22NE%22%2C%22NG%22%2C%22NU%22%2C%22NF%22%2C%22MP%22%2C%22NO%22%2C%22OM%22%2C%22PK%22%2C%22PW%22%2C%22PS%22%2C%22PA%22%2C%22PG%22%2C%22PY%22%2C%22PE%22%2C%22PH%22%2C%22PN%22%2C%22PL%22%2C%22PT%22%2C%22PR%22%2C%22QA%22%2C%22RE%22%2C%22RO%22%2C%22RU%22%2C%22RW%22%2C%22BL%22%2C%22SH%22%2C%22KN%22%2C%22LC%22%2C%22MF%22%2C%22PM%22%2C%22VC%22%2C%22WS%22%2C%22SM%22%2C%22ST%22%2C%22SA%22%2C%22SN%22%2C%22RS%22%2C%22SC%22%2C%22SL%22%2C%22SG%22%2C%22SK%22%2C%22SI%22%2C%22SB%22%2C%22SO%22%2C%22ZA%22%2C%22GS%22%2C%22SS%22%2C%22ES%22%2C%22LK%22%2C%22SD%22%2C%22SR%22%2C%22SJ%22%2C%22SZ%22%2C%22SE%22%2C%22CH%22%2C%22SY%22%2C%22TW%22%2C%22TJ%22%2C%22TZ%22%2C%22TH%22%2C%22TL%22%2C%22TG%22%2C%22TK%22%2C%22TO%22%2C%22TT%22%2C%22TN%22%2C%22TR%22%2C%22TM%22%2C%22TC%22%2C%22TV%22%2C%22UG%22%2C%22UA%22%2C%22AE%22%2C%22GB%22%2C%22US%22%2C%22UM%22%2C%22UY%22%2C%22UZ%22%2C%22VU%22%2C%22VE%22%2C%22VN%22%2C%22VI%22%2C%22WF%22%2C%22EH%22%2C%22YE%22%2C%22ZM%22%2C%22ZW%22)%2Cf)) [Answer] # Python 1779 bytes ``` a=' AF AFG AX ALA AL ALB DZ DZA AS ASM AD AND AO AGO AI AIA AQ ATA AG ATG AR ARG AM ARM AW ABW AU AUS AT AUT AZ AZE BS BHS BH BHR BD BGD BB BRB BY BLR BE BEL BZ BLZ BJ BEN BM BMU BT BTN BO BOL BA BIH BW BWA BV BVT BR BRA VG VGB IO IOT BN BRN BG BGR BF BFA BI BDI KH KHM CM CMR CA CAN CV CPV KY CYM CF CAF TD TCD CL CHL CN CHN HK HKG MO MAC CX CXR CC CCK CO COL KM COM CG COG CD COD CK COK CR CRI CI CIV HR HRV CU CUB CY CYP CZ CZE DK DNK DJ DJI DM DMA DO DOM EC ECU EG EGY SV SLV GQ GNQ ER ERI EE EST ET ETH FK FLK FO FRO FJ FJI FI FIN FR FRA GF GUF PF PYF TF ATF GA GAB GM GMB GE GEO DE DEU GH GHA GI GIB GR GRC GL GRL GD GRD GP GLP GU GUM GT GTM GG GGY GN GIN GW GNB GY GUY HT HTI HM HMD VA VAT HN HND HU HUN IS ISL IN IND ID IDN IR IRN IQ IRQ IE IRL IM IMN IL ISR IT ITA JM JAM JP JPN JE JEY JO JOR KZ KAZ KE KEN KI KIR KP PRK KR KOR KW KWT KG KGZ LA LAO LV LVA LB LBN LS LSO LR LBR LY LBY LI LIE LT LTU LU LUX MK MKD MG MDG MW MWI MY MYS MV MDV ML MLI MT MLT MH MHL MQ MTQ MR MRT MU MUS YT MYT MX MEX FM FSM MD MDA MC MCO MN MNG ME MNE MS MSR MA MAR MZ MOZ MM MMR NA NAM NR NRU NP NPL NL NLD AN ANT NC NCL NZ NZL NI NIC NE NER NG NGA NU NIU NF NFK MP MNP NO NOR OM OMN PK PAK PW PLW PS PSE PA PAN PG PNG PY PRY PE PER PH PHL PN PCN PL POL PT PRT PR PRI QA QAT RE REU RO ROU RU RUS RW RWA BL BLM SH SHN KN KNA LC LCA MF MAF PM SPM VC VCT WS WSM SM SMR ST STP SA SAU SN SEN RS SRB SC SYC SL SLE SG SGP SK SVK SI SVN SB SLB SO SOM ZA ZAF GS SGS SS SSD ES ESP LK LKA SD SDN SR SUR SJ SJM SZ SWZ SE SWE CH CHE SY SYR TW TWN TJ TJK TZ TZA TH THA TL TLS TG TGO TK TKL TO TON TT TTO TN TUN TR TUR TM TKM TC TCA TV TUV UG UGA UA UKR AE ARE GB GBR US USA UM UMI UY URY UZ UZB VU VUT VE VEN VN VNM VI VIR WF WLF EH ESH YE YEM ZM ZMB ZW ZWE' z=lambda b:a[a.find(" "+b)+4:a.find(" "+b)+7] ``` Not sure what to do with the mass of data. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 420 bytes ``` «⟑``‟Ḃȯ†√¦∑iRṫΠʁǓ₴5]p#4Ṅl}3ẋ¶T+⟑V]ḭr≤ṁǔ A»cP⌐kẋṠ†⟇Ǔ≈ɽ⟩›ṪwSʀ₇⌊Ǔ∇•Xwð⇩I‡ṅfβ℅₍ṗµ∆€¾aǍ⟑Ȧ2⋏$λ⁺]/|f₁Pa⟨,₁,h¨ṁ₌ε⟑‹İ⟨Nṫw%yĖ⁼*>₈˹ȯU÷s¬)∨ʀ0ŀƈ½)(m-Ẋ ǓḂ⟩[0e•₂↲S⟇Ġj⟨^ɖg[⌐₁⋏żo:ẎRʁ⌐ð%⇧↓Y*?* †8„S|⁽l3√⁺⟑«⇧2ẇ:»⟑⟇βE'ċ¬$≠∪₀↳↲æMf»₄τẇkA¨£vJfZ«ƛ¤‛H∧λŻJ@±*dCẋ°4£Mgċ ≥ƒX¢ǎd≤ǔ₈b¢&Ẋ≈•ġ.ẎAl>₅j¨∵½↳Ŀa>€¼₌Rǔb*JA⌐Ḃ∵Ḣ3\⌈|ẋ;Π1₆›Ẇ∧≬₆ETh□ʀ≬¨«⇧2ẇ:»½ǒ÷₇Π≤¶:ɽq∇¨»12τẇkAZƛ÷$f$vj;fZ«↲↵˝≥꘍≠}ĊKṫ⟑ɖhṪ⁺|oI3⌈%‟ṙK/i⁺!ṅȮiȧS'₌βP⅛‛ṙ∧6ƈ;7↔⋎¡↵G]ḟɾḋ†*↑o«⇧23f20ẋfẇWf:⁰ḟ›i ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq+KfkWBg4oCf4biCyK/igKDiiJrCpuKIkWlS4bmrzqDKgceT4oK0NV1wIzThuYRsfTPhuovCtlQr4p+RVl3huK1y4omk4bmBx5RcbkHCu2NQ4oyQa+G6i+G5oOKAoOKfh8eT4omIyb3in6nigLrhuap3U8qA4oKH4oyKx5PiiIfigKJYd8Ow4oepSeKAoeG5hWbOsuKEheKCjeG5l8K14oiG4oKswr5hx43in5HIpjLii48kzrvigbpdL3xm4oKBUGHin6gs4oKBLGjCqOG5geKCjM614p+R4oC5xLDin6hO4bmrdyV5xJbigbwqPuKCiMSWwrnIr1XDt3PCrCniiKjKgDDFgMaIwr0pKG0t4bqKIMeT4biC4p+pWzBl4oCi4oKC4oayU+Kfh8SgauKfqF7Jlmdb4oyQ4oKB4ouPxbxvOuG6jlLKgeKMkMOwJeKHp+KGk1kqPyog4oCgOOKAnlN84oG9bDPiiJrigbrin5HCq+KHpzLhuoc6wrvin5Hin4fOskUnxIvCrCTiiaDiiKrigoDihrPihrLDpk1mwrvigoTPhOG6h2tBwqjCo3ZKZlrCq8abwqTigJtI4oinzrvFu0pAwrEqZEPhuovCsDTCo01nxIsg4omlxpJYwqLHjmTiiaTHlOKCiGLCoibhuoriiYjigKLEoS7huo5BbD7igoVqwqjiiLXCveKGs8S/YT7igqzCvOKCjFLHlGIqSkHijJDhuILiiLXhuKIzXFzijIh84bqLO86gMeKChuKAuuG6huKIp+KJrOKChkVUaOKWocqA4omswqjCq+KHpzLhuoc6wrvCvceSw7figofOoOKJpMK2Osm9ceKIh8KowrsxMs+E4bqHa0FaxpvDtyRmJHZqO2ZawqvihrLihrXElsKv4oml6piN4omgfcSKS+G5q+KfkcmWaOG5quKBunxvSTPijIgl4oCf4bmZSy9p4oG6IeG5hciuacinUyfigozOslDihZvigJvhuZniiKc2xog7N+KGlOKLjsKh4oa1R13huJ/JvuG4i+KAoCrihpFvwqvih6cyM2YyMOG6i2bhuodXZjrigbDhuJ/igLppIiwiIiwiS1AiXQ==) or [Verify all test cases (takes a while, but doesn't time out)](https://vyxal.pythonanywhere.com/#WyJqVCIsIsab4oaSIiwiwqvin5FgYOKAn+G4gsiv4oCg4oiawqbiiJFpUuG5q86gyoHHk+KCtDVdcCM04bmEbH0z4bqLwrZUK+KfkVZd4bitcuKJpOG5gceUXG5BwrtjUOKMkGvhuovhuaDigKDin4fHk+KJiMm94p+p4oC64bmqd1PKgOKCh+KMiseT4oiH4oCiWHfDsOKHqUnigKHhuYVmzrLihIXigo3huZfCteKIhuKCrMK+YceN4p+RyKYy4ouPJM674oG6XS98ZuKCgVBh4p+oLOKCgSxowqjhuYHigozOteKfkeKAucSw4p+oTuG5q3clecSW4oG8Kj7igojElsK5yK9Vw7dzwqwp4oioyoAwxYDGiMK9KShtLeG6iiDHk+G4guKfqVswZeKAouKCguKGslPin4fEoGrin6heyZZnW+KMkOKCgeKLj8W8bzrhuo5SyoHijJDDsCXih6fihpNZKj8qIOKAoDjigJ5TfOKBvWwz4oia4oG64p+Rwqvih6cy4bqHOsK74p+R4p+HzrJFJ8SLwqwk4omg4oiq4oKA4oaz4oayw6ZNZsK74oKEz4ThuodrQcKowqN2SmZawqvGm8Kk4oCbSOKIp867xbtKQMKxKmRD4bqLwrA0wqNNZ8SLIOKJpcaSWMKix45k4omkx5TigohiwqIm4bqK4omI4oCixKEu4bqOQWw+4oKFasKo4oi1wr3ihrPEv2E+4oKswrzigoxSx5RiKkpB4oyQ4biC4oi14biiM1xc4oyIfOG6izvOoDHigobigLrhuobiiKfiiazigoZFVGjilqHKgOKJrMKowqvih6cy4bqHOsK7wr3HksO34oKHzqDiiaTCtjrJvXHiiIfCqMK7MTLPhOG6h2tBWsabw7ckZiR2ajtmWsKr4oay4oa1xJbCr+KJpeqYjeKJoH3Eikvhuavin5HJlmjhuarigbp8b0kz4oyIJeKAn+G5mUsvaeKBuiHhuYXIrmnIp1Mn4oKMzrJQ4oWb4oCb4bmZ4oinNsaIOzfihpTii47CoeKGtUdd4bifyb7huIvigKAq4oaRb8Kr4oenMjNmMjDhuotm4bqHV2Y64oaQ4bif4oC6aSIsIjtaxptgID0+IGBqIiwiW1wiQUZcIiwgXCJBWFwiLCBcIkFMXCIsIFwiRFpcIiwgXCJBU1wiLCBcIkFEXCIsIFwiQU9cIiwgXCJBSVwiLCBcIkFRXCIsIFwiQUdcIiwgXCJBUlwiLCBcIkFNXCIsIFwiQVdcIiwgXCJBVVwiLCBcIkFUXCIsIFwiQVpcIiwgXCJCU1wiLCBcIkJIXCIsIFwiQkRcIiwgXCJCQlwiLCBcIkJZXCIsIFwiQkVcIiwgXCJCWlwiLCBcIkJKXCIsIFwiQk1cIiwgXCJCVFwiLCBcIkJPXCIsIFwiQkFcIiwgXCJCV1wiLCBcIkJWXCIsIFwiQlJcIiwgXCJWR1wiLCBcIklPXCIsIFwiQk5cIiwgXCJCR1wiLCBcIkJGXCIsIFwiQklcIiwgXCJLSFwiLCBcIkNNXCIsIFwiQ0FcIiwgXCJDVlwiLCBcIktZXCIsIFwiQ0ZcIiwgXCJURFwiLCBcIkNMXCIsIFwiQ05cIiwgXCJIS1wiLCBcIk1PXCIsIFwiQ1hcIiwgXCJDQ1wiLCBcIkNPXCIsIFwiS01cIiwgXCJDR1wiLCBcIkNEXCIsIFwiQ0tcIiwgXCJDUlwiLCBcIkNJXCIsIFwiSFJcIiwgXCJDVVwiLCBcIkNZXCIsIFwiQ1pcIiwgXCJES1wiLCBcIkRKXCIsIFwiRE1cIiwgXCJET1wiLCBcIkVDXCIsIFwiRUdcIiwgXCJTVlwiLCBcIkdRXCIsIFwiRVJcIiwgXCJFRVwiLCBcIkVUXCIsIFwiRktcIiwgXCJGT1wiLCBcIkZKXCIsIFwiRklcIiwgXCJGUlwiLCBcIkdGXCIsIFwiUEZcIiwgXCJURlwiLCBcIkdBXCIsIFwiR01cIiwgXCJHRVwiLCBcIkRFXCIsIFwiR0hcIiwgXCJHSVwiLCBcIkdSXCIsIFwiR0xcIiwgXCJHRFwiLCBcIkdQXCIsIFwiR1VcIiwgXCJHVFwiLCBcIkdHXCIsIFwiR05cIiwgXCJHV1wiLCBcIkdZXCIsIFwiSFRcIiwgXCJITVwiLCBcIlZBXCIsIFwiSE5cIiwgXCJIVVwiLCBcIklTXCIsIFwiSU5cIiwgXCJJRFwiLCBcIklSXCIsIFwiSVFcIiwgXCJJRVwiLCBcIklNXCIsIFwiSUxcIiwgXCJJVFwiLCBcIkpNXCIsIFwiSlBcIiwgXCJKRVwiLCBcIkpPXCIsIFwiS1pcIiwgXCJLRVwiLCBcIktJXCIsIFwiS1BcIiwgXCJLUlwiLCBcIktXXCIsIFwiS0dcIiwgXCJMQVwiLCBcIkxWXCIsIFwiTEJcIiwgXCJMU1wiLCBcIkxSXCIsIFwiTFlcIiwgXCJMSVwiLCBcIkxUXCIsIFwiTFVcIiwgXCJNS1wiLCBcIk1HXCIsIFwiTVdcIiwgXCJNWVwiLCBcIk1WXCIsIFwiTUxcIiwgXCJNVFwiLCBcIk1IXCIsIFwiTVFcIiwgXCJNUlwiLCBcIk1VXCIsIFwiWVRcIiwgXCJNWFwiLCBcIkZNXCIsIFwiTURcIiwgXCJNQ1wiLCBcIk1OXCIsIFwiTUVcIiwgXCJNU1wiLCBcIk1BXCIsIFwiTVpcIiwgXCJNTVwiLCBcIk5BXCIsIFwiTlJcIiwgXCJOUFwiLCBcIk5MXCIsIFwiQU5cIiwgXCJOQ1wiLCBcIk5aXCIsIFwiTklcIiwgXCJORVwiLCBcIk5HXCIsIFwiTlVcIiwgXCJORlwiLCBcIk1QXCIsIFwiTk9cIiwgXCJPTVwiLCBcIlBLXCIsIFwiUFdcIiwgXCJQU1wiLCBcIlBBXCIsIFwiUEdcIiwgXCJQWVwiLCBcIlBFXCIsIFwiUEhcIiwgXCJQTlwiLCBcIlBMXCIsIFwiUFRcIiwgXCJQUlwiLCBcIlFBXCIsIFwiUkVcIiwgXCJST1wiLCBcIlJVXCIsIFwiUldcIiwgXCJCTFwiLCBcIlNIXCIsIFwiS05cIiwgXCJMQ1wiLCBcIk1GXCIsIFwiUE1cIiwgXCJWQ1wiLCBcIldTXCIsIFwiU01cIiwgXCJTVFwiLCBcIlNBXCIsIFwiU05cIiwgXCJSU1wiLCBcIlNDXCIsIFwiU0xcIiwgXCJTR1wiLCBcIlNLXCIsIFwiU0lcIiwgXCJTQlwiLCBcIlNPXCIsIFwiWkFcIiwgXCJHU1wiLCBcIlNTXCIsIFwiRVNcIiwgXCJMS1wiLCBcIlNEXCIsIFwiU1JcIiwgXCJTSlwiLCBcIlNaXCIsIFwiU0VcIiwgXCJDSFwiLCBcIlNZXCIsIFwiVFdcIiwgXCJUSlwiLCBcIlRaXCIsIFwiVEhcIiwgXCJUTFwiLCBcIlRHXCIsIFwiVEtcIiwgXCJUT1wiLCBcIlRUXCIsIFwiVE5cIiwgXCJUUlwiLCBcIlRNXCIsIFwiVENcIiwgXCJUVlwiLCBcIlVHXCIsIFwiVUFcIiwgXCJBRVwiLCBcIkdCXCIsIFwiVVNcIiwgXCJVTVwiLCBcIlVZXCIsIFwiVVpcIiwgXCJWVVwiLCBcIlZFXCIsIFwiVk5cIiwgXCJWSVwiLCBcIldGXCIsIFwiRUhcIiwgXCJZRVwiLCBcIlpNXCIsIFwiWldcIl0iXQ==) Messy port of 05AB1E. ## How? ``` «⟑``‟Ḃȯ†√¦∑iRṫΠʁǓ₴5]p#4Ṅl}3ẋ¶T+⟑V]ḭr≤ṁǔ A»cP⌐kẋṠ†⟇Ǔ≈ɽ⟩›ṪwSʀ₇⌊Ǔ∇•Xwð⇩I‡ṅfβ℅₍ṗµ∆€¾aǍ⟑Ȧ2⋏$λ⁺]/|f₁Pa⟨,₁,h¨ṁ₌ε⟑‹İ⟨Nṫw%yĖ⁼*>₈˹ȯU÷s¬)∨ʀ0ŀƈ½)(m-Ẋ ǓḂ⟩[0e•₂↲S⟇Ġj⟨^ɖg[⌐₁⋏żo:ẎRʁ⌐ð%⇧↓Y*?* †8„S|⁽l3√⁺⟑« # Push compressed string "dzaibwbrbfdmfrghitlvmdngrwknlclktzthtcugusalvgcugagmgiuzzmgrnihmhninmknlssazczlipsslchzwzaafarhkmnetcrdjerfjhtmwmlprumccnftjbebocoismhnpncnzphtkaskhdogugtnablwssosjvnyebtcafihuidirimjpkelbompashsdtwtovegelalsmctgttcystsgesbhbgcmcxjokimsmammnenopesmsygbviaumymurutlbviovakwmranqavcvubmecdeltnrrerosacihrluegggjekg" ⇧ # Uppercase 2ẇ # Split into chunks of two : # Duplicate »⟑⟇βE'ċ¬$≠∪₀↳↲æMf» # Push compressed integer 5045888909142307005039435397419896531 ₄τ # Convert to base-26 as a list: [21,8,2,6,7,1,4,1,9,0,3,10,12,17,6,4,0,16,5,9,8,2,0,1,3,1] ẇ # Split the string into chunks of that size: [["DZ", "AI", ..., "US"], ["AL", "VG", ..., "ZM"], ["GR", "NI"], ..., ["KG"]] kA # Push the uppercase alphabet ¨£vJ # Zip the list with the alphabet, and for each, append the corresponding letter to each: # [["DZA", "AIA", ..., "USA"], ["ALB", "VGB", ..., "ZMB"], ["GRC", "NIC"], ..., ["KGZ"]] f # Flatten Z # Zip the ["DZ", "AI", "BW", ...] list with this «ƛ¤‛H∧λŻJ@±*dCẋ°4£Mgċ ≥ƒX¢ǎd≤ǔ₈b¢&Ẋ≈•ġ.ẎAl>₅j¨∵½↳Ŀa>€¼₌Rǔb*JA⌐Ḃ∵Ḣ3\⌈|ẋ;Π1₆›Ẇ∧≬₆ETh□ʀ≬¨« # Push compressed string "cfjmkzpkmfawlrlytdpnbimgmvmxsnaobdbsclcngnnutmbzsvfkgpmtpwsbwfaddkgqmemppgcgcdckkrmzplcvambbbnfoglgdiqpyptaeuyfmehagmqatgfgysrtntrtvskszsepfsc" ⇧2ẇ # Uppercase and split into chunks of two : # Duplicate »½ǒ÷₇Π≤¶:ɽq∇¨» # Push compressed integer 5023299766197034891137684120 12τ # Convert to base 12 as a list: [5,3,2,3,2,0,2,3,2,0,1,8,0,6,6,1,0,11,2,2,7,1,2,0,2,0] ẇ # Split the list into chunks of that size: [["CF", "JM", "KZ", "PK", "MF"], ["AW", "LR", "LY"], ..., ["PF", "SC"], []] kAZ # Zip with the uppercase alphabet ƛ÷$f$vj; # Map, and for each, insert the letter between each string: [["CAF", "JAM", "KAZ", "PAK", "MAF"], ..., ["PYF", "SYC"], []] fZ # Flatten and zip the ["CF", "JM", ..., "SC"] list with this «↲↵˝≥꘍≠}ĊKṫ⟑ɖhṪ⁺|oI3⌈%‟ṙK/i⁺!ṅȮiȧS'₌βP⅛‛ṙ∧6ƈ;7↔⋎¡↵G]ḟɾḋ†*↑o« # Push compressed string "aqataaxalababihbjbenbyblreeestgssgsgwgnbieirlilisrkmcomkpprkkycymmomacpmspmrssrbsisvntfatfuaukrytmyt" ⇧ # Uppercase 23f # Push list [2, 3] 20ẋf # Repeat it twenty times: [2, 3, 2, 3, 2, 3, ..., 2, 3] ẇ # Split the string into chunks of that size: ["AQ", "ATA", "AX", ..., "YT", "MYT"] W # Wrap the stack into a list f # Flatten : # Duplicate ⁰ḟ # Find the index of the input in it › # Increment i # Index into the list ``` [Answer] # C - 1324 Bytes ``` char*c="AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE";f(char* i){for(;*c;c+=5)!strncmp(c, i,2)&&printf("%c%c%c",*(c+2),*(c+3),*(c+4));} ``` **Ungolfed** ``` char*c = "AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE"; f(char* i) { for(; *c; c += 5) !strncmp(c, i, 2) && printf("%c%c%c", *(c + 2), *(c + 3), *(c + 4)); } ``` **Explanation** A function that receives a character string with an Alpha-2 code and converts it to Alpha-3 using a "raw" list which contains the Alpha-2 codes followed by their Alpha-3 counterpart every five(5) characters; the function looks for the given code within the list and if it is found its counterpart is displayed. Tested on GCC, generates some warnings if not compiled with std=c89. ## C99 - 1296 Bytes (By @ceilingcat) ``` f(int*i){for(char*c="AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE";*c;c+=5)write(!strncmp(c,i,2),c+2,3);} ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 111 bytes ``` Switch[#,"HM","HMD","AN","ANT","PS","PSE",_,Association[#@"CountryCode"->#@"UNCode"&/@EntityList@"Country"]@#]& ``` Don't [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g8syQ5I1pZR8nDVwlEuABJRz8wEQIkA4LBhKuSTryOY3FxfnImUGt@XrSyg5JzfmleSVGlc35KqpKuHVAg1A/MVtN3cM0rySyp9MksLoErU4p1UI5V@x9QlJlXEp2m71Ct5OKqBLUVbB/YptBgpdrY/wA "Wolfram Language (Mathematica) – Try It Online") [Try in the Wolfram Cloud!](https://www.wolframcloud.com/obj/4ec45ac9-dd2f-4a24-8c75-de1e61660872) --- Explanation: `Switch[#,"HM","HMD","AN","ANT","PS","PSE",` If our input is equal to one of the three countries not in the Mathematica database, return the correct code. `_,` Otherwise `Association[#@"CountryCode"->#@"UNCode"&/@EntityList@"Country"]` Create an association between the two-letter and three-letter codes of each country `@#]` and find the value matching the input. [Answer] # C, 216+554+1=771 bytes ``` #include<stdio.h> #define G d=getc(f);w=d&31|64 FILE*f;char c,d,r[4],y,w;char*z(a,b){for(f=fopen("f","r");;){G;c=d/4&56;y=w;G;c|=d>>5&7;*r=a;r[1]=r[2]=b;r[c>26?1:2]=c&31|64;if(!c)fgets(r,4,f);if(a==y&b==w)return r;}} ``` It requires this file with the name "f" in the same directory, shown here as a hex dump. You can use `cut -c 11-58 "data.txt" | xxd -r -p > f` to recreate the file. It should have 554 bytes. ``` 00000000 01 e6 01 18 41 4c 41 01 4c 04 3a 21 b3 a1 c4 81 |....ALA.L.:!....| 00000010 ef 01 29 01 11 41 54 41 c1 87 01 f2 c1 4d 81 57 |..)..ATA.....M.W| 00000020 41 75 c1 b4 01 ba a2 13 42 48 82 e4 c2 42 02 19 |Au......BH...B..| 00000030 42 4c 52 22 85 a2 9a 02 0a 42 45 4e 42 ad 22 d4 |BLR".....BENB.".| 00000040 22 8f 02 01 42 49 48 02 37 42 96 02 32 16 47 49 |"...BIH.7B..2.GI| 00000050 8f c2 4e 42 47 02 26 82 89 2b a8 43 4d 23 c1 c3 |..NBG.&..+.CM#..| 00000060 16 0b 19 43 59 4d 83 26 94 64 a3 0c a3 0e 08 eb |...CYM.&.d......| 00000070 0d 0f 4d 41 43 43 58 23 63 23 8f 0b 0d 43 4f 4d |..MACCX#c#...COM| 00000080 a3 e7 a3 e4 a3 eb 23 32 43 c9 48 d2 03 55 43 19 |......#2C.H..UC.| 00000090 03 ba a4 cb 24 2a 04 2d 24 af 45 a3 65 27 b3 96 |....$*.-$.E.e'..| 000000a0 a7 d1 25 32 05 05 45 53 54 25 14 a6 8b c6 4f 26 |..%2..EST%....O&| 000000b0 2a 26 c9 06 32 c7 a6 f0 26 14 06 41 54 46 07 41 |*&..2...&..ATF.A| 000000c0 07 4d 27 e5 44 a5 07 28 07 49 07 72 c7 4c c7 44 |.M'.D..(.I.r.L.D| 000000d0 a7 90 27 b5 27 b4 67 27 a7 2e 07 17 47 4e 42 c7 |..'.'.g'....GNB.| 000000e0 b9 28 34 08 8d 56 81 08 8e 28 d5 29 93 09 8e 29 |.(4..V...(.)...)| 000000f0 c4 29 d2 c9 51 09 05 49 52 4c 29 cd 09 0c 49 53 |.)..Q..IRL)...IS| 00000100 52 09 34 8a 2d 2a d0 6a 25 4a 4f 8b 3a 2b c5 4b |R.4.-*.j%JO.:+.K| 00000110 49 0b 10 50 52 4b ab f2 4b 97 6b 47 2c e1 0c 36 |I..PRK..K.kG,..6| 00000120 2c c2 2c f3 8c 52 8c 59 0c a9 4c b4 6c 15 0d 8b |,.,..R.Y..L.l...| 00000130 8d 87 2d 37 4d 79 8d 96 2d 2c ad 94 2d 88 cd 91 |..-7My..-,..-...| 00000140 4d 92 4d 75 19 14 4d 59 54 8d b8 c6 6d 0d 24 2d |M.Mu..MYT...m.$-| 00000150 e3 0d ee ad c5 4d 53 4d 41 ad fa 4d 4d 2e a1 4e |.....MSMA..MM..N| 00000160 b2 2e 90 0e 8c 41 8e 2e 83 2e 9a 0e 69 4e 45 0e |.....A......iNE.| 00000170 27 ae 35 2e 66 ad d0 4e 4f 2f cd 90 2b b0 97 10 |'.5.f..NO/..+...| 00000180 b3 30 c1 b0 c7 d0 59 50 45 30 88 90 6e b0 ec d0 |.0....YPE0..n...| 00000190 54 30 32 51 81 52 a5 52 af 52 75 12 37 22 ac 33 |T02Q.R.R.Ru.7".3| 000001a0 c8 0b 2e 0c 23 8d 26 10 0d 53 50 4d 56 83 37 b3 |....#.&..SPMV.7.| 000001b0 53 4d 53 14 53 a1 93 ae 12 13 53 52 42 f3 23 13 |SMS.S.....SRB.#.| 000001c0 ac 53 07 d3 cb 13 09 53 56 4e b3 82 33 af 1a c1 |.S.....SVN..3...| 000001d0 07 13 53 47 53 13 93 45 13 0c 2b 33 c4 d3 b2 33 |..SGS..E..+3...3| 000001e0 aa d3 fa d3 e5 03 a8 53 59 34 d7 34 6a 14 3a 14 |.......SY4.4j.:.| 000001f0 28 54 6c 34 e7 34 8b 34 cf 34 f4 d4 ae d4 b2 b4 |(Tl4.4.4.4......| 00000200 6d 14 23 d4 b6 15 27 15 01 55 4b 52 c1 45 47 42 |m.#...'..UKR.EGB| 00000210 15 33 35 2d d5 59 15 5a 56 95 36 c5 36 ae 56 49 |.35-.Y.ZV.6.6.VI| 00000220 b7 86 c5 68 39 a5 1a 4d 1a b7 |...h9..M..| 0000022a ``` The function takes the Alpha-2 code as two separate characters, which must be capitalized, and returns the capitalized Alpha-3 code. I don't know of an online compiler that allows you to include binary files like this, so no link, unfortunately. #### Explanation: Since we're only dealing with capital letters, we can use only the lower five bits to store a character. The basic strategy is to store the Alpha-2 codes in the file, and use the bits we save to describe how to create the Alpha-3 code; then, the program will search for the Alpha-2 code and follow the instructions. The instruction format is simple. We have six instruction bits. The lower five bits store a 5-bit letter code which can be converted to ASCII with `&31|64`. If the high bit is zero, the letter is added to the end of the code. If it's one, the letter is inserted in the middle. If the instruction bits are all zero, the file stores the complete Alpha-3 code in the next 3 bytes of the file (these are visible in the hex dump). Of the 247 conversions, 156 append a character to the end, 71 insert a character in the middle, 4 prepend a character to the beginning, and 16 conversions are replacements, which are anything not included in the other categories. Inserts and appends only use two bytes in the file, while the others use five; (156+71)\*2+(4+16)\*5=554 bytes. Ungolfed version: ``` #include <stdio.h> FILE* f; char c,d,r[4],y,w; char* z(a,b){ for(f=fopen("f","r");;){ // get first character d=getc(f); w=d&31|64; c=d/4&56; y=w; // get second character d=getc(f); w=d&31|64; c|=d>>5&7; // c now holds the instruction // prepare return string for inserts/appends r[0]=a; r[1]=r[2]=b; r[c>26?1:2]=c&31|64; // insert or append if(!c) // replace fgets(r,4,f); if(a==y&b==w) return r; } } ``` ]
[Question] [ Your task is to take an array of numbers and a real number and return the value at that point in the array. Arrays start at \$\pi\$ and are counted in \$\pi\$ intervals. Thing is, we're actually going to interpolate between elements given the "index". As an example: ``` Index: 1π 2π 3π 4π 5π 6π Array: [ 1.1, 1.3, 6.9, 4.2, 1.3, 3.7 ] ``` Because it's \$\pi\$, we have to do the obligatory trigonometry, so we'll be using cosine interpolation using the following formula: \${\cos(i \mod \pi) + 1 \over 2} \* (\alpha - \beta) + \beta\$ where: * \$i\$ is the input "index" * \$\alpha\$ is the value of the element immediately before the "index" * \$\beta\$ is the value of the element immediately after the "index" * \$\cos\$ takes its angle in radians # Example Given [1.3, 3.7, 6.9], 5.3: Index 5.3 is between \$1\pi\$ and \$2\pi\$, so 1.3 will be used for `before` and 3.7 will be used for `after`. Putting it into the formula, we get: \${\cos(5.3 \mod \pi) + 1 \over 2} \* (1.3 - 3.7) + 3.7\$ Which comes out to 3.165 # Notes * Input and output may be in any convenient format * You may assume the input number is greater than \$\pi\$ and less than `array length` \* \$\pi\$ * You may assume the input array will be at least 2 elements long. * Your result must have at least two decimal points of precision, be accurate to within 0.05, and support numbers up to 100 for this precision/accuracy. (single-precision floats are more than sufficient to meet this requirement) Happy Golfing! [Answer] # [R](https://www.r-project.org/), ~~59~~ 53 bytes ``` function(x,i)x[0:1+i%/%pi]%*%c(a<-cos(i%%pi/2)^2,1-a) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCJ1OzItrAylA7U1VftSAzVlVLNVkj0UY3Ob9YI1MVKKJvpBlnpGOom6j5P00jWcNQz1jHWM9cx0zPUlPHVM9Y8z8A "R – Try It Online") Nothing too clever here - just an R version of the formula in the question. Thanks @MickyT for saving a byte, and to @Giueseppe and indirectly @xnor for another two, and thanks to @RobinRyder for saving a further 3. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~85~~ 74 bytes -8 bytes thanks to @xnor -2 bytes thanks to @Quintec This takes advantage of the Python 3.8 pre-release's new `:=` assignment operator. Other than that, this is really just the equation written out in Python. ``` import math lambda l,i:cos(i%math.pi/2)**2*(l[(j:=int(i/pi))-1]-l[j])+l[j] ``` Usage: ``` >>> p=lambda l,i:cos(i%math.pi/2)**2*(l[(j:=int(i/pi))-1]-l[j])+l[j] >>> print(p([1.3, 3.7, 6.9],5.3)) 3.165249203414993 ``` [Try it online!](https://tio.run/##pYw5DsMgEAB7v4ImEkvwWjbKYUt@CaIgSeG1wKwIjV9PxBvSTDEjDZ9lS4d5cq6VIqdcRPRl64KPr48XQdPyTl9Jl2aRaZhAqUnJYOW@rHQUSQMTQD@6PtjdwbWx8vrfoOPcEks7otHC4EOLO85O39AA1B8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` d©ØPṪÆẠ‘H×I_@Ḋ}®ị ``` A full program accepting \$i\$ and the array which prints the interpolated value. **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//ZMKpw5hQ4bmqw4bhuqDigJhIw5dJX0DhuIp9wq7hu4v///81LjP/WzEuMywgMy43LCA2Ljld "Jelly – Try It Online")** ### How? Interpolates between all neighbours using \$\frac{\cos(i \mod \pi)+1}2\$ then picks the relevant value. ``` d©ØPṪÆẠ‘H×I_@Ḋ}®ị - Link: number, i; list of numbers, A ØP - pi (ish) = 3.141592653589793 d - divmod = [i//pi, i%pi] © - (copy to register for later) Ṫ - tail (gets i%pi leaving register copy as [i//pi]) ÆẠ - cosine = cos(i%pi) ‘ - increment H - halve × - multiply by A (vectorises) I - increments -- i.e. (cos(i%pi)+1)(r-l)/2 for neighbours [l,r] Ḋ} - dequeue A _@ - swapped arg subtract (vectorises) -- i.e. r-(cos(i%pi)+1)(r-l)/2 - = r+(cos(i%pi)+1)(l-r)/2 ® - recall value from the register ị - index into (vectorises) -- i.e. [β+(cos(i%pi)+1)(α-β)/2] - implicit print of Jelly representation (only 1 entry so [] wont appear) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes ``` n=>m=>(Math.Cos(m%Math.PI)+1)/2*(n[m=(int)(m/Math.PI)-1]-n[++m])+n[m] ``` ~~I beat Python!~~ ~~Darn it, Python beat me.~~ I beat Python again! [Try it online!](https://tio.run/##NYm9CsIwEIB3n6KLcGfSlFpUpCaLIAgKbg4hQxtTDJgr2BYR8dmjWNy@H9ultvNxN5DdXNqhvjlt@GhPqoK3fKxKNTKSVEEqOFb9VWzbDsL0h6c9shyz@QxIBwmeeoSQ/Veam5Q0Y8Eg@34Ty8n57nt38OSgAXIPbV65KHhSiBVPlmL9RliIArGMHw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Röda](https://github.com/fergusq/roda), 51 bytes ``` f a,i{j=i//PI;[(cos(i%PI)+1)/2*(a[j-1]-a[j])+a[j]]} ``` [Try it online!](https://tio.run/##K8pPSfz/P00hUSezOss2U18/wNM6WiM5v1gjUzXAU1PbUFPfSEsjMTpL1zBWF0jFamqDyNja/7mJmXnVXJxpGtGGesY6CsZ65joKZnqWsToKpnrGmly1/wE "Röda – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ≈ëBü☺ÆssÅ¢â)KjjïΔ ``` [Run and debug it](https://staxlang.xyz/#p=f7894281019273738f9b83294b6a6a8bff&i=[1.3,+3.7,+6.9],+5.3&a=1&m=2) Unpacked, ungolfed, and commented it looks like this. ``` VP|% divmod with pi; push div and mod results separately |7^h do (cos(modpart) + 1) / 2 sX swap the original div result to top of stack, store it in the x register v decrement ;:- pairwise differences of array @ get element at index N* negate and multiply ;x@ get element from the original array at the x index, where x is the register + add ``` [Run this one](https://staxlang.xyz/#c=VP%7C%25%09divmod+with+pi%3B++push+div+and+mod+results+separately%0A%7C7%5Eh%09do+%28cos%28modpart%29+%2B+1%29+%2F+2%0AsX++%09swap+the+original+div+result+to+top+of+stack,+store+it+in+the+x+register%0Av+++%09decrement%0A%3B%3A-+%09pairwise+differences+of+array%0A%40+++%09get+element+at+index%0AN*++%09negate+and+multiply%0A%3Bx%40+%09get+element+from+the+original+array+at+the+x+index,+where+x+is+the+register%0A%2B+++%09add&i=[1.3,+3.7,+6.9],+5.3&a=1&m=2) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~47~~ ~~46~~ 38 bytes ``` u0;J=V/MP[A=UgJc) nUgJf))½McVuMP)Ä]×+A ``` To be continued... (golfing) [Try it online!](https://tio.run/##y0osKPn/v9TA2ss2TN83INrRNjTdK1lTIQ9IpWlqHtrrmxxW6hugebgl9vB0bcf//6MN9Yx1FIz1zHUUzPQsY7lM9YwB "Japt – Try It Online") [Answer] # APL+WIN, ~~39~~ 37 bytes 2 bytes saved thanks to Adám ``` 2⊃m+(-/m←⎕[0 1+⌊n÷○1])÷2÷1+2○(○1)|n←⎕ ``` [Try it online!Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4bPepqztXW0NXPBYoB5aINFAy1H/V05R3e/mh6t2Gs5uHtRoe3G2obAXkaIBHNmjyIyv9A/f/TuEz1jLkM9YwVjPXMFcz0LAE "APL (Dyalog Classic) – Try It Online") Explanation: ``` n←⎕ prompt for input of integer 2÷1+2○(○1)|n evaluate first term of formula [0 1+⌊n÷○1] identify indices of alpha and beta m←⎕[...] prompt for input of vector and select alpha and beta -/m alpha-beta 2⊃m+ take result of adding beta to complete the equation ``` [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` v!i|(c,r)<-properFraction$i/pi=cos(r*pi/2)^2*(v!!(c-1)-v!!c)+v!!c ``` [Try it online!](https://tio.run/##FcZBCoMwEADAr2zAQ2KTiIYqhXrtJ8RCWIQu1WRZxVP/nraXYV5xfy/rWsqp6KPRirk7lsyLPCTiQTlV1DCNmHctNVPTmWdX61Mpja417hc0l79li5RgBBZKB1QwtT5YCH6w0PvbDAquPpQv "Haskell – Try It Online") Note: the array is represented as a list. Thanks to @xnor for the half-angle tip. [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes ``` ->a,i{z=Math::PI;Math.cos(i%z/2)**2*(a[-1+j=(i/z).to_i]-a[j])+a[j]} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSezusrWN7Ekw8oqwNMaxNBLzi/WyFSt0jfS1NIy0tJIjNY11M6y1cjUr9LUK8mPz4zVTYzOitXUBpG1/wsU0qKjDfWMdYz1zHXM9CxjdRRM9Yxj/wMA "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~20~~ 18 bytes ``` ³%ØPÆẠ×_++H ÷ØPịÇ/ ``` [Try it online!](https://tio.run/##y0rNyan8///QZtXDMwIOtz3cteDw9HhtbQ@uw9uBAg93dx9u1////7@pnvH/aEM9Yx1jPXMdMz3LWAA "Jelly – Try It Online") ``` ÷ØPịṁؽµ³%ØPÆẠ×I_@SH Dyadic link, arguments x (index) and Z (array): ÷ØP x/pi ị Index (into Z). When x/pi is an integer, returns that elt of Z. Otherwise returns 2 elements at floor and ceiling. ؽ [1,2] (generic 2 element array) ṁؽ Mold; shape like [1,2] to ensure we have 2 elements. µ Start a new, monadic chain with the result [a,b] ³%ØPÆẠ×I_@SH Monadic chain ³ x %ØP x mod pi ÆẠ Unarccosine; cos(x mod pi). I Increment; b-a. ×I (b-a) cos(x mod pi) S a+b _@S a + b - (b-a) cos(x mod pi) H Halve; this is equivalent to our desired result. ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 54 bytes ``` ${Cos[y%PI/2]^2*&`-@(j:=x[1'-1*Floor[y'-y/PI]-1])+j@1} ``` [Try it online!](https://tio.run/##DcHBCoIwGADgu0@xg2nZNpmjIkEQhMBLeOj280fDZiXRxO3QiJ599X3KOdXfdRhIWYX40xgLftG1eYHnIksurF6OZfUGkTKRHZ7GzOBT5vOuRSZwtR5r8Q1Hra8W4mnqbxh18@PlTtq6RlltIRkogYj8AQguKZF8R8mW75GSDZcYIYYf "Attache – Try It Online") ## Explanation ``` ${Cos[y%PI/2]^2*&`-@(j:=x[1'-1*Floor[y'-y/PI]-1])+j@1} ${ } parameters: x, y Cos[y%PI/2]^2 the scaling function factor * times j:= set j to x[ ] the element in x at 1'-1*Floor[y'-y/PI]-1 the closest indices scaled by PI &`-@( ) spread subtraction over bounds +j@1 add the upper bound ``` [Answer] # C (GCC) ~~99~~ 79 bytes -20 bytes ceilingcat ``` float P=3.141593;b; #define f(i,a)(cos(fmod(i,P))+1)/2*(a[b=i/P-1]-a[++b])+a[b] ``` [Try it online!](https://tio.run/##JY3LCoMwFET3fsWlpZA0D0lTWyT4D@5tFtdoJOCjVHfirzcNdDlnDjNODM7F6McFN6grLdVdFaU2rcnOXe/D3IMngSMlblmJn5YupZpSpmh@uxJs2irktVBWYMNYaylLyMYwbzBhmAmFPQP4z2OjLVSwK6m5lk/@kOVhUvv@JN2T08W/5hNPf0USkFKTHfHr/IjDGsU4/QA "C (gcc) – Try It Online") Calling code ``` int main() { float a[3] = {1.3,3.7,6.9}; printf("%f\n", f(5.3,a)); } ``` note that it needed the compiler flag `-lm` to link with math libraries, so +3 bytes if you count that. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~21~~ ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žq‰`ž>;UÝèÐÁ-θX*-θ ``` [Try it online](https://tio.run/##yy9OTMpM/f//6L7CRw0bEg63HtpnZx16eO7hFYcnHG7UPbcjQgtI/P9vqmfMFW2oZ6xjrGeuY6ZnGQsA) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/k5ulir6SQmJeioGQPZj5qmwRkFv8/uq/wUcOGhMOth/bZWYcennt4xeEJhxt1z@2I0AIS/3X@m@oZc0Ub6hnrKBjrmesomOlZxnIZGumZgQQNdRTAMkBBHQUTPSMoF6zQQs8kFgA). **Explanation:** ``` žq‰ # Take the divmod PI of the (implicit) input-decimal # (part = input integer-divided by PI, remainder = input modulo-PI) # i.e. 5.3 → [1, 2.158...] ` # Push both values separately to the stack ž # Take the cosine of the remainder # i.e. 2.158... → -0.554... > # Increase it by 1 # i.e. -0.554... → 0.554... ; # Halve it # i.e. 0.554... → 0.222... U # Pop and store it in variable `X` Ý # Pop the part, and push a list in the range [0, part] # i.e. 1 → [0, 1] è # (0-based) index all of them into the (implicit) input-list # i.e. [1.3, 3.7, 6.9] and [0, 1] → [1.3, 3.7] Ð # Triplicate this list Á # Rotate the last copy once towards the right # i.e. [1.3, 3.7] → [3.7, 1.3] - # Subtract the values in the top two lists from one another # i.e. [1.3, 3.7] and [3.7, 1.3] → [-2.4, 2.4] θ # Pop and only leave the last value of this list # i.e. [-2.4, 2.4] → 2.4 X* # Multiply it by `X` # i.e. 2.4 * `X`=0.222... → 0.534... - # Subtract it from each of the values in the list we triplicated # i.e. [1.3, 3.7] - 0.534... → [0.765..., 3.165...] θ # And only leave the last value of this list # i.e. [0.765..., 3.165...] → 3.165... # (which is output implicitly as result) ``` ]
[Question] [ # Challenge Let's imagine an `N`-tuple of integers between 0 and `M` inclusive, and let's call it `F`. There are `(M + 1) ** N` possible `F`s in total. How many such `F`s satisfy all of the following inequalities (index is one-based)? * `F[n] + F[n+1] <= M` for `1 <= n < N` * `F[N] + F[1] <= M` Write a program or function that takes two **positive integers** `N` and `M` and outputs the answer in any convenient form. ## Test Cases ``` (N,M) => Answer (1,1) => 1 (2,1) => 3 (3,1) => 4 (4,1) => 7 (1,2) => 2 (2,2) => 6 (3,2) => 11 (4,2) => 26 (10,3) => 39175 (10,4) => 286555 (10,5) => 1508401 (25,3) => 303734663372 (25,4) => 43953707972058 (25,5) => 2794276977562073 (100,3) => 8510938110502117856062697655362747468175263710 (100,4) => 3732347514675901732382391725971022481763004479674972370 (100,5) => 60964611448369808046336702581873778457326750953325742021695001 ``` ## Explanation ``` M (max value of element) = 1 F[1] + F[1] <= 1; F = [0] (1,1) => 1 F[1] + F[2] <= 1; F = [0,0], [0,1], [1,0] (2,1) => 3 F = [0,0,0], [0,0,1], [0,1,0], [1,0,0] (3,1) => 4 F = [0,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0], [0,1,0,1], [1,0,0,0], [1,0,1,0] (4,1) => 7 --- M = 2 F[1] + F[1] <= 2; F = [0], [1] (1,2) => 2 F = [0,0], [0,1], [0,2], [1,0], [1,1], [2,0] (2,2) => 6 F = [0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,2,0], [1,0,0], [1,0,1], [1,1,0], [1,1,1], [2,0,0] (3,2) => 11 (4,2) => 26 (left as exercise for you) ``` # Rules * This is a [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") challenge. **The time complexity of your code should be polynomial in `M` and `N`** (e.g. you can't generate all `(M + 1) ** N` tuples and then check for the condition). Please explain your approach in your submission. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest answer in bytes wins. [Answer] # [Python](https://docs.python.org/2/) with [numpy](http://www.numpy.org/), 59 bytes ``` lambda M,N:trace(mat(tri(M+1)[::-1])**N) from numpy import* ``` [Try it online!](https://tio.run/##NY27DgIhEAB7vmJLQCzWkuQ@AYprT4tVDyWRRzZrcV@PZ4zlTCaZvsmz1dNI03m8qFzvBMFFL0y3VRcSLZx1OKBZvD/ixVgbjUrcCtR36Rvk0huLHfPEVB@rRoe4B40hQK4wewVfiH@AzrkKRBdc0vvJqJ8ZHw "Python 2 – Try It Online") Uses matrix multiplication to count paths. If float precision is an issue, the `mat` could specify `mat(...,int)`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 27 bytes ``` .N?Ys:RTtYh-QNgQ+NTs:Rdtszh ``` [Demonstration](http://pyth.herokuapp.com/?code=.N%3FYs%3ARTtYh-QNgQ%2BNTs%3ARdtszh&input=5%0A100&debug=1) Expects input in the format: ``` M N ``` This is classic dynamic programming, over the left end of the values set so far, the right end, and the current size of the gap. How it works, in pseudocode/Python: ``` .N | define memoized fill(left, right, gap): ? | if cap > 0 then s:RTtY | sum(fill(i, right, gap - 1) h-QN | for i in range(M - left + 1)) gQ+NT | else M >= left + right | output: s:Rdtsz | sum(fill(i, i, N - 1) h | for i in range(M + 1)) ``` `Q` is used for `M`, `z` is used for `N`, `:` is `fill`, `N` is `left`, `T` is `right`, `Y` is `gap`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` Q:&>~PiY^Xds ``` [Try it online!](https://tio.run/##y00syfn/P9BKza4uIDMyLiKl@P9/Uy5DAwA "MATL – Try It Online") This is a direct translation of [xnor's Python answer](https://codegolf.stackexchange.com/a/164370/56433) and my first MATL answer, so it's most likely not optimal. E.g. there is likely a shorter way to get an upper-left triangular matrix of ones than `t&lYRP`. *Edit: And it turns out there is, namely `:&>~P`. Thanks to Luis Mendo for -1 byte!* ``` M is the first input and N the second Q: increment M and generate range from 1 to M+1 &> compare vector element wise with itself with greater-than function results in a upper-right triangular matrix ~ inverse to get lower-left triangular matrix P flip rows to get upper-left triangular matrix i input N Y^ take the matrix to the power of N Xds compute the sum of the main diagonal ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` °(√&╒íÆ½╨⌂'├╖▼1_Z ``` [Run and debug it](https://staxlang.xyz/#p=f828fb26d5a192abd07f27c3b71f315f5a&i=1+1%0A2+1%0A3+1%0A4+1%0A1+2%0A2+2%0A3+2%0A4+2%0A10+3%0A10+4%0A10+5%0A25+3%0A25+4%0A25+5%0A100+3%0A100+4%0A100+5%0A&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` ^1]( [1, 0, ... 0] with M zeroes :) get all rotations of the array { begin block {:+rm map each array to reverse(prefixSums(arr)) },v* execute preceding block N-1 times F for each array, execute the rest of the program iT remove the last i elements from the array, where i is the iteration index F+ add the remaining elements to the running total implicitly print output ``` [Run this one](https://staxlang.xyz/#c=%5E1]%28+++%09[1,+0,+...+0]+with+M+zeroes%0A%3A%29+++++%09get+all+rotations+of+the+array%0A%7B++++++%09begin+block%0A++%7B%3A%2Brm%09map+each+array+to+reverse%28prefixSums%28arr%29%29%0A%7D,v*+++%09execute+preceding+block+N-1+times%0AF++++++%09for+each+array,+execute+the+rest+of+the+program%0A++iT+++%09remove+the+last+i+elements+from+the+array,+where+i+is+the+iteration+index%0A++F%2B+++%09add+the+remaining+elements+to+the+running+total%0A+++++++%09implicitly+print+output&i=1+1%0A2+1%0A3+1%0A4+1%0A1+2%0A2+2%0A3+2%0A4+2%0A10+3%0A10+4%0A10+5%0A25+3%0A25+4%0A25+5%0A100+3%0A100+4%0A100+5%0A&a=1&m=2) [Answer] # [R](https://www.r-project.org/), 72 bytes ``` function(M,N)sum(diag(Reduce(`%*%`,rep(list(outer(0:M,0:M,"+")<=M),N)))) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NXx0@zuDRXIyUzMV0jKDWlNDlVI0FVSzVBpyi1QCMns7hEI7@0JLVIw8DKVweElbSVNG1sfTWB@oDgf5qGqY6hgeZ/AA "R – Try It Online") Ports xnor's approach. Fails for larger test cases as R only has 32-bit integer support (they get cast to `double` once the max int value is reached), so using `gmp` or another arbitrary precision arithmetic library would be required. Strangely, R lacks a matrix power operator, as `^` always applies elementwise. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ 25 bytes ``` +/1 1⍉+.×⍣(⎕-1)⍨⌽∘.≤⍨⍳1+⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtglGBlyPOtrT/mvrGyoYPurt1NY7PP1R72INoLyuoeaj3hWPevY@6pih96hzCYjTu9lQGyj1H6jnfxqXKZehAQA "APL (Dyalog Unicode) – Try It Online") A full program which takes N, then M as inputs. Follows the same algorithm as xnor's Python solution. -6 bytes from Bubbler. ]
[Question] [ ## Overview Given the integer representation of three elements in GF(2^64), give the product of the first two elements over GF(2^64) with the reducing polynomial defined as the polynomial m such that m(x) = x^64 + n(x), where n is the polynomial representation of the third element. ## You want me to *what*? A finite field GF(p^q), where p is a prime and q is a natural number, contains p^q elements. (GF stands for Galois Field, which is another name for a finite field.) The elements of this finite field can be given many interpretations, but the two most common are as the integers between 0 and p^q-1, and as the polynomials with term coefficients between 0 and p-1 and degree less than q. There is a one-to-one correspondence between the base-p integer interpretations and the polynomial interpretations, from a one-to-one mapping between digits and term coefficients: ``` Integer interpretation (binary) | Polynomial interpretation (given x) --------------------------------+------------------------------------ 0 | 0 1 | 1 10 | x 11 | x + 1 100 | x^2 101 | x^2 + 1 1101 | x^3 + x^2 + 1 ``` Finite field arithmetic makes the most intuitive sense under the polynomial interpretation, but for brevity, the integer interpretation is used, and operations are described according to the integer representations of the finite field elements involved. Addition in GF(p^q), like polynomial addition, operates with no carryover. Each digit in the sum is equal to the sum of digits in the addends, mod p. Likewise, subtraction in GF(p^q), like polynomial subtraction, is borrowless, with each digit in the difference being the difference in the corresponding digit in the minuend and subtrahend, mod p. If p = 2, both carryless addition and borrowless subtraction are equivalent to a bitwise XOR. Multiplication in GF(p^q) relies on (but is *not*) polynomial multiplication, but with each term coefficient reduced mod p. If the factors are interpreted as integers rather than as polynomials, the operation can be implemented like long multiplication, but with summation of intermediate terms done without carry, as with finite field addition: ``` 1111 * 1101 ------ 1111 1111 ^ 1111 --------- 1001011 ``` Multiplication in GF(p^q) also relies on a reducing polynomial, an irreducible polynomial with term coefficients in the set of integers between 0 and p-1, degree q, and leading coefficient 1 (and thus corresponding to an element in GF(p^(q+1))). Irreducible, in this context, means that it is not equal to any reduced polynomial product, as described above, of any other polynomials with term coefficients in the set of integers between 0 and p-1. Last, multiplication in GF(p^q) relies on polynomial division, but with each term coefficient reduced mod p. Like reduced polynomial multiplication, this operation can be done directly on the integer representation by doing long division, but with borrowless subtraction rather than subtraction with borrow: ``` 1100 ,-------- 11111 / 10001001 ^ 11111 ------- 11100 ^ 11111 ------- 1101 ``` Now, for the actual description of multiplication in GF(p^q). First, the carryless product of the factors is calculated, as described above, keeping all digits in the product. Then, the remainder of the carryless division of this carryless product and the reducing polynomial (as interpreted as the integer interpretation of an element of GF(p^(q+1))) is taken. This remainder is the final product. ## Task Given 3 64-bit words A, B, and C, return pmod(pmul(A, B), C+1<<64)), where pmul is the carryless multiplication operation as described above, and pmod is the remainder of the carryless division operation as described above. C + 1<<64 can be assumed to correspond to an element in GF(2^65) that in turn represents an irreducible polynomial. As with most code golf challenges, standard loopholes apply, and shortest program wins. ## Test cases Each test case is represented in four hexadecimal numbers, with the first three being the three arguments A, B, and C, as described above, and the fourth being the expected return value. (All values were calculated by Nemo, an open-source package for Julia that provides support for finite fields, among other things.) ``` 0x0000000000000000 0x0000000000000000 0x000000000000001B 0x0000000000000000 0x0000000080000000 0x0000000080000000 0x000000000000001B 0x4000000000000000 0x0000000100000000 0x0000000100000000 0x000000000000001B 0x000000000000001B 0x0000000200000000 0x0000000200000000 0x000000000000001B 0x000000000000006C 0x0000000000000001 0x0000000000000001 0x702414004010004F 0x0000000000000002 0x0000000080000000 0x0000000100000000 0x702414004010004F 0x8000000000000000 0x0000000F00000000 0x0000000F00000000 0x702414004010004F 0x686D881284A01126 0x0000208000000000 0x0080000000000002 0x702414004010004F 0x870AF102748F8A93 ``` ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language, copied from [here](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet): ``` var QUESTION_ID=160069,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~39~~ 36 bytesSBCS ``` {×≢⍵:(⍺×⊃⌽⍵)≠((⍺⍺×⊃⍺)≠1↓⍺,0)∇¯1↓⍵⋄0} ``` [Try it online!](https://tio.run/##jY/BSsNAEIbveYrcuoEIk@1iordYCe1JsPoAKVo9tCo9KeJFJTbRLRURe9SikFsPWoSCl/RN5kXibEI1pRX8D8P@38zOv@uftFb2zvzW8UGank@fMByiHK8zlBMy0RXefZE3MHxmiv1gOVHMwuCBjiYY2L1JRrkd4@01XKRNDPooe9h7rG3RjWRUxuCeXH27QnWnWquneS/og7Z7dLh/SicTuwOUIRMoP7iB0SujmU2TimugfMdoqFWzQYbRZaFF@2OUMcfoLd9Ak7SCkDBVmX5Spb9pzNcbelvvGLQjC01ivQQkDg7MVFLo16ouIRu4sASAAIuI8Ag5NrieBdwWjue4a@WS1sHwxWdtvWk0/s5ScopZmaxC/LIsmNf/szgsZC1Bs1dsLKDVylzWNw "APL (Dyalog Unicode) – Try It Online") -3 bytes thanks to @ngn. A recursive inline operator (dop). You can assign it to `f` and use it as `a(m f)b`. A port of [orlp's Python answer](https://codegolf.stackexchange.com/a/160150/78410), but using bit arrays instead of integers. Dyalog APL has neither 64-bit integers nor bitwise ops, but can simulate them pretty well using array ops. ### How it works ``` {×≢⍵:(⍺×⊃⌽⍵)≠((⍺⍺×⊃⍺)≠1↓⍺,0)∇¯1↓⍵⋄0} ⍝ ⍺←A, ⍵←B, ⍺⍺←M {×≢⍵: ⋄ } ⍝ If B has at least one bit, ∇ ⍝ Recursive call with M fixed with... 1↓⍺,0 ⍝ A shifted left once ≠ ⍝ XORed with (⍺⍺×⊃⍺) ⍝ M × highest bit of A ( ) ⍝ as left arg, and ¯1↓⍵ ⍝ B shifted right once as right arg (⍺×⊃⌽⍵)≠ ⍝ XOR the result with A × LSB of B 0 ⍝ Otherwise, return a zero, ⍝ which is equivalent to 64 zero bits ``` The single zero is returned only on recursion. Then it becomes the right arg of `(⍺×⊃⌽⍵)≠`, and it acts exactly like a vector of 64 zeros (since `(⍺×⊃⌽⍵)` evaluates to a 64-length vector). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 51 bytes ``` $\=$'*($\>>63)^$\<<1^$`*($&<<$_&1)for-63..!/ .* /}{ ``` [Try it online!](https://tio.run/##DchBCsIwEADAr0QI1RaabrLJ7gZiXxKqFwWhmFC9iV839jQw9batoTWdz/o4nHSeZ8J@0Tklu@jrPl1K@tLZ/l62kdCYw6TMoKbvpzUMjN46juDYgUICJxwZrETCXSUgQBDIObYkQbznX6nvR3m@2lj/ "Perl 5 – Try It Online") I originally thought this would be hard for perl, but this isn't too bad. All the `$`s of course still hurt for arithmetic challenges.. [Answer] # Python 2, 57 bytes ``` f=lambda a,b,m:a*b and b%2*a^f(a*2%2**64^(a>>63)*m,b/2,m) ``` I really tried to golf this in Rust, but the language is just not suitable for golfing. So here it is in Python. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` Bæc/ḣ-64æcB}ʋƬUSḣ64UḂḄ ``` [Try it online!](https://tio.run/##y0rNyan8/9/p8LJk/Yc7FuuamQBZTrWnuo@tCQ0GCpiZhD7c0fRwR8v/Q5sPL3/UuCXJ0OxRw4yHu7sPz3D6/z/aoMIACIwMLAxgQAckhOCCZGP/G1SYGxiZGJoYGJgYGAKFTNwA "Jelly – Try It Online") Works either as a function or a full program. This takes two arguments: a 2-element list `[A,B]` for the numbers to multiply; and the argument `C` that specifies the polynomial. The TIO link contains a footer that prints the result in hexadecimal, making it easier to verify the test case. ## Algorithm The calculation is done by representing each finite field element that we're working on as a list of bits that represent the coefficients of the polynomial. (For working on finite fields with this representation, we'd really want them to be little-endian, but Jelly's base conversion operators are big-endian, and thus the program ends up swapping endianness a couple of times.) Converting A and B to this form, then convolving them (which is the same operation as polynomial multiplication), gives us a polynomial (not necessarily a normalised one) representing the result. We then need to normalize it (i.e. reduce it to degree at most 63) by doing the polynomial long division, i.e. taking the result modulo *x*64+C (where C is interpreted as a polynomial). This is the same as taking the result modulo *x*64−C because addition and subtraction are equivalent in binary finite fields. If we right-shift the result polynomial by 64 degrees, then multiply by C and add back the parts of the polynomial that fell off during the shift, this doesn't change the value modulo *x*64−C (because some multiple of *x*64 got subtracted from the result and the same multiple of C got added, thus reducing the result by a multiple of *x*64−C and thus not changing the remainder upon dividing by *x*64−C). Additionally, because C has degree at most 63 (it's a "64-bit word" interpreted as a polynomial), the shift-multiply-add sequence must reduce the degree of the resulting polynomial unless it's already 63 or lower, i.e. it's already normalized. It's therefore possible to repeat the shift-multiply-add (with polynomial addition and multiplication in GF(2), i.e. pointwise XOR and XOR-convolution) until we reach a value that remains unchanged, which must be the normalized result. This algorithm is tweaked a little to be terser in Jelly. There are only two major changes. One is that we don't bother using only 0 and 1 as coefficients in the polynomials; in GF(2), 0 and 2 are the same number (all that matters is oddness versus evenness), so we just use regular pointwise addition (which doesn't carry from one coefficient into the next) instead of pointwise XOR and regular convolution instead of XOR-convolution (this saves lots of bytes during the program and requires only a `Ḃ` to fix the coefficients back to the 0-or-1 representation near the end). The other is that instead of immediately adding back the coefficients that got shifted off, they're remembered in a list and added back at the end (which is clearly equivalent because if we added them back immediately, they would just get shifted off again on the next iteration of the shift-multiply-add loop). (We actually remember the whole polynomial, but just take the least significant 64 coefficients for summing purposes.) In order for the sum to work correctly, we need to use a little-endian representation (so that the coefficients that are added to each other when summing, i.e. the ones that are the same distance from the left end of the list, correspond to the same power of *x*0). It's possible to do the sum and the cut down to 64 coefficients either way round, and doing the sum first saves on the need for an extra quick to specify which array rank we want to work on. Then we convert the polynomial back to a big-endian representation, and then to a number, as the program's output. ## Explanation ``` Bæc/ḣ-64æcB}ʋƬUSḣ64UḂḄ B Convert {[A,B]} to big-endian binary æc Take the convolution of / the converted version of A with that of B Ƭ Repeatedly loop, until nothing changes: ʋ (grouping/bracketing mark, sets the Ƭ's scope) ḣ take the prefix - that omits 64 the last 64 elements æc and take its convolution with B the big-endian binary representation of } the second argument U Reverse {the result of} each {iteration} S Sum corresponding elements {of the reversed results} ḣ64 Take the first 64 elements of the sum U Reverse back Ḃ Replace each element with its value mod 2 Ḅ Convert from big-endian binary to decimal ``` The `U`s mark where the program changes from big-endian to little-endian notation for its polynomial, and where it changes back again. [Answer] # MMIX, 36 bytes (9 instrs) ``` 00000000: e3030000 76040100 3f010101 70ff0003 ẉ¤¡¡v¥¢¡?¢¢¢p”¡¤ 00000010: 3b000001 c6030304 c60000ff 5b01fffa ;¡¡¢İ¤¤¥İ¡¡”[¢”« 00000020: f8040000 ẏ¥¡¡ ``` Disassembled and commented ``` ffm SET $3,0 // r = 0 0H ZSOD $4,$1,$0 // loop: t0 = B & 1? A : 0 SRU $1,$1,1 // B >>= 1 ZSN $255,$0,$3 // t1 = A >> 63? C : 0 SLU $0,$0,1 // A <<= 1 XOR $3,$3,$4 // r ^= t0 XOR $0,$0,$255 // A ^= t1 PBNZ $1,0B // if(B) goto loop POP 4,0 // return r ``` Russian peasant multiplication. Surprisingly simple! I think this is the first time MMIX has tied for shortest. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 69 bytes ``` f(a,b,c)=lift(g(a)*g(b)%(x^64+g(c)))%(x-2) g(n)=Pol(Mod(binary(n),2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZNBSsQwFEDBpacIBSHRFJIY2rio0FG7E9yXjqSVlkLplFJh5g6CG3cqzEa8glfwCLqcC3gFk9HR1KZqVsn7Py__h-T2sZFteV40y-XDZZe74uUkhxKnOENBVeYdLKBEuwVM0Q6cTz2-V8AMIb1wGdouYI2Cs1kFT2cXMC1r2S4UwQyhD9nr1rNsmmoBJXAPQdOWdafkwNErB4MUBCCTVQVzDGQ85QnSMR0pc6iCgaI8UWx1d_P2dO3o2f2Vg1RaHJM5-THwPxCdWLISbNjEcKsFGTb-i40OC7Gg8droxLSx4VYLGrd5R71ON4nDG9HIJ4xT1RtfV8wjS9Yf92Z2arEJ0h-mLRq2ZSKLzRPesRCUCR4SSpn3ZWPk-6C1rXcuG6nNJ2FECfO5iER4sJ8kny96803eAQ) ]
[Question] [ Given an array of positive integers `A` as the input, generate a program that, when repeated for `k` times, output the `k`th(1-index) value of the array. For example, if the array is `[1,11]`, the output should be a program that outputs `1`, and when repeated twice, output `11`. Code like `print(end="1");` in Python 3 works: `print(end="1");` prints 1 and `print(end="1");print(end="1");` prints 11 Smallest sum of code lengths to solve all test cases win. Your meta code should solve 500 test cases in 60s, and each of your solution code should return in 10s. Meta code and solution code needn't be in the same language, but all solutions your meta-program generates should be in same language. Pretest data and generator can be seen [here](https://tio.run/##VY/dDoIwDIXveYqTGRIIYDaVG4fyIOqF8qNDHWRgYmJ4dmSg/PSiTb72nLaRd42iplkIGT1ecYKgrGKRL297Y4Ye4qKZkBWSd6HOMrZsfAy0oZLqpSR@zASjFAGYjxAMWzBnEHCj7hyeZyEHuQbCRebizjtQ6mFYbLXe@HaP0lzBEjvKIQKf6uI4f72ODLtx/4rCAeNDs1DtihQWORB7pJ0lR@Z5HFOrmcKMzZK448ftmSFxyZacjnJqVht9rpvmCw). 7 days later will use the sum of submission time(e.g. 12:34 mean 1234) to be the random seed and generate another test case as the final test case. --- The final seed is 7335 in GMT+8, so the final test data is [here](https://tio.run/##VY/RCoJAEEXf/YrLhqCosVtI0Gp9SPVQrtZarbIqBOG3m2ulNQ8zcGbunZkkOCdJ182kSm6NSBFVtZDF/LKx/tBNngyTqkb6KPVRCcfF00IfOq0brfBhNhiliMBCbMGwBvNGAbfaweF@lGqUGyB95D6ufACVGYazWi5D902yQsORMeWQUUhN8byv3ESOeFq/oPDA@Ngsdb8hg0N2xJ3oYMmRBwHHr9WfwhZ2Rfzp4f7KLfHJmhz26testd657boX) [Answer] # [Python 3](https://docs.python.org/3/), generates [Stax](https://tio.run/#stax) This uses a variety of strategies. Most strategies only apply under certain conditions, but there's one fallback strategy that is always usable. At the end, the smallest candidate program is selected. ``` from functools import reduce from math import sqrt symbols = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}" def uncycle(arr): for size in range(1, len(arr)): if all(e == arr[i % size] for (i, e) in enumerate(arr)): return arr[:size] return arr def constant(val): return "A" if val == 10 else str(val) def shift(val): if not val: return "" return constant(abs(val)) + "+-"[val < 0] def encode(a, offsetMode): result = ""; if offsetMode: for i in range(len(a) - 1, 0, -1): a[i] -= a[i - 1] for i in range(len(a)): parts = [] signBit = (a[i] < 0) * 2 continuing = (offsetMode and i == len(a) - 1) * 1 remain = abs(a[i]) while remain > 22: parts.insert(0, remain % 46 * 2 + continuing); remain //= 46 continuing = 1 parts.insert(0, remain * 4 + signBit + continuing) result += "".join(symbols[p] for p in parts) return result def cram(arr): flat = encode(arr, False) offset = encode(arr, True) return offset if len(offset) < len(flat) else flat; def issquare(num): root = int(sqrt(num)) return root * root == num def isgeometric(arr): r = arr[0] return all(r ** (i + 1) == e for (i,e) in enumerate(arr)) def generateProgram(arr): candidates = [] rotated = uncycle(arr) rotated = rotated[-1:] + rotated[:-1] deltas = [b - a for a,b in zip(arr, arr[1:])] # single constant strategy if len(arr) == 1: candidates.append(constant(arr[0])) # repeated constant elif len(set(arr)) == 1: num = arr[0] if num == 10: candidates.append("A") if num % 2 == 0: candidates.append(constant(num // 2) + "H") if issquare(num): candidates.append(str(int(sqrt(num))) + "J") candidates.append(constant(num - 1) + "^") # repdigit if len(arr) == 2 and 10 < arr[1] == arr[0] * 11 < 100: candidates.append(str(arr[0]) + "p") # single digits if max(arr) < 10: candidates.append("".join(map(str, rotated)) + "E|X@") # max 10 if max(arr) == 10 and rotated[0] != 1: candidates.append("".join(str(e - 1) for e in rotated) + "E|X@^") fns = [ ("", lambda x: x), ("H", lambda x: 2 * x), ("^", lambda x: x + 1), ("J", lambda x: x * x), ("Hv", lambda x: 2 * x - 1), ("H^", lambda x: 2 * x + 1), ("^H", lambda x: 2 * x + 2), ("HJ", lambda x: 4 * x * x), ("JH", lambda x: 2 * x * x), (":T", lambda x: x * (x + 1) / 2), ("|F", lambda x: reduce(lambda a, b: a*b, range(1, x+1))), ("J^", lambda x: x * x + 1), ("^J", lambda x: x * x + 2 * x + 1), ] for (stax, fn) in fns: if all(fn(i + 1) == e for (i,e) in enumerate(arr)): candidates.append("|X" + stax) # fixed delta if len(set(deltas)) == 1: delta = deltas[0] start = arr[0] - delta if start == 0: candidates.append(shift(delta)) if delta == 1: candidates.append("|X" + shift(start)) elif delta == -1: candidates.append("|x" + shift(start)) elif delta > 1: candidates.append("|X" + constant(delta) + "*" + shift(start)) elif delta < -1: candidates.append("|x" + constant(-delta) + "*" + shift(start)) # geometric series if isgeometric(arr): candidates.append(constant(arr[0]) + "*") # prefix if len(arr) == 2 and arr[1] // 10 == arr[0] < 10: candidates.append("." + str(arr[1]) + "|X(") # suffix if len(arr) == 2 and arr[0] % 10 == arr[1] < 10: candidates.append("." + "".join(map(str, arr)) + "|X)") # uncycled cram candidates.append('"' + cram(rotated) + '"!|X@') candidates.sort(key=len) return candidates[0] while True: arr = eval(input()) prog = generateProgram(arr) print(prog) ``` [Try it online!](https://tio.run/##jVd9X9s2EP7fn0J1x7CDncQhUBpI13YrY2zduq3b2NLQn5LIiVq/ISs0dOyzszvJ70khKZRYd/fci06PzsmNXMTR/t3dY7KQMkkHnc40nrF5HPjtVNLpR7aaLmg0Z@1pHHauliyVPI7SjndwtN990olcyUOWuomI54KGrh8LVy6YC@sLN1qGEyYMX8Qh8ZfRVMZxkBIeJrGQRLDZcsq0MKRyka@nV0IaRnoTTlB5SEzy6PFXO1/vWnZrz3Hbna7X2@8fHD45ejo4Phk@@@b5i5fffvfq9PuzH85//On1z7@8@fW339/@8edfF3//M3r3bnz5nk6mM@bPF/zDxyCM4uRKpHJ5/Wl18/nf2/9MwwAhgeBupgGzqBD2wCDwgURIyj8zwiMiMH/Lc0jAIqWS6eCH@4QGgcXIcEhANOJkR9mNFYLFHcJsxGBQDCaoZE0A/AgmlyJS9gNlbNRXdZBTqLukkbSuaZABZCrmCxMDgXUMw@sSFqSMpFIoVW2dLrhfNQX9KJZoMyhgzCpo4Y5OUmVnkz1i7rnmCP2ckO5YA7MIG8aiDol9P2XyNTwV4aXLQOImmse501KprAGWipeVVmW2iUug5F2HuF6jXHTEx8Qd4l9UGhtfxKgYJlRI7KfRuFhK@Tx6yTE@S0FCTjZpkV6hACWQPFryaI46ZeSERjNwBrUuQ0VLzyh3NKQQC8QIxUNwuxB9WvCA5QrPSK9XT07F2eZRyoS0IPtMcYf0DzE22IMyKvu40UZKtdMZgnJNUkvEM4wHnLVIH/zk5al5rGSo9nYPN7f9IeaRlZ3ZUaJ7P8HNUA60UbW3tHHW1sAb1YMXUNyRvKuEcMgphXbWIHoPGvK3YpmJM/hMC7oN90c/2bC9@IT4tj4g@PVYB8HT9GpJBbPgmObNG8foiMMJQE5SkpoXpdDK9IYE5DnWnMUhk4JPK3kJogmiWz/cwB2CtFrAFFBnaCIAYjl1bGQO7WPOIrX2RvNuxc8UepPPQFRpdhFLWJjBQpXoGqLs28j1BmOIJX8cuHDAlOqMBZIq1Ak0PFVRUmeCMX7mid4KzBDs7czkMTRRNId2z8kESQlg5zc5HeSUqoirPAllFm2aJCyaWSUdqSJiIbQHwRKmUsg11DoLMnDYel24hgeoan1HclLEdSTRwYYggGjtpvIOHEow2KhfBI2KnQ7pKQ49q4PUe28DChJ5vQ0VzHkF5gHXip/2CDEvzWrdZnzO5aad6CmGg4vkRO/oOL/eumOkOQ/WvW73vu3CmLOdwliT0m/WEcp3mjsP6Uo7R@D7cHOyCWmCPpy8T3VJXt1ePC89ASigrbnQVyQmmPc4ZPXogfYrSA7yYrqe2P96PshCyCMoiuxH6rgUsIACQwQNJzNKVgOysp2K6Kwm60Gd6/LLuq2ii6r8vCFv2p9drztQidSULjcoNT1dnm1U6tWR6vH0lVIzpvNNSE2lwdu1zCwdFOk0nN6e1lT1jGllCzChTAaEtiZOOdGt9jw4TbWQLtfruF6B841KzXKVkwn0DV050BCK0qEv1iZIP9r6CqgPDBt69fbCxPsbXBZnwecroEhF4dUDj@yoeX2NINUytK8WV1kSgIUsyBN6qITNoDMNZMUHYtVjqQKwa6yYua@FdH@6Ckl5riCpe6DAcrcAW20F9mzruAoi1kkiSbS2cnGyfbiFD/deJ1kvFOMJgbmPs4KENw8u213H2mPhIhEMOu7LV0t2q8CVCFRc3i0Psn9bN7a@Wzzt9vbCqtwuS/9Bx@Bop@LX29bv2t2j5woVgl2GkM1YMzXZGpsBd81d3DYc3Sq3x675CK6P3cq8XLFM4e3Y@shuhpBUbQ4tdfCQGvr9AmdinREEifMyvLTBEJEspZV1G76yg2DTJJnJceZALdu4uxsdOD3nibMP/@873oHjdeGp53h9x/Mc7xB/9uFfH36PnP7YGIHsqRKgmYcS0D10DuALGvaOxsb/ "Python 3 – Try It Online") **Update: Validation** It will be time consuming to execute each multiplicity of each program separately. It's possible to run them all at the same time. In order to do this, a small piece of code must be used. It's responsible for a few things. 1. Do implicit output if any. Normally, at the end of a stax program, the top of stack is printed if there has been no other output. When running multiple programs in the same source file, this must be done explicitly. 2. Clear both stacks. 3. Reset registers. For these programs only the x register is used. This boilerplate should be applied after every individual program to be executed. ``` |d{P}{zP}?0XLd ``` For example, the input `[5,2,7,3]` produces the stax program `3527E|X@`. All four multiplicities can be tested at once. ``` 3527E|X@ |d{P}{zP}?0XLd 3527E|X@3527E|X@ |d{P}{zP}?0XLd 3527E|X@3527E|X@3527E|X@ |d{P}{zP}?0XLd 3527E|X@3527E|X@3527E|X@3527E|X@ |d{P}{zP}?0XLd ``` [Try it online!](https://tio.run/##Ky5JrPj/39jUyNy1JsKBqyalOqC2uiqg1t4gwieFiwsmQbQCkhXi0vD/PwA "Stax – Try It Online") In this way, it's possible to test all the multiplicities of all the program in the same run, assuming nothing breaks. It would probably be the largest stax program ever executed if all 500 are done. [Answer] # [Perl 5](https://www.perl.org/) `-p`, generates [Perl 5](https://www.perl.org/) `-p`, overhead ~~19~~ ~~17~~ 13 -1 thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) The score for one input will be `length of the input + 13`. Can obviously be improved by generating self-decompressing programs for larger inputs, but I won't bother. Give the input array separated by commas on one line on STDIN. ``` #!/usr/bin/perl -p chomp;$_="}{\$_=($_)[\$%++]" ``` [Try it online!](https://tio.run/##K0gtyjH9/z85Iz@3wFol3laptjoGSGmoxGtGx6ioamvHKv3/b6xjpmOiY871L7@gJDM/r/i/bgEA "Perl 5 – Try It Online") Run the output concatenated `n` times with no input (e.g. redirect from /dev/null) Sample way to run it for input `2,6,4,7` and the resulting program repeated 4 times: ``` perl -p '}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]' < /dev/null ``` [Try it online!](https://tio.run/##K0gtyjH9/7@2WiXeVsNYx0zHRMdcM1pFVVs7lhKx////5ReUZObnFf/XLQAA "Perl 5 – Try It Online") If you don't like the resulting program trying to read from STDIN use this version with overhead 17: ``` #!/usr/bin/perl -p chomp;$_="1/!say+($_)[\$-++]," ``` [Try it online!](https://tio.run/##K0gtyjH9/z85Iz@3wFol3lbJUF@xOLFSW0MlXjM6RkVXWztWR@n/fyMdMx0THXOuf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") Sample way to run it for input `2,6,4,7` and the resulting program repeated 4 times: ``` perl -E '1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],' ``` [Try it online!](https://tio.run/##K0gtyjH9/99QX7E4sVJbw0jHTMdEx1wzWkVXWztWhyrC////yy8oyczPK/6v62uqZ2igZwAA "Perl 5 – Try It Online") This version crashes after printing the required output [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), generates 05AB1E ``` ¸»“"ÿ"#.g<“ƵƒçJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0I5Dux81zFE6vF9JWS/dBsg8tvXYpMPLvf7/jzbVMTTXMdcxNNYxigUA "05AB1E – Try It Online") The generated program for the input `[5,17,7,13,2]` is `"5 17 7 13 2"#.g<è`. [Test suite for [5,17,7,13,2]](https://tio.run/##MzBNTDJM/f@/pqxSL0xHM@b/fyVTBUNzBXMFQ2MFIyVlvXSbwyu4sIiRr4yqOmltGBYhAA) The length of the generated program is `len(input) + 5` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) Anonymous prefix lambda. Returns a program body. ``` { 1=≢⍵:⍕⍵ ⍝ single element (2=≢⍵)∧(⍵[2]=11×⍵[1]):⍕⍵[1] ⍝ 2, 22 etc. 1=≢∪⍵:'⊢',⍕⊃⍵ ⍝ all the same (⊢≡⊃×⍳∘≢)⍵:'+',⍕⊃⍵ ⍝ linear ((⌊=⊢)!⍣¯1⊢⊃⍵)∧(1∧.=1↓⍵):'!',⍕!⍣¯1⊃⍵ ⍝ factorial followed by all 1s (⍵[2]∧.=1↓⍵)∧(⍵[1]=10|2⊃⍵):(⍕⊃⍵),'⌈',(⊃⍕2⊃⍵) ⍝ b ab ab ab e←{∊⍉2 2⍴'+×',⍕¨⍵}¨⍸(⊃⍵)=∘.×⍨⍳10 b←⍵∘≡¨e(({0::⍬ ⋄ ⍎⍵}¨,\)⍴∘⊂)¨⍨(≢⍵) ∨/b:⊃b/e Q←{'''',⍨⍵/⍨1+''''=⍵} (5∧.≤⍵)∧(≢⍕⍵)>6+(+/14=⍵)+≢⍵:'{⍺←⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[⍵] ⍝ string fallback (≢⍕⍵)>9+(+/5=⍵)+≢⍵:'{⍺←¯4+⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[4+⍵] ⍝ offset string fallback '{⍺←⊃⋄1⌽⍺⊢⍵}',⍕⍵ ⍝ fallback } ``` [Try it online!](https://tio.run/##tZPPa9RAFMfv@Sump0lI3N0Z01UDETx5LoiX2kOyO1sXpxvZBKSse9FSsulmKchSLx5aBRcRemgLInjZ/ifzj6zvTX5YtaIeGkImM/N9n@/Le5PgubzV3Q1ktL1aPRQDtX84MghezFeTE5VfeCqfw0BU/o7E/cG2FERIsSMGiVEITV4qLZV@NGHc5Fs@Y5dH@Mq2rBIAr5rBHcI5EUmnYVw1Sj@hF1XZCXUwIHtdmQZSkuSpIHGwIypLkKnJMYjQ5UylbwFhaYD9a7jsD0QwrAJNNc18iLbWVP5@ecoQpLU6eQaPhs/U/htc8eiahtXSmtkLOkk07AeS9CIpoxeiS8JdnSiL6xR1IX4CVvVhUJ/WS14ae2adsOVQNU2pY@rpvFJoz5AE5V06COyVSjOVTzjhKj@n9uWRTni5gKgxPr@YJcKHGjWwWLB4xloFIQQCbOryHS8XwjRHLQ/a9Zmogz0wnRUY5wmU9hxV2SsLqQuzbHiBUemiGXpgFDarBm1gbhQuRzteNGFgNi74yCxLtI7VUZMPdW2QimfFut@2TbvJXFRbdnkQ6UjlXzHl2fzBY2w7fNrBHlPTb7ieoWaMlhtEKzZhXhy5OBnCwYWuSRkGnWd1h37Y3UO79Wvdlqeu/a@OoKw8o14vFskfrOsvuY7nXPnh6jgyXq0o/J9iGCSCdKKu8KgBpgDBCQywSW4TRlyDUoM@EnGCinyG29Xo/DYpVjDir3BOXNK@OTjnN8VuE@6SO3f/H/8d "APL (Dyalog Unicode) – Try It Online") ## Methods This explores various methods and returns the first usable one, eventually falling back to a universally applicable method. ### Single element If the list has only one element, it is returned as-is. ### 2, 22 etc. A single digit can just be repeated to generate the number 11 times bigger, ### All the same We just return the rightmost (`⊢`) number. ### Linear *f(n) = k×n* sequences just insert a plus before the first term. ### Factorial followed by all 1s When the first number n=!m and subsequent numbers are 1, then `!m` is a solution because `!m` is n and `m!m` is 1 and `!1` is 1. ### b ab ab ab Since all two-digit numbers are larger than all single-digit numbers, a running maximum, where the front of the first number is glued to the back of the second number, is a solution. ### The three-line-code Check whether any formula of the type `+a×b` is valid. ### String fallback Long sequences with no numbers under 5 (because 4 is a line break) can be encoded as characters of the SBCS. ### Offset string fallback If there are numbers under 5, we shift up by 9 to avoid those. ### Fallback Simple string concatenation of the string `"{⍺←⊃⋄1⌽⍺⊢⍵}"` and the stringified (`⍕`) input. E.g. `[3,1,4]` returns the program body `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4`. The part in braces is an ambivalent function which means it can be either a prefix function or an infix function. Thus the leftmost instance of it will run in prefix mode, and all the others in infix mode. The difference between the modes is whether `⍺`, signifying the left argument, has a value. If it doesn't then it will be assigned the function `⊃` (first). **Explanation of fallback method** `{`…`}` anonymous lambda:  `⍺←⊃` If there is no left argument (`⍺`) assign the function `⊃` (first) to `⍺`  `⋄` then: At this point, the following code means two different things depending on whether `⍺` is a list of numbers (infix call) or the function "first" (prefix call).  If `⍺` is a list of numbers:   `⍺⊢⍵` discard the left argument in favour of the right argument   `1⌽` rotate that one step left  If `⍺` is the function "first":   `⊢⍵` yield the right argument   `⍺` pick the first element of that   `1⌽` rotate it one step (a no-op on a scalar) **Example run of fallback method** Executing `3 1 4`'s code, `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4`, assigns the "first" function to `⍺` and thus returns the first element; `3`. Executing `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4` lets the rightmost lambda "capture" the left `3 1 4` as its left argument, so `⍺` has a value which is discarded in favour of `3 1 4` which is then rotated one step left and yields `1 4 3` as result. This is then used as sole argument to the leftmost lambda, where `⍺` becomes the "first" function, causing the result to be the first element; `1`. Executing `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4` lets the rightmost lambda "capture" the middle `3 1 4` as its left argument which is then discarded in favour of the right argument, `3 1 4`, which when rotated one step left is `1 4 3`. This is then used as right argument of the middle lambda together with the leftmost `3 1 4` as left argument. The left argument is discarded for the right, which rotated one step left yields `4 3 1`. This then becomes the sole argument of the leftmost lambda, so `⍺` becomes the "first function", returning the first element; `4`. ## Scoring When it becomes time to test using actual data, use [this test harness](https://tio.run/##jVpLq17JdZ33r7ge6QqddJ9d7xIokEEwZOBgHDLp9EBq33ZEriXTUgim05PEGLXcagJG2JMM7ATShIAHtiEEMmn/k@@PdM7ea60618GB6HEf56tTj/1ce@16/IPbP/ruDx/fPv/e119/8@bZ5cf/9Mk7V/7HHl0@@@XlzW8fXt68Pb5dXd7889WLp8@@d3tzdXN78/2bZy/fwcDrxJH3L6/@7fr4/n764JHZ737mP9oH9znB8WPMkbarlK5uXn747jt3F3r1777WvcvrX97b/IXX/6hFH9/eXr3865urF4@/f6Mlj2GXz35xDPJVfn159fNjivsxwYP//frt02c3jz/Wi9eXz18/Ot6@/43Lm3/56lfmE8XY2LwdX959ZJcf/9SfPLz3jZhsDV1zfvT4w5fPP376@Pbqo@e3t8//7ua7V09@GBu1F2uLIYjfm1DysUM@@98nLvzwem34/nbv8vmre9t1/PpWI2LNJ1eP@Y8r3LiuLq9eX958lq7S5c1v7j343c9iw199ebz1qX/9z2tO8eiQ0bsurOPhr23HDE@OGY4PQ3y/@OrLm@vrT/aHh7r@4@rykx8di36Baba/OkT7Gx/1@h/u@6xfXlPhmOby6sv3njw8FnrynhT0bd/bvePPFiv@9r3jmz3wB498ToqounQun/3rko3P6rZy/4/bg@sH71nx0fcf0BDvfXJ581@@5S/e/slfutqPo/3kR3b5/L/9@Wsf86kv@e2rGPH@8TtM7sXLjw/DPbR2e/vk8Yd/szR0Ljd9ufoHV/vqV@XB/3fFY6TWfP7RRy9uXv4fS6@T/KH5tjsOt967@vTrYwl/xX3ltXvqoY8v3v7Zd/78W4dKjnm@ePutb/7pX1zde/fpsx/87ct3Xz59fu/Kvn6/bmnrWz6@5s3qZvvxW9qsbGabNf@Xj7/l@D@28sE77x@fzfjAXzP/5Bjbtnr84C@mEWOOuebxQzmez@N/mj4u@QL9eHBM3Y93jkfHL2lr/gp/PAYf41KOXSUf63s6BuT4ffhq2PKx9jHS5zj@HwOmL7r5Qj4s2zHXcRj/5PjBPxu@vS0dD2JDvoRPHk/Nv8eXzfeWfb7Yf47V4gWfzTcwfPHjQ9/A7vv1swyOq5BYbAqjsFA8mBg7/aeJpy3kVmJg9Rex/RSPCjZ@fL654I4fLKQQAgsZxEIxc9tSodoSh/hgK9wFNxf72I8vAy9u01wKiSvGq5RHbMx3EO/74gln2V0GGaLwx3XDBxBu1gF8sRqnKGFDjRv2gzYM2GOfw3U5/LcQif8aT1McP8cLCbKJZXJopUDBoSrfRvJZfANhFTDh08RiJ507wWZd97RdN64m467xVny@x@oDIkzLA@APjV@by0Ef1JgHmtjSHk8bLNggVpOMe8yTwhUshXjy5lZnUISrDxrokntatgKnrPADWnB2qw8Nw8iLb2xwjzmOFPoZmNYlk91qEmSZY3sjRO0D4/SFPmHxTo@tZNhw4aErNRkhwZ8c8vIDxoc9FODega3MpVEYWCzS6aThs7H1yfAQRjDj4wo7H9TpjH220D/dBlHFaPsZnogokOFHzQd2jI6zxduxYsWKAws0BoESdtA4eZiA1RCgcZ2EYGQw7wI77mGxOLkvH7vZ6dGcCwcyTA5/qJB7CChBHdPtYNB7q6RRZHKYTRHMTSEsJcUWU0R0CNI4dVIYTbAo36EHwx3GQN1kekMKF5@hvRSngiigXYiWduzWWaALW/GsLPMd4aYezhFNsoLoDoEyLsW2kGxil5vBTge1YRHCJjfHYA0tjxBgppWP2Ku/anSxFE/blnkSi80irSCy7VQMhXa80rDDtdUeMRz2g5hXEQgZt5kyBsykIHLF4BoRwX8MDy8IefCFsIyGeGR@EAjKP0dU7m4ghR6fT6vGDBhA64@oUX32yhCFTDvoWhEoG2JJRWwMqU45SGw7QmQoqigITnhjqHGE1A2i5@nhUpPaZXr0mSZSFsyX3uLnmUgsO@zXYGswQGsM0UVReUc8jgARS6URJpISUQZtZcNGarybYue0lbn85BBkRZ5JyMItVskMfQMHK5DT8S2CnU@5klskalspE05YoRLzGJkSlIqcJF/Xej7QTcUwr1IHRBU@7h82eY//UhFeKlELHjHot61sSsGWlOSxUxyt4iwbMRG2AsnNM/yG6Co0574QYbCumN1DytSaoFIOq80MLQipAFPwqxYeW@GYOicTwwDaM3qkQUcR3ywR0gEWhp3AspjTYfBY3So0hoAnw03QUaA16Dh8IWKcQIJ0ohANqR3PExc77DDTqNop@uo2AVNB0EKsaQwmiaJCyJ1ElpBWYBK3I6PYCGmLj8mxUKcgw28Y9RlOk2BUCp@X2@TAAYnxD/5aYLwIciG8cJhOqXSB6iRjLFTyAD4vyOdDm6IVTeayRPknAIcEEcfs/gbstxGVVyIo2FnHhgWpES1TYUQehGkJa0COC7ybIR02ZihjBC40jKTclpn2Eh00MPlE4FRcC6DJlfcQnrByhR@jhjDtJb4gn8NxMbjhALHNEWKyu3nB99RwoK1QSYVlSdXHeaVvD/kDPpgjxe1EOolI1toCaFglE5v5ppAQO9wK20OJIrCLLzuiDGJubHkgKmWG@rDMzLTceAwqEp6dkcUi5m8II7YSachop9k2OtXg8T1wwVCgQUcYhuJkp0WpsEJ9hghuMDjG03itQYMTS2TAqcOOOzO7Qj9DEjBWD@UUbs0SQl28UWAiMUkN0BiLlonKw39vrGeOrQwoo9JGJ3UMA2cUHUtPlTB8wusS7K7SKFR/lFV65YUhsQdqiHGJUcNUp0MUxJcUZGPB3Takv4jDg4kOhlP5QUYgiUi/45ARauDrjEiV2AWV95aEAiLYRNbz78CFiXk8A@N3ajWFrIiBjRoyjG2o5lElGHJGiWhUgGeMdhAnQmSikdO98ragGvEnI1wROnAvzwBBwC7h4RMpNsO9ElKiUL1BFgboMrFRyJ5VswcFHKPJOclMRFxm0gO6qXrTgKwBuhFPG9NiAlWS6S6NBsQkE45lVb4zhYFiZVTQqmGLQ0X5UJYTJSFt6KEx@cESK2vBEZpWkRVyg9WjfFJFDL8Ab8R0UZlGFY1g9YPgaSqNRsRqoniCJQr9DnJQSGI7wilwL@GboGlGVojT9fVxQiXK8B9F6SFf1WmZpX4G0gB5MLDRQhmzUuwbKsG6CdgrOw9@BmMDpUWiJp0YAXIijgnJGZOsCSUR@cbA2LkIGMTMjOI808crEWJCyCPoasuPo1iYLpIqXiFcI5JTFnCSoRtyWibzMqgd66EiI63BxBJYXbbg0@skivV54aMhpGIiEQDu5iYqLZK/mSBEJWNimZV2XixAZ2wqJOoKa/SimFNiOeInAnpbZQvRsSEFklDqOBQSQOYZjCpgWs@CYEsd8QIIhQSqRomSDFaYTARYQ1AbskZ4U17VdyY1llnM5BPGwtj7AhmN3BbiZVvlUYFLDlr5oJptVYgpErLBhGj8SNvYR8WOyFjaIKJmYY/wm7Rj0T@NOHjSCMLBElDAEBdDDGlMe2aC6ompbyxMF85ZWJYVWpXp8KGDcN6J0pWlAgpw4bpK/8Guk2oUa8wuiwGeLJDi03livKipkCV6BKFM3nAyrZQT2snq9pNd7NILdefVAgpulylYCsKt4TgjLYYdxLhCX9sGbW1AAOS1KkKKGaMEK8AC/g0hHtYXx4m8WDcl1kVItfDdKgxQhdVInmcUCaQfYgZYUmaMzSqfapypLixlJCuNpM1cIVBYT9DcTvQS5OeOXDbJ8zAaTtV4HYVUEj8mkySITPIXwtHGEnGF04zEm@EGqtBhpHiA/FMzOD@mR8YWoa6MmDOZd4vOAGbJKu3dh5YTayf6IUruzoCCqrwiDTDHAfYxBIHGyQSFYSQoPeHf3FbZWbmbUh157DgIKFpUc6Z4cEfQmQw7kFUC80/utTMvzpWgQRAklPtKsIOPM12jui5RH2a6yU5aECEgps8ApZXGGtGraFOrFxRdFKLgoszSRDKBPWYoaKJeTJU7XNMNmCyiKYZUxh3SgwWRzVaAhGUlmPmg4QxV0lmVRma2AyBsQsGR6BvLZC4V3RjiSNLsnSxdEUNR5B4w64j7lheVQgosk7p21TXCDEC/IZZYBVqPv2z/wGyMHDuDXYopENEJeQszTF@FhREdZYQKFfqF/KkZp4OYTASBKZMKa4nYBYhCvB5IFwW@Y@Rn1TIoTKVlU@ZPpFkD87sjFqFORrkQW2O@aXf4U1EiK84ZU2oh4S82uK2W1MBg1ByZMQbYIuLSUITMVHNmCwMcF6wqLWI5de3T2kpXklKorhOIN9FRY/UeKyBbVoVFFhZOaF0UrwG5EZ@jDhc8yHc4t9ViYEsp0hXjTRFIDfZ3yY3nKeIr/R8q0sFQmUMnrFJRByRMI2pIbb7CWEYyphD2IaudSIH9xuF5B12ltCjGLHqtqzEFo0TMqnf6H4Q8KMwVNxmhnd8Ep2KLIB6s9braAmIeE9tCqgDF5ZFByESrvyflTEhi8DOnxGgqUSERru4nkBokVRusPKuOCExmp1NmkVCZtUj4YchkIusxLzVkefW5WQitLh6MnVAriBg7qz8xEZX@jFhIxpfQjsZqvv9ANJ3gIVELZJjBP4i8j4LCcCquIvaxcfoGTiftZ1/c0EhOSq@JnjPZF2KhTy4rSnSGNfFidlq3bCYTOrU7xaiHV7cZkoURUaLoCVba7OymhgXIjzsavKhL2PSEgAy9h8hRJJsEuE3Ji03duXXaUuKqlV2CwtDQCWmZb@hj6ijkAjQ1dYsBfYcEmJEFZBJEn2HplTcWiKvKukKR0LsY7MVVEnK8OjDZoSyrTwuxRn9uUTCVjLDyRRYvmVheraaNut8q8MtC5v1ENYVqy0IUALNDWHEnOEvkf9OmbByefraxGPkbM2UDmqGZTubRDpKdFzNWkRiplf4@1ejOvHTRSdBNXploBHVpg3L74qF4zWTqRkgnnuLljErCJBX1E9haWq3bLHqIzFmsnVf3tK2EzlsIuwfTjgsA8K1J9gQRhp0GoWMyoPkM9JFNxkIcEG9XpStyCM49ACt0MaHrRspJxRTVbm21JRfiGJvO4vtE4GJ9mYXNMskp3NUxNTYmwU0aPAdsobKfoMJ5sA5ig35dT2EPfiODnOgY8JakjvwxRRUjMDd1gKvYNOOFmyy4nVkJoItvquiy6Cam8cS4APMxFEd19UsmbV9kL5NkUrHGIhwcT5yziyklpAEA38XqhxPL@tnErVyiqO5P@MR1K8hOi77TeYpz8nbWukiVlx82NhNPeYEFOFkvO2c3bbpJG/sCGoGv0s70VO@gLZ2EJTltu@miEAATaB9CI9l/F4mbdLTJKyr4fTBYGK9KwOIn2dMkPgT3sHRpo1HBlVdUTH3rCiV1VrLLJSYTDu9ECOulzmDZyXsZOVWRSmR8UleyqrCwzpbbqkRBvenGQ1IGTWrgzMUZdCZFdbCGON6dNK0N1REn1JASKqjIoSqVqKKcpNvuJfmgi6S84Q5BlQtHaWoCYHAH3kSsJyugZlzl/RDkt6m8sjBCxWbRIY@CufJUgGRnQ4w2MmXyJB@jS0SXHpsYPd7pa2jENmavBcCN1xzV4A84AqlLz0V3J08CfpWPUSueTe7E6UUZGWmPvK6Z4HaPsb@TVvHGtCF2blfD8vRhl@y6uJDFLqKfQzMNXwAi2NK6FZbZJwfv1SmVTvY3q/LJIGM7rqd5k0VdKNEtEBLPcRfs5jg3XDWt1pOtFDlE6qXVZttspXv0lYTWxPSX874GKxXjPZZlXWTQjOV4BZs4mBeK0nVZ10ltibyJzdQD5POyI8qQu1otx6lLEnXdZGCt3gCc8rrI0s5@FjYVUEkUBW23rysdk5VGk9WmQLgRLxMItnU3lz2bxfu1MwHspFFMHO0KlyY2jiVb0gWXqiZH1lUm1GC5KjqlxT503lqquuAaYk9Njb/drTyzk5Wxd5y2a4dKY@ku0UjoUE9eWAVGiEUJIeJiW8lavA7pdN3LNLXdAkwbCKi52mu8yMd7VMGNJul0qZz03LpVGo3Fsi5ZF7YUUlWRVRbRnxfsZG8qGjuMb3Ux3pUtAENEmCou2QjBFcCzPCePSArFFJeVy5pKCqW9tq5OJOSMiSOOsyGvCywF9RNhPhHhwhGKOwqU3PVgvJ7nbRJbfH6R9tjE9v1GSrI7l1Gi4E5J3pl59aFxN2rwVcB8wpuG8mPcuQti59Ucwbe0C82cRgAGpRDQ5dPZ91WyoCbceNEdfQ14VF1YVRc3iL6YdybrNbK4YhYnSUUB1ITkjdYI5E/QCc4L5y18YyBeVlF5SXwljDSzgKalFekOFz90HdLuhGDri3iYrPaC6Jh3dJ3FjadOiqYQysVo3WEvDCjki9gRzLwwnHmFk5AnL9yTBJMmLwPzPgXctajLb8JAxC@dlyDYDyKRyps7nbdTMmNXknNXCKHS2bCduQh8sTBEXwlcppWzIwSeB4w0vaOQ@4VBHgIy9gyMoVpZlLdTNl4@aMI/jH6NXp5Ur0wUDo2gNhz@fwA "APL (Dyalog Unicode) – Try It Online") (linked populated with pretest data). The test cases go in the Input field, and the Output will be the total byte count of all 500 programs together. (It will also throw an error, but that's just because it afterwards tries to evaluate the Input as-is.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal) ``` ´⎚´§´⪪⪫IA ”y¦ Lυ⊞υω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPpUd@sQ8sfrVqlpGnNBRHyys/M03BOLC7R8MwrKC3R0NTUUVBSUNKEK1A6tEzh/Z4151sfdc0733q@E6j1///oaFMdQ3Mdcx1DYx2j2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ´⎚´§´⪪ ``` Output the literal string `⎚§⪪`. ``` ⪫IA ``` Cast the input array to string, join with spaces, and print. ``` ”y¦ Lυ⊞υω ``` Output the literal string `¦ Lυ⊞υω`. Output of for example `5,17,7,13,2` is `⎚§⪪5 17 7 13 2¦ Lυ⊞υω`. [Try it online!](https://tio.run/##AS4A0f9jaGFyY29hbP//4o6awqfiqqo1IDE3IDcgMTMgMsKmIO@8rM@F4oqez4XPif// "Charcoal – Try It Online") Explanation: ``` ⎚ ``` Clear the canvas, so that only the last output is visible. ``` §⪪5 17 7 13 2¦ Lυ ``` Take the length of the predefined list `u`. Use that to index into the list of integers that have been split on spaces and output the selected element. ``` ⊞υω ``` Push a dummy variable to the predefined list `u`, so that the next copy will output the next element of the list. Total output length = (length of all integers in all lists) + (number of integers in all lists) + (number of lists \* 9) characters (SBCS). [Answer] # [Haskell](https://www.haskell.org/), generates Haskell ``` main = interact $ ("main=print$("++) . (++"!!)$ -1\n +1--") ``` [Try it online!](https://tio.run/##FYjBCoMwEER/ZQ05JOykuCa2XvwS6yEUoVIbxPr/6crMPJj3zr/Psm21fvNaaKS1nMuRXydZcuZy436os84we7qRYzZN4y0FeRZiCcH4WqceHR6IygjpIa2@DpIgArlfjZqkG5DmPw "Haskell – Try It Online") For the first testcase `[5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4]` it produces the following program: ``` main=print$([5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4]!!)$ -1 +1-- ``` Try it [once](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RFI9pUx0jHXMcYSBrrGJrqGBoAeUY6hiY6hoY6hmYgZAyEJkBsoWMSq6ioqaKga8iloG2oq/v/PwA "Haskell – Try It Online"), [doubled](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RFI9pUx0jHXMcYSBrrGJrqGBoAeUY6hiY6hoY6hmYgZAyEJkBsoWMSq6ioqaKga8iloG2oq0stc/7/BwA) and [trippled](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RFI9pUx0jHXMcYSBrrGJrqGBoAeUY6hiY6hoY6hmYgZAyEJkBsoWMSq6ioqaKga8iloG2oqzvYzPn/HwA). This uses the same approach as my Haskell answer to [*I double the source, you double the output*](https://codegolf.stackexchange.com/a/132632/56433). The length of each generated program is the length of the input list as string plus 25, thus the score for the currently available testcases is `12266 + 500 * 25 = 24766`. This shows that the code to data ratio is basically equal, and I doubt it is possible to write small enough decompression code which will decreases the score. It might be possible if the lists where much larger. [Answer] # [Python 2](https://docs.python.org/2/), generates Python 2 ``` import sys a=`input()[::-1]`.replace(' ','') sys.stdout.write('print%s[-open(__file__,"a").tell()/%s]#'%(a,len(a)+37)) ``` [Try it online!](https://tio.run/##DcrRCoIwFAbg@55CCtlGv9Y5aqbQk4jYqEWDpcMtwqc3r7/PL/E9jbyu9uOnOSZhCTt9u9vRf6NUXdtm1N/z2XinH0aKREAItdtWHuJz@sb8N9u4gZ/tGNPQZZM3oxyGl3VmGLDXe5VH45xUpzT0B5FKDbcNrY5FrdS6dnQGEYhBBagEVaALqAZdQQ34DCYwgwtwCa7AF3ANvoKb/g8 "Python 2 – Try It Online") For the input ``` [10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29] ``` the generated program is ``` print[29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10][-open(__file__,"a").tell()/98]# ``` which is 98 bytes. Adapted from [this solution](https://codegolf.stackexchange.com/a/132565/78410) in "I double the source, you double the output!". Dammit, two shorter answers popped in before I finished writing this answer. [Answer] # Java 8, generates Python 2 ``` interface M{static void main(String[]a){int l=a[0].length();System.out.print("print"+a[0]+"[open(__file__,'a').tell()/"+(l+35+(l+"").length())+"]#");}} ``` [Try it online.](https://tio.run/##Pc2xDoMgGATgVyF0EAKlTaztYPoInRwJIUTRYhGN/jVpjM9OtUOXu@XLXWtmc@wHG9rqFaMLYMfalBY9lgkMuBLNvatQZ1wgBYwuNFIZumwO@buRZyW8DQ08Cc2LzwS2E/0bxLBBIPhXmO2MYbmfEK1r563WPDEJFWC9J/SEGfEszfbEmP4XKcPqgGm@rjFGmfILz/iV39QX) I.e. `[3,4,5,6,7]` generates this Python 2 program: ``` print[3,4,5,6,7][open(__file__,'a').tell()/48]# ``` [Try it online once](https://tio.run/##K6gsycjPM/r/v6AoM68k2ljHRMdUx0zHPDY6vyA1TyM@Pi0zJzU@Xkc9UV1TryQ1J0dDU9/EIlb5/38A); [Try it online twice](https://tio.run/##K6gsycjPM/r/v6AoM68k2ljHRMdUx0zHPDY6vyA1TyM@Pi0zJzU@Xkc9UV1TryQ1J0dDU9/EIlaZROX//wMA); [Try it online three times](https://tio.run/##K6gsycjPM/r/v6AoM68k2ljHRMdUx0zHPDY6vyA1TyM@Pi0zJzU@Xkc9UV1TryQ1J0dDU9/EIlaZtsr//wcA). Generated Python program is based on [*@Mr.Xcoder*'s answer for the *Third time the charm* challenge](https://codegolf.stackexchange.com/a/157883/52210). **Explanation:** Java 8 code: ``` interface M{ // Class static void main(String[]a){ // Mandatory main-method int l=a[0].length(); // The length of the first argument // (Note that this is the length of the input as String, // not the size of the array) System.out.print( // Print: "print" // Literal "print" +a[0] // Appended with the argument +"[open(__file__,'a').tell()/" // Appended with literal "[open(__file__,'a').tell()/" + // Appended with an integer that is formed by: (l // Getting the length we got earlier +35 // +34 for the rest of the Python 2 code + 1 +(l+"").length()) // + the length of the length (<10→1; 10-99→2; etc.) +"]#");}} // Appended with literal "]#" ``` Python 2 code: ``` print # Print [3,4,5,6,7] # From this array [ # The `k`'th item, open(__file__,'a').tell() # where `k` is the length of its own source code / # divided by 48 # the length of its own source code (once) + 1 ]# # With a trailing comment, so we can repeat the program ``` [Answer] # Python 2, Generates C++ This isn't going to beat any records, I was mainly interested in thinking about if I could figure out how to do it :) Use the fact that global variables are run before main, and so can increment a global variable, then using a #ifdef to ensure main is only defined once. ``` import sys print("""#include <stdio.h> #ifndef A #define A int v; int d[]={""" + sys.argv[1] + """}; struct C{C(){v++;}}; int main(void){ printf("%d",d[v]); } #else C c1; #endif """) ``` [Answer] # Bash, outputs programs in Perl 5 Bash program can be called like `script.sh 1,2,3`. Perl program should be called with the `-E` flag. ``` echo "shift@a;@a=($1)unless@a;END{say\$a[0];exec'true'}" ``` The generated `perl` code for an input of `4,7,8` is: ``` shift@a;@a=(4,7,8)unless@a;END{say$a[0];exec'true'} ``` Pretty brute force. Removes an element of the array (`perl` doesn't care that the array doesn't exist at first), sets it if it is not already set. It then echoes the first element of the array at the end. (The `END` block is run last). The `exec 'true'` quits the program, so that the further `END` blocks are not executed. Example: ``` #Once $ perl -E "$(bash script.sh 4,7,8)" 4 #Duplicated twice $ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)" 7 #Duplicated thrice $ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)" 8 ``` [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), generates Runic ``` 74akw94/85akw R32B~~?US' Sqq1Ky1Ky \i<{1[lil1-{S{)]{{1KyB D'0$'´$$' $ Rl0) ? R"{Zs$;|1|l;|y"@ "UwR'10<|I+}"$~ /' Su0 Rakwc4akw/ ``` [Try it online!](https://tio.run/##KyrNy0z@/9/cJDG73NJE38IUSHMFGRs51dXZhwarKwQXFhp6VwIRV0ymTbVhdE5mjqFudXC1Zmx1NVDUictF3UBF/dAWFRV1BRUFEAjKMdBUsOcKUqqOKlaxrjGsybGuqVRy4FIKLQ9SNzSwqfHUrlVSqVPQBxpeasClAAFBQHuTQY7Q///f0FDByFDB2FDBxFDB1FDBzBAA "Runic Enchantments – Try It Online") Takes input as a space-separated list of values. [Output done once](https://tio.run/##KyrNy0z@/z@0PEjd0MCGy1O71uDQFjNDBSBpCiZNwKQxmDQCk4aGCtVRxSrWXIZcOdZclf//AwA "Runic Enchantments – Try It Online") [Output done twice](https://tio.run/##KyrNy0z@/z@0PEjd0MCGy1O71uDQFjNDBSBpCiZNwKQxmDQCk4aGCtVRxSrWXIZcOdZclRRo/f8fAA "Runic Enchantments – Try It Online") [Output done four times](https://tio.run/##KyrNy0z@/z@0PEjd0MCGy1O71uDQFjNDBSBpCiZNwKQxmDQCk4aGCtVRxSrWXIZcOdZclUNO6///AA "Runic Enchantments – Try It Online") Utilizes the continuous numerical read mode command, `´` that was committed [on Jan 12](https://github.com/Draco18s/RunicEnchantments/commit/667df6ba47f3f87b41dab178105ddaa1141e4ded) and I found this question on the 14th. This command allows arbitrary length values can be encoded as without this feature it would be very difficult to do so (e.g. `1392` would need to be represented as `1X3+X9+X2+`, necessitating an additional loop at a minimum); precisely the problem I wanted to solve when I created the `´` command. In the original code, the `|` in the strings `"{Zs$;|1|l;|y"` and `"UwR'10<|I+}"` are replaced with `\n` (which sit in the grid and not modify it, as they normally would) with `w`rite commands: `74akw`, `94/Rakw`, `c4akw`, and `85akw`. The original characters can be literally anything. `|` was chosen to be a symbolic placeholder that visually represented what I wanted. Several bytes saved (if unscoring ones) by not having to reflectively add an entry point, as `wR'10<` writes an `R` into a location where one already exists (position `0,1`), and then proceeds to fill its stack with junk before running out of mana, following a looping sequence `U"'i34`. The resulting output code works by using the `w`rite command to change the first character on the second line to a `R`ight redirection (so only one IP executes a print statement), with clever use of stack length resulting from taller and taller programs to determine which index to read. Every other IP changes that same location to the same instruction and terminates. Everything else goes unused. [![Execution flow](https://i.stack.imgur.com/zaEag.png)](https://i.stack.imgur.com/zaEag.png) *Image is out of date, but sufficient for flow explanation.* Each execution of `1Iy` maintains the IP's ability to handle a larger and larger stack (caused by the `l` command), the size of which allows the program to determine how many copies of the base source code there are. The final `1` is used to increment the previous `l` to the required number when rotating the stack (created next) in order to arrive at the correct value. The `Z` command negates this value so that the stack rotates in the correct direction. The original input array is then encoded using continuous read mode, primed with a 0 to avoid incrementally modifying the same value, to read the original inputs. The space NOP is required to exit continuous read mode and allow the subsequent 0 to prime the stack again. Score should equal approximately `3+v.toString().length`, for each array entry `v`, `+23` for each array. Approximately `(2.55*total length of input)` or `33837` for the sample input, if I did things right. Minor changes were introduced into my expected final program due to side effects introduced in the same build regarding the `s` command, however it resulted in a better score at the same time. ]
[Question] [ You know what a **palindrome**, a **prime** and a **date** are. > > Your task is to list all dates in 100 thousands of years that fulfill > all three characteristics. > > > Nevermind anything but the numbers, use the following formats: **YYYYMMDD** and **YYYYYMMDD**. Dates between 0000-01-01 and 9999-12-31 should be printed as **8 digit** palindromes dates (If there is any?) and dates between 10000-01-01 and 99999-12-31 should be printed as **9 digit** palindromes. It's not mandatory to list the dates in chronological order. **Example part of valid output.** First three 9 digit prime palindromic dates: ``` ... 100111001 100131001 100161001 ... ``` **Rules** [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~144~~ 141 bytes (134+7 for the `-rprime` flag) Saved 3 bytes thanks to [benj2240](https://codegolf.stackexchange.com/users/77973/benj2240)! ``` ('01'..'12').map{|m|('01'..'31').map{|d|(?0..?9).map{|k|q=m+d y=q.reverse+k r=y+q Time.new(y,m,d).day==d.to_i&&r.to_i.prime?&&(p r)}}} ``` [Try it online!](https://tio.run/##NYq9DsIgFEb3PoUTP6HeFJ0cCC/hbmpgIA0FbquGCK8umsZOJ9/5Dj7uuTVGB0kBqDxRDn6M7@LL7s5yd6YwPQDoy39PJSkvTJdVArRPi4sVU4cqi9Rdnbcw2xfLve8NBzNmpQys4eYIwY0Q8RdpQlg8IK@1tvYJcXVhXtoRt/ML "Ruby – Try It Online") The algorithm: * generate all possible MMDD combinations, from "0101" to "1231" * generate all years for that date that would result in a palindrome, by reversing the MMDD string and adding in the middle, in turn, all chars in the (0..9) range * check if that is a valid date by creating a `Time` instance with the given `y`, `m`, `d` values. If the resulting time object has a `#day` value equal to `d`, then that was a valid date. Otherwise, it would shift the date (for example, `Time.new 2018,2,30` returns `2018-03-02`). * check if the valid palindrome date is also a prime and display it if it is. The inner loop was initially a function that was called for each element in the `(?0..?9)` range, as well as for the empty string. Since the empty string produced no results (there are no valid 8 digit prime palindromes), I decided to remove it and refactor to this version. [Answer] # [Python 2](https://docs.python.org/2/), ~~116~~ ~~107~~ ~~128~~ ~~122~~ 119 bytes ``` def g(n=9**8): while n<1e9: n+=2;m=n/100%100 if 0<m<13and n%100<31+(m+m/8)%2and`n`[::-1]==`n`and 2**n%n==2:print n ``` The second half of the 4th line is inspired by [mxdsp](https://codegolf.stackexchange.com/users/46026/mxdsp)'s [answer here to another golf question](https://codegolf.stackexchange.com/a/60150/76878). ## Explanation The function `g()` takes an argument only to initialize the `n` variable using its default value. The initial value is an odd number that's as short as possible and as large as possible while still being less than the first valid answer 100111001. Loop until `n` reaches the end of the date range 109. Increment `n` by 2. `m` is the month of date `n`. If `n` is a valid date, palindrome and prime, print it: * Date: + `0 < m < 13` checks that `m` is a valid month. + `n % 100 < 31 + (m+m/8)%2` checks that `n`'s day of the month is valid. `(m+m/8)%2` adds `1` for all months with 31 days. Credit for that goes to [ArmanX's answer](https://codegolf.stackexchange.com/a/153389/76878). There are no primes for February 29-30. * Palindrome: ``n`[::-1] == `n``. The backticks stringify `n`. `[::-1]` reverses the string. * Prime: `2**n % n == 2` is a [Fermat primality test](https://en.wikipedia.org/wiki/Fermat_primality_test). That test is only probabilistic. There are also non-primes that match. But not in the range of numbers we're looking at. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 155 bytes ``` ⎕CY'dfns' n←⍕x m←(⍎2↑¯4↑n) d←(⍎¯2↑n) :If n≡⌽n :AndIf 1 pco x :AndIf m<13 :AndIf d<32 :If m d≡2 29 :AndIf (400|⍎((≢n)-4)↑n)=0 ⎕←x f x+72 :End ⎕←x :End f x+1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO96FHbhDSFiv@P@qY6R6qnpOUVq3PlAcUe9U6t4MoFMjQe9fYZPWqbeGi9CZDM0@RKgQoeWm8EEbDyTFPIe9S58FHP3jwuK8e8FCDfUKEgOV@hAsbNtTE0hrFTbIyNwHpyFVKAuowUjCxhUhomBgY1QKM1NB51LsrT1DXRBNtga8AFdB7Q2gouoFO1zYHaXfNS4GJgDkjCEOSh/0DLDYDA0MAQAA "APL (Dyalog Unicode) – Try It Online") This is a Tradfn (**trad**itional **f**unctio**n**) that takes one argument `arg = yyyymmdd` or `arg = yyyyymmdd`. Usage is `f arg`. This will not output anything when the argument starts at `10000101` because it doesn't find a prime palindrome date in 60 seconds. Here is a less golfed approach that will output the OP's example output of ``` 100111001 100131001 100161001 ``` ([Try it Online!](https://tio.run/##RVBBDoIwELz3Fb1RYkjaQiISPRjjwSd4JFa8QDV6qYlnlESNHniAfoAXeOEp@xFcK@il2Znp7Ew23qSe2sfpetXA6biF/JZQ08C1nMwdleidQzRycCkNyXBgcLlKyO91FeCrXaJasq7kl4hmCdVQPOD80iQaa4VY0M1iTU0Hs6Hwu1kNfWk9GVXoklQOOokFnB9wNWNQPLXrBa5NGHGC9TDWEKza66N9qtWPs@C/UEjqC/sxDPsc1XS3/MSi1PIda4Gw/s8pGqzNueBCyvAN "APL (Dyalog Unicode) – Try It Online")) Notice that both codes are the exact same until right before calling the function recursively for the next date. While the golfed version just calls it as `f arg+1`, the less golfed code jumps from day `31` to day `01` and from month `12` to month `01`, which speeds it up quite a bit. ### How it works: ``` ⎕CY'dfns' ⍝ Copy (⎕CY) all dfns to enable the use of pco. n←⍕x ⍝ Assign (←) the input to the variable n. m←(⍎2↑¯4↑n) ⍝ Take (↑) the last 4 (¯4) elements of n, then take the first 2 elements of that and assign to m. d←(⍎¯2↑n) ⍝ Take the last 2 (¯2) elements of n, and assign to d. :If n≡⌽n ⍝ If n matches (≡) its reverse (⌽) (is a palindrome) :AndIf 1 pco x ⍝ And a prime (1 pco) :AndIf m<13 ⍝ And month < 13 :AndIf d<32 ⍝ And day < 32 :If m d≡2 29 ⍝ If it is 2/29 :AndIf (400|⍎((≢n)-4)↑n)=0 ⍝ And the year mod 400 = 0 ⎕←x ⍝ Print x f x+72 ⍝ call f with arg year0301 :End ⎕←x ⍝ Print x :End f x+1 ⍝ call f for the next date. ``` [Answer] # Python 3, 163 bytes ``` r=range for m in r(1,13): for d in r(1,31+(m%2==(m<8))-2*(m==2)): t="%02d"*2%(m,d) for i in r(10):x=int(t[::-1]+str(i)+t);all(x%i for i in r(2,x))and print(x) ``` Solution is fairly long (and probably can get improved upon), but doesn't use any built-in functions for prime/date/palindrome checking. A somewhat ungolfed version for clarity: ``` for month in range(1,13): for day in range(1,31 + (month%2==(month<8)) - 2*(month==2)): t = "%02d%02d" % (month, day) for i in range(10): x = int(t[::-1] + str(i) + t) if all(x%i for i in range(2,x)):print(x) ``` Valid dates are generated by choosing a month and day. As commented before, only size 9 need be considered. Also note that leap years aren't considered. This isn't required because of the lucky coincidence that palindrome primes of length 9 which end on 0229 simply don't exist (other date anomalies like the 30th February of 1712 can be discarded for the same reason). Next the middle digit is chosen freely, and a prime test is performed. Because of the prime test had to be as short as possible, it is very naive and thus cripplingly slow. Using an external library could solve this (and save some bytes), but as mentioned before I didn't want to use any. [Answer] # WolframLanguage (Mathematica) 187 bytes There may be some reduction in size to be found. Explanation to follow... ``` t=ToString;p=PadLeft;d=DateObject;Cases[""<>{t/@p[#,If[Length@#<5,4, 5]],t/@ p[#2,2],t/@p[#3,2]}&@@@(IntegerDigits/@#[[1]]&/@DayRange[d@#,d@#2]),x_/;PalindromeQ@x&&PrimeQ@ToExpression@x]& ``` **Test cases** ``` t = ToString; p = PadLeft; d = DateObject; Cases["" <> {t /@ p[#, If[Length@# < 5, 4, 5]], t /@ p[#2, 2], t /@ p[#3, 2]} & @@@ (IntegerDigits /@ #[[1]] & /@ DayRange[d@#, d@#2]), x_ /; PalindromeQ@x && PrimeQ@ToExpression@x] &[{10011, 10, 1}, {10017, 1, 1}] ``` (\* {"100111001", "100131001", "100161001"} \*) **Explanation of code** `DayRange[d@#,d@#2]` returns all of the dates between `{10011, 10, 1}`and `{10017, 1, 1}`. In this case, it returns approximately 5 years, 4 months of dates (precisely 1920 dates). Leap years are taken into account. The dates are returned in Wolfram-standard formatting. For example, the first date will appear as `DateObject[List[1,1,1],"Day","Gregorian",-5.`]` `#[[1]] & /@` will remove the part of the date, in each date, that concerns us. In the example, `DateObject[List[1,3,7],"Day","Gregorian",-5.]` returns the abbreviated date, `{1,3,7}`. `t/@p[#3,2]}` or `ToString/@Padleft[#3,2]` pads the third element, namely, the 7 standing "for 7th day of the month" as `"07"`. Similar padding is provided for the single digit symbol for the month of March, namely, `3` is returned as `"03"`. `p[#, If[Length@# < 5, 4, 5]]` pads the year with zeros to reach the length of a 4 or 5 digit string. In this case, January, namely `1`, is returned as `"00001"'. `"" <>...` joins the strings. In this case, it returns `"000010307"`. `Cases[...x_ /; PalindromeQ@x && PrimeQ@ToExpression@x]` returns those cases, among the 1920 dates, that are palindromes and primes. [Answer] ## [Javascript](https://www.javascript.com/), ~~187~~ 177 Assumptions: no matching 4 digit years; no matching days in February between 29-30 ``` p=n=>(n<10?'0':'')+n;f=n=>n[3]+n[2]+n[1]+n[0];for(m=13;--m;)for(d=31+(m+(0|m/8))%2;--d;){for(y=10;y--;){z=p(m)+p(d);Y=+(f(z)+y+z);for(i=2;Y%i&&i*i<Y;i++);if(Y%i)console.log(Y)}} ``` It works like this: ``` p=n=>(n<10?'0':'')+n; //Prepend a 0 for 1-digit numbers and convert to a string f=n=>n[3]+n[2]+n[1]+n[0]; //Flip four digits for(m=13;--m;) //Month loop, from 12 to 1 for(d= 31+(m+(0|m/8))%2 //Calculate the days in the month, allowing Feb. 29 & 30 ;--d;){ //Day loop for(y=10;y--;){ //Middle digit loop z=p(m)+p(d); //Prepend zeros to the month and day Y=+(f(z)+y+z); //Flip the digits; append the middle digit, //month, and day; convert back to an integer for(i=2;Y%i&&i*i<Y;i++); //Check if it's a prime if(Y%i)console.log(Y)}} //If it doesn't divide evenly, it's not prime. Print it! ``` History: * 187 to 177: There are no prime palindrome dates that fall on Feb. 29 or 30, so we can pretend Feb. has 30 days and save 10 characters. Notes: Through testing, I found there are no valid matches that are 4-digit years or fall on Feb. 29 or 30. There are, unfortunately for the sake of the code, exactly five (invalid) results that fall on the 31st of various months that only have 31 days. [Answer] # Java 10, ~~329~~ ~~327~~ ~~320~~ ~~318~~ ~~312~~ ~~308~~ ~~307~~ 264 bytes ``` v->{for(int y=9999,m,d;++y<1e5;)for(m=0;++m<13;)for(d=0;++d<32;)try{java.time.LocalDate.of(y,m,d);var t=y+"".format("%02d%02d",m,d);long n=new Long(t),x=1;for(;n%++x%n>0;);if(t.contains(new StringBuffer(t).reverse())&n==x)System.out.println(t);}finally{continue;}} ``` -1 byte thanks to *@assylias*. **Explanation:** [Try it online](https://tio.run/##fVLBjtowEL33K6ZIILuAIaBdqUrSQ9VLpWV72GovVQ/GmSxmHTtynKAI@HY6Tuh1rdijN555k@eZo@zk8li835SRTQM7qe35E4C2AX0pFcJzhACd0wUo9hpNx1PyXWnT9wwWcrh1y2/n0nlGidDnX2ktqkWRzud9luBDyuNdla/JUWXJdsTFgItsu0l58P35SP8igq5QPDklzQ8ZULiS9ZGJp530EPJ@PpkISq5kYJPpelPEPRkjdMmCUM4GEtEwiyd4CV7bt@9tWaJngQuPHfoGGeezegh4cvaNLjh/6ZuAlXBtEDXlBGPJnV5LbaUx/Tmyattier3eovjVCnbOI2BZaqWRRLN9G8AQHXoORFHhUh1QvaOHxsEJQarQRi44yA6BCtWU4Cz8/vlLCKLcO2dQWqhZZAHLx4cnUTbPk8uF2ekmS2Yz@znfXC52ur2DLedDYFweQ@stlNI0mA7e@M4DX5UPljO2k@EgandidrEWD3ye8NVjwRd66IbO8ir9TxhrT9njF71MeJbEohHMI/io5t0TfIvjoNBRt3ujFTRBBjLDNFXUJjZ26M9feZcbmxKHkHFhhWK2NeY@bdfbPw) (note: the prime-checking part has been replaced with a more efficient separated method, although even with that it still times out after 60 seconds, only outputting the first ~115 palindromic prime dates). [Pastebin of all 197 outputs from a local run.](https://pastebin.com/iyntGMFW) ``` v->{ // Method without empty unused parameter and no return-type for(int y=9999,m,d;++y<1e5;) // Loop over the years in the range [1000,9999]: for(m=0;++m<13;) // Inner loop over the months in the range [1,12]: for(d=0;++d<32;){ // Inner loop over the days in the range [1,31]: try{java.time.LocalDate.of(y,m,d); // If it's a valid date: var t=y+"".format("%02d%02d",m,d); // Convert the numbers to a String in format "yyyyyMMdd" long n=new Long(t), // Convert this String to a long x=1;for(;n%++x%n>0;);// Prime-checking loop if(t.contains(new StringBuffer(t).reverse()) // If the string is palindromic &n==x) // and the long is a prime: System.out.println(t); // Print the string with trailing newline }finally{ // If it isn't a valid date: continue;}}} // Continue to the next iteration of the inner-most loop ``` [Answer] # VBA, 347 ``` Sub PalindromeDate() Dim DateString As String For i = 0 To 9999 For j = 1 To 12 For k = 1 To 31 DateString = Format(i, "0000") & Format(j, "00") & Format(k, "00") If DateString = StrReverse(DateString) Then Debug.Print DateString Else End If Next k Next j Next i End Sub ``` [Answer] # Deadfish~, 10529 bytes ``` {iiiii}dcdcicdciiicdddcicdcic{dddd}ic{iiii}dcdcicdciiiiiicddddddcicdcic{dddd}ic{iiii}icdddcicdciiiiicdddddcicdciiic{dddd}dc{iiii}iiiiic{d}iiicicdcccicdc{i}dddc{dddd}dddddc{iiiii}dddc{d}icicdciiiiiicddddddcicdc{i}dc{ddddd}iiic{iiii}dcccdcicdciccc{dddd}ic{iiii}dcccdciicddciccc{dddd}ic{iiii}dcccdciiiiicdddddciccc{dddd}ic{iiii}dcccdc{i}dddc{d}iiiciccc{dddd}ic{iiii}iiiiicddddddccdciicddcicciiiiiic{dddd}dddddc{iiiii}dddc{d}iiccdc{i}dc{d}icicc{i}ddc{ddddd}iiic{iiii}dcicdcdc{i}ddc{d}iicicicdc{dddd}ic{iiii}iiiiicdddddcdcdciiicdddciciciiiiic{dddd}dddddc{iiii}iiiiicdddddcdcdc{i}ddc{d}iiciciciiiiic{dddd}dddddc{iiiii}dddc{d}iiicdcdciiiiicdddddcicic{i}dddc{ddddd}iiic{iiii}dciicddcdciiicdddciciicddc{dddd}ic{iiii}dcdciicddciiiicddddciicddcic{dddd}ic{iiii}dcdciicddc{i}dddc{d}iiiciicddcic{dddd}ic{iiii}icdddciicddciiicdddciicddciiic{dddd}dc{iiii}icdddciicddc{i}dddc{d}iiiciicddciiic{dddd}dc{iiii}iiiiic{d}iiiciicddcicdciicddc{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiiciicddc{i}dddc{d}iiiciicddc{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiiciicddc{i}ddc{d}iiciicddc{i}dddc{dddd}dddddc{iiii}dccicddciiicdddciicdcc{dddd}ic{iiii}dccicddciiiiiicddddddciicdcc{dddd}ic{iiii}icddcicddciicddciicdciic{dddd}dc{iiii}icddcicddciiiicddddciicdciic{dddd}dc{iiii}icddcicddciiiiicdddddciicdciic{dddd}dc{iiii}icddcicddc{i}ddc{d}iiciicdciic{dddd}dc{iiii}iiiiicddddddcicddccciicdciiiiiic{dddd}dddddc{iiii}iiiiicddddddcicddciicddciicdciiiiiic{dddd}dddddc{iiii}iiiiicddddddcicddciiicdddciicdciiiiiic{dddd}dddddc{iiii}dciccddciiiicddddciiccdc{dddd}ic{iiii}icdccddciiicdddciiccic{dddd}dc{iiii}icdccddc{i}ddc{d}iiciiccic{dddd}dc{iiii}iiiiicdddddccddciiicdddciicciiiiic{dddd}dddddc{iiii}dcdciiicdddccciiicdddcic{dddd}ic{iiii}dcdciiicdddciiiiiicddddddciiicdddcic{dddd}ic{iiii}icdddciiicdddciiiiicdddddciiicdddciiic{dddd}dc{iiii}iiiiic{d}iiiciiicdddccciiicdddc{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiiciiicdddciiiiiicddddddciiicdddc{i}dddc{dddd}dddddc{iiiii}dddc{d}iciiicdddciicddciiicdddc{i}dc{ddddd}iiic{iiii}dcciicdddciiicdddciiicddcc{dddd}ic{iiii}dcciicdddc{i}dc{d}iciiicddcc{dddd}ic{iiii}icddciicdddciicddciiicddciic{dddd}dc{iiii}iiiiicddddddciicdddcicdciiicddciiiiiic{dddd}dddddc{iiii}iiiiicddddddciicdddciiiiiicddddddciiicddciiiiiic{dddd}dddddc{iiii}iiiiicddddddciicdddc{i}dddc{d}iiiciiicddciiiiiic{dddd}dddddc{iiiii}dddc{d}iiciicdddciiiiicdddddciiicddc{i}ddc{ddddd}iiic{iiii}icdcicdddc{i}dddc{d}iiiciiicdcic{dddd}dc{iiii}icdcicdddc{i}dc{d}iciiicdcic{dddd}dc{iiii}iiiiicdddddcicdddciicddciiicdciiiiic{dddd}dddddc{iiiii}dddc{d}iiicicdddciiiicddddciiicdc{i}dddc{ddddd}iiic{iiiii}dddc{d}iiicicdddc{i}dddc{d}iiiciiicdc{i}dddc{ddddd}iiic{iiii}dciiccdddciicddciiiccddc{dddd}ic{iiii}dciiccdddciiiiiicddddddciiiccddc{dddd}ic{iiii}dcdciiiicddddccciiiicddddcic{dddd}ic{iiii}dcdciiiicddddciiicdddciiiicddddcic{dddd}ic{iiii}dcdciiiicddddciiiicddddciiiicddddcic{dddd}ic{iiii}icdddciiiicddddciiiiicdddddciiiicddddciiic{dddd}dc{iiii}icdddciiiicddddc{i}dc{d}iciiiicddddciiic{dddd}dc{iiii}iiiiic{d}iiiciiiicddddc{i}dddc{d}iiiciiiicddddc{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiiciiiicddddc{i}dc{d}iciiiicddddc{i}dddc{dddd}dddddc{iiiii}dddc{d}iciiiicddddc{i}ddc{d}iiciiiicddddc{i}dc{ddddd}iiic{iiiii}dddc{d}iciiiicddddc{i}dc{d}iciiiicddddc{i}dc{ddddd}iiic{iiii}dcciiicddddciiiicddddciiiicdddcc{dddd}ic{iiii}iiiiicddddddciiicddddciiiicddddciiiicdddciiiiiic{dddd}dddddc{iiii}iiiiicddddddciiicddddc{i}ddc{d}iiciiiicdddciiiiiic{dddd}dddddc{iiii}dciciicddddccciiiicddcdc{dddd}ic{iiii}dciciicddddc{i}ddc{d}iiciiiicddcdc{dddd}ic{iiii}icdciicddddciiiiicdddddciiiicddcic{dddd}dc{iiii}icdciicddddc{i}dddc{d}iiiciiiicddcic{dddd}dc{iiiii}dddc{d}iiiciicddddciicddciiiicddc{i}dddc{ddddd}iiic{iiiii}dddc{d}iiiciicddddc{i}dddc{d}iiiciiiicddc{i}dddc{ddddd}iiic{iiiii}dddc{d}iiiciicddddc{i}ddc{d}iiciiiicddc{i}dddc{ddddd}iiic{iiii}icdddciiiiicdddddc{i}dc{d}iciiiiicdddddciiic{dddd}dc{iiiii}dddc{d}iciiiiicdddddciiicdddciiiiicdddddc{i}dc{ddddd}iiic{iiiii}dddc{d}iciiiiicdddddc{i}dc{d}iciiiiicdddddc{i}dc{ddddd}iiic{iiii}dcciiiicdddddccciiiiicddddcc{dddd}ic{iiii}dcciiiicdddddciicddciiiiicddddcc{dddd}ic{iiii}dcciiiicdddddciiiiiicddddddciiiiicddddcc{dddd}ic{iiii}icddciiiicdddddcicdciiiiicddddciic{dddd}dc{iiii}icddciiiicdddddciiiiicdddddciiiiicddddciic{dddd}dc{iiii}icddciiiicdddddc{i}dddc{d}iiiciiiiicddddciic{dddd}dc{iiii}iiiiicddddddciiiicdddddciiiiicdddddciiiiicddddciiiiiic{dddd}dddddc{iiiii}dddc{d}iiciiiicdddddcicdciiiiicddddc{i}ddc{ddddd}iiic{iiiii}dddc{d}iiciiiicdddddciiiiicdddddciiiiicddddc{i}ddc{ddddd}iiic{iiii}dciciiicdddddccciiiiicdddcdc{dddd}ic{iiii}dciciiicdddddcicdciiiiicdddcdc{dddd}ic{iiii}icdciiicdddddciiiiiicddddddciiiiicdddcic{dddd}dc{iiii}icdciiicdddddc{i}ddc{d}iiciiiiicdddcic{dddd}dc{iiii}icdciiicdddddc{i}dc{d}iciiiiicdddcic{dddd}dc{iiii}iiiiicdddddciiicdddddciiiicddddciiiiicdddciiiiic{dddd}dddddc{iiii}dciiciicdddddcicdciiiiicddcddc{dddd}ic{iiii}dciiciicdddddciiiicddddciiiiicddcddc{dddd}ic{iiii}dcdciiiiiicddddddciiiiiicddddddciiiiiicddddddcic{dddd}ic{iiii}icdddciiiiiicddddddc{i}ddc{d}iiciiiiiicddddddciiic{dddd}dc{iiii}dcciiiiicddddddccciiiiiicdddddcc{dddd}ic{iiii}dcciiiiicddddddcicdciiiiiicdddddcc{dddd}ic{iiii}dcciiiiicddddddciiiicddddciiiiiicdddddcc{dddd}ic{iiii}icddciiiiicddddddccciiiiiicdddddciic{dddd}dc{iiii}iiiiicddddddciiiiicddddddciiiicddddciiiiiicdddddciiiiiic{dddd}dddddc{iiiii}dddc{d}iiciiiiicddddddccciiiiiicdddddc{i}ddc{ddddd}iiic{iiiii}dddc{d}iiciiiiicddddddciiiiiicddddddciiiiiicdddddc{i}ddc{ddddd}iiic{iiii}iiiiicdddddciiiicddddddciicddciiiiiicddddciiiiic{dddd}dddddc{iiiii}dddc{d}iiiciiiicddddddccciiiiiicddddc{i}dddc{ddddd}iiic{iiiii}dddc{d}iiiciiiicddddddciiiicddddciiiiiicddddc{i}dddc{ddddd}iiic{iiii}dcdc{i}dddc{d}iiiccc{i}dddc{d}iiicic{dddd}ic{iiii}dcdc{i}dddc{d}iiic{i}dddc{d}iiic{i}dddc{d}iiicic{dddd}ic{iiii}icdddc{i}dddc{d}iiiciiiiicdddddc{i}dddc{d}iiiciiic{dddd}dc{iiiii}dddc{d}ic{i}dddc{d}iiiccc{i}dddc{d}iiic{i}dc{ddddd}iiic{iiii}dcciiiiiic{d}iiic{i}dddc{d}iiic{i}dddcddddddcc{dddd}ic{iiii}icddciiiiiic{d}iiiciiiiiicddddddc{i}dddcddddddciic{dddd}dc{iiii}iiiiicddddddciiiiiic{d}iiiciiiiicdddddc{i}dddcddddddciiiiiic{dddd}dddddc{iiiii}dddc{d}iiciiiiiic{d}iiiccc{i}dddcddddddc{i}ddc{ddddd}iiic{iiiii}dddc{d}iiciiiiiic{d}iiic{i}dc{d}ic{i}dddcddddddc{i}ddc{ddddd}iiic{iiii}dciciiiiic{d}iiiciiiiiicddddddc{i}dddcdddddcdc{dddd}ic{iiii}dciciiiiic{d}iiic{i}dc{d}ic{i}dddcdddddcdc{dddd}ic{iiii}icdciiiiic{d}iiiciiiiicdddddc{i}dddcdddddcic{dddd}dc{iiii}dciiciiiic{d}iiiciiicdddc{i}dddcddddcddc{dddd}ic{iiii}dciiciiiic{d}iiiciiiicddddc{i}dddcddddcddc{dddd}ic{iiii}dciiciiiic{d}iiiciiiiiicddddddc{i}dddcddddcddc{dddd}ic{iiii}dciiciiiic{d}iiic{i}dc{d}ic{i}dddcddddcddc{dddd}ic{iiii}dcdc{i}ddc{d}iic{i}dddc{d}iiic{i}ddc{d}iicic{dddd}ic{iiii}iiiiic{d}iiic{i}ddc{d}iiciiiicddddc{i}ddc{d}iic{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiic{i}ddc{d}iiciiiiicdddddc{i}ddc{d}iic{i}dddc{dddd}dddddc{iiiii}dddc{d}ic{i}ddc{d}iiccc{i}ddc{d}iic{i}dc{ddddd}iiic{iiiii}dddc{d}ic{i}ddc{d}iiciiiiiicddddddc{i}ddc{d}iic{i}dc{ddddd}iiic{iiiii}dddc{d}ic{i}ddc{d}iic{i}dddc{d}iiic{i}ddc{d}iic{i}dc{ddddd}iiic{iiii}icddc{i}dddc{d}iicicdc{i}ddc{d}iiiciic{dddd}dc{iiii}icddc{i}dddc{d}iiciiiiicdddddc{i}ddc{d}iiiciic{dddd}dc{iiii}icddc{i}dddc{d}iic{i}ddc{d}iic{i}ddc{d}iiiciic{dddd}dc{iiii}iiiiicddddddc{i}dddc{d}iiccc{i}ddc{d}iiiciiiiiic{dddd}dddddc{iiii}iiiiicddddddc{i}dddc{d}iic{i}dc{d}ic{i}ddc{d}iiiciiiiiic{dddd}dddddc{iiiii}dddc{d}iic{i}dddc{d}iiciicddc{i}ddc{d}iiic{i}ddc{ddddd}iiic{iiii}dciciiiiiic{d}iic{i}dddc{d}iiic{i}ddcddddddcdc{dddd}ic{iiii}dciciiiiiic{d}iic{i}dc{d}ic{i}ddcddddddcdc{dddd}ic{iiii}icdciiiiiic{d}iiccc{i}ddcddddddcic{dddd}dc{iiii}icdciiiiiic{d}iiciiicdddc{i}ddcddddddcic{dddd}dc{iiii}iiiiicdddddciiiiiic{d}iiciiicdddc{i}ddcddddddciiiiic{dddd}dddddc{iiiii}dddc{d}iiiciiiiiic{d}iiciicddc{i}ddcddddddc{i}dddc{ddddd}iiic{iiii}dciiciiiiic{d}iiciiiicddddc{i}ddcdddddcddc{dddd}ic{iiii}dcdc{i}dc{d}iccc{i}dc{d}icic{dddd}ic{iiii}icdddc{i}dc{d}icicdc{i}dc{d}iciiic{dddd}dc{iiii}icdddc{i}dc{d}ic{i}dddc{d}iiic{i}dc{d}iciiic{dddd}dc{iiii}icdddc{i}dc{d}ic{i}ddc{d}iic{i}dc{d}iciiic{dddd}dc{iiii}iiiiic{d}iiic{i}dc{d}iciiiiiicddddddc{i}dc{d}ic{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiic{i}dc{d}ic{i}ddc{d}iic{i}dc{d}ic{i}dddc{dddd}dddddc{iiiii}dddc{d}ic{i}dc{d}ic{i}dddc{d}iiic{i}dc{d}ic{i}dc{ddddd}iiic{iiii}dcc{i}ddc{d}icicdc{i}dc{d}iicc{dddd}ic{iiii}icddc{i}ddc{d}iciiiiicdddddc{i}dc{d}iiciic{dddd}dc{iiii}icddc{i}ddc{d}ic{i}dc{d}ic{i}dc{d}iiciic{dddd}dc{iiii}iiiiicddddddc{i}ddc{d}icicdc{i}dc{d}iiciiiiiic{dddd}dddddc{iiiii}dddc{d}iic{i}ddc{d}ic{i}ddc{d}iic{i}dc{d}iic{i}ddc{ddddd}iiic{iiii}dcic{i}dddc{d}ic{i}ddc{d}iic{i}dc{d}iiicdc{dddd}ic{iiii}iiiiicdddddc{i}dddc{d}ic{i}ddc{d}iic{i}dc{d}iiiciiiiic{dddd}dddddc{iiii}dcdccicccdccic{dddd}ic{iiii}dcdcciciicddcdccic{dddd}ic{iiii}dcdcciciiiiicdddddcdccic{dddd}ic{iiii}icdddccicdcicdcciiic{dddd}dc{iiii}icdddcciciiiicddddcdcciiic{dddd}dc{iiii}icdddccic{i}dddc{d}iiicdcciiic{dddd}dc{iiii}dccdcicccdcicc{dddd}ic{iiii}icddcdciciicddcdciciic{dddd}dc{iiii}dcicddcic{i}ddc{d}iicdciicdc{dddd}ic{iiii}icdcddciciiicdddcdciicic{dddd}dc{iiii}icdcddciciiiicddddcdciicic{dddd}dc{iiii}iiiiicdddddcddcicdcicdciiciiiiic{dddd}dddddc{iiiii}dddc{d}iiicddcicccdciic{i}dddc{ddddd}iiic{iiii}dciicdddciciiicdddcdciiicddc{dddd}ic{iiii}dciicdddciciiiiiicddddddcdciiicddc{dddd}ic{iiii}dcdcicciiicdddccdcic{dddd}ic{iiii}dcdcicciiiiiicddddddccdcic{dddd}ic{iiii}icdddcicccccdciiic{dddd}dc{iiii}iiiiic{d}iiicicciiicdddccdc{i}dddc{dddd}dddddc{iiii}iiiiic{d}iiicicciiiicddddccdc{i}dddc{dddd}dddddc{iiiii}dddc{d}icicciicddccdc{i}dc{ddddd}iiic{iiii}dcccc{i}dddc{d}iiicccc{dddd}ic{iiii}dcccc{i}ddc{d}iicccc{dddd}ic{iiii}iiiiicddddddccciicddccciiiiiic{dddd}dddddc{iiii}iiiiicddddddccciiiiicdddddccciiiiiic{dddd}dddddc{iiiii}dddc{d}iiccciiiiiicddddddccc{i}ddc{ddddd}iiic{iiii}dcicdcccccicdc{dddd}ic{iiii}dcicdcciicddccicdc{dddd}ic{iiii}dcicdcciiiiicdddddccicdc{dddd}ic{iiii}iiiiicdddddcdcc{i}ddc{d}iicciciiiiic{dddd}dddddc{iiiii}dddc{d}iiicdcc{i}ddc{d}iiccic{i}dddc{ddddd}iiic{iiiii}dddc{d}iciicdciiiicddddcicddc{i}dc{ddddd}iiic{iiiii}dddc{d}iciicdc{i}dddc{d}iiicicddc{i}dc{ddddd}iiic{iiii}dccicdcccicdcc{dddd}ic{iiii}dccicdciiiiicdddddcicdcc{dddd}ic{iiii}dccicdciiiiiicddddddcicdcc{dddd}ic{iiii}iiiiicddddddcicdcccicdciiiiiic{dddd}dddddc{iiii}iiiiicddddddcicdciiiiicdddddcicdciiiiiic{dddd}dddddc{iiiii}dddc{d}iicicdciiiiicdddddcicdc{i}ddc{ddddd}iiic{iiii}icdccdciiiiicdddddciccic{dddd}dc{iiii}dciicdcdc{i}ddc{d}iicicicddc ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~262~~... 213 bytes ``` import StdEnv @ =(rem) f=[d\\d<-[a*10^4+b*100+c\\a<-[10^4..99999],b<-[1..12],c<-[1..28+[0,3,if(@a 400<1|| @a 4<1&& @a 100>0)1 0,3,2,3,2,3,3,2,3,2,3]!!b]]|(\k=k==reverse k)[p\\p<-:toString d]&&all((<)0o@d)[2..d-1]] ``` [Try it online!](https://tio.run/##PY/BaoQwFEX38xWZjZiqIbGzaIspLtpFoTuXSQoxiUMwiaJ2oOC3NzW09MHjHQ6XC085I0P0k/50BnhpQ7R@npYNdJt@DbdTC2i@GA9PA2Wac91UTN4R/HEp@uPgQnEuD5cMQo9pRNkngRCpRal@sX4oGC7vSzvkrQQXjBuy7yBhQ7IswdH1jCEBKVX/7T@J87kXYs/5SEdKF3Mzy2rACNnM@dxUT9vUbYsNV6BFlknn8ryBeGo1ZDVCuiJCxG6Tx1MUDPFbDU5e11i9vceXryC9VesP "Clean – Try It Online") [Answer] # [Javascript](https://www.javascript.com/), ~~234~~ 229 bytes A bit bulky, but posting it to get the JS ball rolling. Any suggestions welcome! ``` f=n=>100+10*n+n/10|0 p=n=>{for(i=2;i<n;n=n%i++<1?0:n);return n>1} q=n=>(''+(100+n)).slice(-2) r=_=>{for(m=13;--m;)for(d=32;--d;)for(x=10;--x+1;){s=q(f(d))+q(f(m))+x+q(m)+q(d);if(p(s|0)&&d<(m==2?29:31+(m+m/8|0)%2))console.log(s)}} ``` ## Ungolfed: ``` // Flip a one- or two-digit number f=n=>100+10*n+n/10|0 // Primality test // For initial testing, you can replace this line with: // p=require('primality') // This uses the primality npm module and is way faster p=n=>{for(i=2;i<n;n=n%i++<1?0:n);return n>1} // Convert number to string, pad with zeroes if necessary q=n=>(''+(100+n)).slice(-2) r=_=>{ // Loop months for(m=13;--m;) // Loop days for(d=32;--d;) // Loop middle digit for(x=10;--x+1;) { // Construct 'date' s = // Start with day and month, each flipped q(f(d))+q(f(m)) + // Add middle digit ( will be casted to string since the previous expression is also a string) x + // Add month and date as they are q(m)+q(d); if( // Check for primality p(s|0) && // Check if it's a valid date by validating day ( month and year will always be valid) d<( // For February, we always assume 28 days ( check for 29 because we use less than) m==2?29 : // For other months, it alternates between 31 and 30 // EXCEPT July and August both have 31 days, then continues alternating 31+(m+m/8|0)%2)) console.log(s) } } ``` ## How it works: The digit flipping magic is based mostly on experimenting. I started by figuring out what number to subtract from to get the flipped version. I only cared about the last two digits. So, if we take `n`, find `k` so that `n+k=flip(n)`. For `10<n<20` `k` started at 101 and increased in increments of 9. However, for `n<10`, this was 100. I assumed `k` increased for every jump of 10, and after a bit of fiddling I figured it was correct. So, `k=100+9*n+n//10` where // means integer division. Thus, we get `n+k = n+(100+9*n+n//10) = 100+10*n+n//10 = flipped(n)`. I cannot prove, nor claim that this works for any number, but it produced correct results for the numbers used here. For the primality test, credit to [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/153255). I had a bit shorter version, but I could not get it right: ``` p=n=>{for(i=n;--i-1;)if(!(n%i))return 1;} ``` I skipped on the palindrome test, by looping over months, days and a middle digit so I can build strings as `dDmMxMmDd`, where `D` is the day's first digit, `d` is the second, etc. ## History Saved 5 bytes by getting rid of the conditional part of q ``` q=n=>n<10?'0'+n:(''+n).slice(-2) // from q=n=>(''+(100+n)).slice(-2) // to ``` [Answer] # APL NARS 626 bytes, 313 chars ``` f;y;m;d;i;k;v;x;t t←{60⊥3↑3↓⎕TS}⋄t0←50+t x←2 12⍴v,v←31 28 31 30 31 30 31 31 30 31 30 31 x[2;2]←29⋄m←d←1⋄y←10000 X: i←{(0=4∣⍵)∧0≠100∣⍵:1⋄0=400∣⍵:1⋄0}y A: →0×⍳y≥1e5 →0×⍳t≥t0 k←d+100×m+y×100 →B×⍳∼k=⍎⌽⍕k⋄→B×⍳∼0πk⋄⎕←k B: d+←1 →A×⍳d≤x[1+i;m] d←1⋄→C×⍳∼m=12⋄m←1⋄y+←1⋄→X C: m+←1⋄→A ``` this print what find in 50 second, than stop itself (because otherwise i can not stop the program for copy paste the test, because i not know how to stop the program without close the windows of the interpreter) test: ``` f 100111001 100131001 100161001 101030101 101060101 101141101 101171101 102040201 102070201 103000301 103060301 104000401 104030401 104040401 ``` [Answer] # [Julia 0.6](http://julialang.org/), 109 bytes Link goes to a longer version with two differences: 1. Checks for primes with hand written function, since the Primes package is not available on TIO. 2. Iterates over a different date range to not time out. ``` [s for s in Dates.format(Date(0,1,1):Date(100000,1,1),"YYYYmmdd") if Primes.isprime(parse(s))&&s==reverse(s)] ``` [Try it online!](https://tio.run/##TY5BCoMwEEX3niIEKhmIxbTQhaB00UsUcZGS2KbEUZLYensbFaF/9R784c97tEZe5n4MwxjKh34anGtP2t4RTwySmwzaH6N2MrBFmMhjuOACis3F7pzeY7pOKQrEtMSXpdMf7bxmHtKUYVZJa9mUVXiYqpyfCswEABvkVoFm1qiSq3/1X9IaVAbZ9hivaVwRy5SgfOXzH19WbiAZnMFg9yuYfw "Julia 0.6 – Try It Online") ]
[Question] [ This is a simple challenge which hopefully may lead to some creative answers. Quoting [Wikipedia](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling): *"Dual-tone multi-frequency signaling (DTMF) is an in-band telecommunication signaling system using the voice-frequency band over telephone lines between telephone equipment and other communications devices and switching centers."* ## Task Given two integers representing the column and row frequencies in the following table, your task is to output the corresponding key: ``` | 1209 Hz | 1336 Hz | 1477 Hz -------+---------+---------+--------- 697 Hz | 1 | 2 | 3 770 Hz | 4 | 5 | 6 852 Hz | 7 | 8 | 9 941 Hz | * | 0 | # ``` ## Examples * If the input is `[ 1209, 852 ]`, the expected output is "7". * If the input is `[ 1477, 941 ]`, the expected output is "#". ## Rules * You must take input as *integers* in any reasonable format, such as two separate variables or an array of two variables. Please specify in which order your program is expecting them (either *column\_freq, row\_freq* or *row\_freq, column\_freq*). * The input is guaranteed to be valid. * You must print or output a *character*. However, you're also allowed to output an integer for digit keys. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # JavaScript (ES6), ~~39~~ 35 bytes ``` a=>b=>"310*58# 47269"[a%b%83%16%13] ``` Maps the two inputs into numbers in the range `[0, 13)` by calculating: `col % row % 83 % 16 % 13`. Takes input in currying syntax (`f(col)(row)`) and returns a single-char string. ## Test Cases ``` let f= a=>b=>"310*58# 47269"[a%b%83%16%13] console.log( f(1336)(941) ) console.log( f(1209)(697) ) console.log( f(1336)(697) ) console.log( f(1477)(697) ) console.log( f(1209)(770) ) console.log( f(1336)(770) ) console.log( f(1477)(770) ) console.log( f(1209)(852) ) console.log( f(1336)(852) ) console.log( f(1477)(852) ) console.log( f(1209)(941) ) console.log( f(1477)(941) ) ``` ``` .as-console-wrapper{max-height:100%!important} ``` ## History Started with the range of `[0, 20)` with calculation `col % row % 29 % 20`, which required 8 wasted characters in the mapping. [Answer] ## Haskell, ~~42~~ 37 bytes ``` x#y="_1425__#9__*70836"!!mod(2*x+y)18 ``` Just some math to index a string. Input order is `<column> # <row>`, e.g. `1336 # 697`. [Try it online!](https://tio.run/##PYxLCsIwFAD3OcVr4kJrhObTJgF7A3cuQwiFChb7kRqhgd49thu3w8w8m8/r0fcpLSTW2DPJS@@J8T5XhRYVzrJhao88X87xxHQamm6EGtoJAbznbgxwACZERSqjdvQN9zDfRsD4L1i7rdflerGMF4buNmVSKefWuMEtpEoVVJecGsmcQyj9AA "Haskell – Try It Online") Edit: @flawr found a formula that works on shorter string. Overall -5 bytes. Thanks! [Answer] # [MATL](https://github.com/lmendo/MATL), 23 bytes ``` 13*+79\'186#294*3750'w) ``` Inputs are: column frequency, then row frequency. [Try it online!](https://tio.run/##y00syfn/39BYS9vcMkbd0MJM2cjSRMvY3NRAvVwTKGFkYMllbm4AAA "MATL – Try It Online") ### Explanation Multiplying the column frequency by 13, adding the row frequency, and computing modulo 79 gives a different value for each of the 12 pairs of inputs. ``` 13* % First input (implicit) times 13 + % Add to second input (implicit) 79\ % Modulo 79 '186#294*3750' % Push this string w % Swap ) % Index ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` DḢ×3++6ị9R;“*0# ”¤ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l4Y5Fh6cba2ubPdzdbRlk/ahhjpaBsoLCo4a5h5b8P7xc/1HTmsj//6OjzSzNdRQMjQwsY3W4FKA8Y2MzJJ6JuTmYZ25ugKQSwoOphPBgKi1MjZBUQngwlRAeTKWliSGSSggPphLCA6mMBQA "Jelly – Try It Online") Takes input as `row`, `column` in two arguments. This uses `3*<first digit of row> + <column> + 6 % 14` to give a different value for each. This is indexed into `[1,2,3,4,5,6,7,8,9,"*","0","#"," "," "]` to give the output. The spaces could really be any character; they are just buffer to create an implicit mod 14. **Low level** ``` DḢ×3++6ị9R;“*0# ”¤ D - digits (of <row>) Ḣ - head (get first element) ×3 - multiply by 3 + - add (<column>) +6 - add 6 ị - index into: ¤ - the nilad: 9R - range(9) ; - concatenate “*0# ” - the string "*0# " ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` %157ị9R;“*0#”¤s3¤ị@⁹%11¤ ``` [Try it online!](https://tio.run/##y0rNyan8/1/V0NT84e5uyyDrRw1ztAyUHzXMPbSk2PjQEqCgw6PGnaqGhoeW/P//39LE8L@hibk5AA "Jelly – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 34 bytes ``` (a,b)=>'806739214*#5'[a*b%2785%12] ``` [Try it online!](https://tio.run/##dc9LCoMwFIXhuasQimgkLSY@YgZ2I6WD@KBYxJQq3X6a3EHJxWb6w3fgPNVHbcN7fu3nVY@TWaY9HufHvHcmU7Qn3TVti0aUkrMqP9XpTeV9wkVbJ4zfzaDXTS/TZdGPDFTWSEEZLyShsRfKssGhEoKQ6MiFKDCH4HMIId7WHHMIPocQ4rJimEPwOYQj/zfmhqg9@7NuCAc7BCHI7VnMUXDchSC3ZzFHwXEXgtyexRwFx10gUWS@ "JavaScript (Node.js) – Try It Online") # [Python 3](https://docs.python.org/3/), 39 bytes ``` lambda a,b: '806739214*#5'[a*b%2785%12] ``` [Try it online!](https://tio.run/##bc9BCoMwEIXhvacIFNFIFiZRxxR6kraLiNAK1Upx09OnmVmUDLr9mW/grd/t@V5sGKfHtInLLbz8PIxeeDWcRdHXHVhndFOd2uLqqyE30Le5NvewfqZlK4mVnQOlTe2kEkmwtuOhAZAySyFAzSGFFFLYw741HFJIIYU9dI3mkEIKKaSQP0Cs4pz/PWIeIqZwAOMcDllAiOEAxjkcsoAQwwGMczhkASEGmWXhBw "Python 3 – Try It Online") row,column can be supplied in any order. [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 34 bytes ``` &"~"/9-4*&"d"/6-+1g,@ 147*2580369# ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X02pTknfUtdES00pRUnfTFfbMF3HgcvQxFzLyNTCwNjMUvn/fyDPXMHSxBAA "Befunge – Try It Online") Explanation: ``` &"~"/9-4* (Get number / 126 - 9) * 4 = 0, 4, or 8 &"d"/6- Get number / 100 - 6 = 0, 1, 2, or 3 + Add the above results - this becomes the x-coordinate in the "lookup table" 1g,@ Get a value on row 1 column x, output it, and end ``` ]
[Question] [ In this challenge, you must parse a list of lists, into a simpler list format. This challenge is based on my sadflak parser. In my sadflak parser, it has all the () removed, replaced with the sum of the ()s at the start of the list, to make the program run faster. To parse into a Sad-List, you have to do this (python implementation thing, uses a tuple of tuples): ``` def sadlistfunc(list): new-sadlist = [0] for i in list: if i == (): new-sadlist[0]+=1 else: new-sadlist.append(sadlistfunc(i)) ``` This is a recursive function. For a list, start a new list, starting with the number of () from the list input, then the rest of this list is sad-list versions of every list that was not a () from the list input, in order. return the list. ## Input: you may take input in a few different formats: * you may take it as a list * you may take it as a tuple * you may take it as a string if you take it as a string, you should use some set of brackets, as appear in brain-flak. you may not use characters 1 and 2 just be reasonable Input will always be inside one list, but your program may assume an implicit list layer outside of the input, i.e. ()()() = (()()()), or it may choose not to. Examples will be with explicit outside list ## output: may be list or tuple or string, or whatever. you may use whatever reasonable output format, as is the meta consensus. ## Example: ``` (()()()) = [3] (((()))) = [0,[0,[1]]] ((())()(())) = [1, [1], [1]] () = invalid input, if the outside bracket is explicit. ((((())())())(())()) = [1, [1, [1, [1]]], [1]] ``` note that input is not strict. these inputs could be: ``` [[],[],[]] [[[[]]]] [[[]],[],[[]]] [] [[[[[]],[]],[]],[[]],[]] ``` or some other reasonable format # explained test case: ``` (()()((())())()) ``` to "sadify" this, first we count the number of () ``` ()() () ( ((())()) ) ``` 3. then we remove these, and add a 3 at the start ``` (3,((())())) ``` there is one list in this list. we sadify this ``` ((())()) ``` how many ()? ``` () ((()) ) ``` 1. we remove and add a 1 at the start ``` (1,(())) ``` this has one list in it ``` (()) ``` count ``` () ( ) ``` remove and add count ``` (1) ``` then we put this back into its list ``` (1,(1)) ``` then we put this back into its list ``` (3,(1,(1))) ``` done This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shorter is better [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` L+]/bYyM-b]Yy ``` [Test suite](http://pyth.herokuapp.com/?code=L%2B%5D%2FbYyM-b%5DYy&test_suite=1&test_suite_input=%5B%5B%5D%2C%5B%5D%2C%5B%5D%5D%0A%5B%5B%5B%5D%5D%2C%5B%5D%2C%5B%5B%5D%5D%5D%0A%5B%5B%5B%5B%5B%5D%5D%2C%5B%5D%5D%2C%5B%5D%5D%2C%5B%5B%5D%5D%2C%5B%5D%5D&debug=0). ## How it works ``` L+]/bYyM-b]Yy L define a function y with argument b: /bY list 1: count how many [] can be found in b ] wrap into singleton -b]Y list 2: filter out [] from b yM apply y (this function) to each + concatenate the two lists above y apply y to the input ``` [Answer] # CommonLisp, 49 bytes ``` (defun s(l)(cons(count()l)(mapcar's(remove()l)))) ``` take input as list of lists. [Try it online!](https://tio.run/##LYpRCsAgDEOv0j/TY4lzIGiVVnd9Z9keISEhqRYbe@PK9xIyVEbqYseWTPCpLY4UNRg0t/5k3w4bQ4tMglGAw/zrC7@8) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` ;[[]]x{↰₀}ᵐA&{∋∅}ᶜg,A ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3zo6Oja2ovpR24ZHTQ21D7dOcFSrftTR/aijtfbhtjnpOo7//0eDQGysDhxDGf@jAA "Brachylog – Try It Online") [Answer] ## Mathematica, 42 bytes ``` {#~Count~{0},##&@@#~DeleteCases~{0}}&//@#& ``` Avoids explicit recursion by using `//@` (`MapAll`) which maps a function over every node in a tree. This also means that the functions are executed from the leaves upwards. However, it will also be applied to `{}` which get turned into `{0}` in the process. That's why we count and remove `{0}` instead `{}`. [Answer] ## [Retina](https://github.com/m-ender/retina), 42 bytes ``` +`(({()|}(?<-3>))*)(?!\3){} 1$1 {(1*) {$.1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0FDo1pDs6ZWw95G19hOU1NLU8NeMcZYs7qWy1DFkKtaw1BLk6taRc/w///q6logBJK1EMQFEQAzQKIQRi1YEZSDUAxlAQA "Retina – Try It Online") [Answer] ## Clojure, 59 bytes ``` (fn f[i](conj(map f(remove #{[]}i))(count(filter #{[]}i)))) ``` Not much different from the [CommonLisp](https://codegolf.stackexchange.com/a/128352/59617) answer. Its `count` and `remove` seem to accept a bit nicer construct, here I had to use sets. [Answer] # [Actually](https://github.com/Mego/Seriously), 12 bytes ``` ;[]@c@;░Q£Mo ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/986OtYh2cH60bSJgYcW@@b//x8NArGxOnAMZQAA "Actually – Try It Online") Takes input as a comma-separated square-bracket list with explicit outer brackers. Explanation: ``` ;[]@c@;░Q£Mo ;[]@c count the number of empty lists @;░ filter out empty lists Q£Mo recurse with filtered list and append result ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~46~~ 45 bytes ``` f=lambda l:[l.count([])]+map(f,filter(len,l)) ``` [Try it online!](https://tio.run/##LY2xDsMgDER3vsIjqKhDx0j5EssDbUFFcgCBO/TrCaRIPr27G3zlJ5@cHr2Hnd3xfDvgDfn@yt8kGsnQ7XBFBxsii6@afbJsTBffpO2oEMleR3b4iZkG/3k1S8soUirkCvMHxHSxbQqg1DhGg57F2DgB "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Tị߀;@ċ“”$ ``` [Try it online!](https://tio.run/##y0rNyan8/z/k4e7uw/MfNa2xdjjS/ahhzqOGuSr/D7cfnfRw54z//6NBIDZWRwGJgDEB "Jelly – Try It Online") Takes input as list of lists of lists... Of course it uses the algorithm the other answers use. ;) [Answer] # [Haskell](https://www.haskell.org/), 102 bytes ``` data L=I Int|T[L]deriving Show (I n:r)#m=r#(n+m) (x:r)#m=x:r#m _#m=[I m] f(T[])=I 1 f(T t)=T$map f t#0 ``` [Try it online!](https://tio.run/##bYwxD8IgFIR3fsUldIDooKsJP4Ckm2yEGJK2lliwQaIO/nfEarvY4b13L9/d9fZ2aYch58Ymi1pIyJBeStemaaO7u3DGsb8@CJMIh8ipF5GysPGcsOf3L4d6cipKS3hDOqa04aVo/5FIXKjK2xEdEt1lb12AQHMlGKMLCVUBFZQuoe1vzD@buFknZg5OlvXs7FrWovMb "Haskell – Try It Online") Because Haskell is strictly typed, there are no arbitrarily nested lists. As a remedy `data L=I Int|T[L]deriving Show` declares tree-like nested lists with either Ints or empty lists as leafs. Input is like in the second example format, with an additional constructor `T` before each opening brace: `T[T[T[]],T[],T[T[]]]`. The same goes for the output, with each number being preceded by a constructor `I`. Function `f` performs the *saddening*. Outputs for the test cases: ``` T [I 3] T [T [T [I 1],I 0],I 0] T [T [I 1],T [I 1],I 1] T [T [T [T [I 1],I 1],I 1],T [I 1],I 1] ``` [Answer] ## Javascript (ES6), 77 bytes Golfed: ``` let m=a=>!a.length||a.map(m).reduce((b,c)=>(c.length?b.push(c):b[0]++,b),[0]) ``` Ungolfed: ``` const traverse = arr => !arr.length || arr .map(traverse) .reduce( (accum, val) => (val.length ? accum.push(val) : accum[0]++, accum), [0] ); ``` ## Demo ``` let m=a=>!a.length||a.map(m).reduce((b,c)=>(c.length?b.push(c):b[0]++,b),[0]) o.innerHTML = [ JSON.stringify(m([[],[],[]])), JSON.stringify(m([[[[]]]])), JSON.stringify(m([[[]],[],[[]]])), JSON.stringify(m([])), JSON.stringify(m([[[[[]],[]],[]],[[]],[]])) ].join('\n') ``` ``` <pre id=o></pre> ``` ]
[Question] [ A variable number of bits is an array of 0 or more bits. So `[0, 1]` is a variable number of bits, but so is `[]`. Write a function or program that, given an nonnegative integer returns a variable number of bits such that every integer has a one-to-one (bijective) mapping with an array. There are an infinite amount of such mappings, you are free to construct one as you please, but it **must** be one-to-one. Your mapping must *conceptually* be one-to-one for an arbitrarily sized integer, but it's OK if your *implementation* fails for large integers due to numerical limits of types in your preferred language (e.g. C's `int`). As an example of what is **not** a one-to-one mapping, is simply listing the binary digits of the integer. In such a system 5 becomes `[1, 0, 1]` (or `0b101`), but it's not one-to-one, because `0b0101` or `[0, 1, 0, 1]` also means 5. It should be fairly obvious that a mapping is not one-to-one if it skips an integer (e.g. it doesn't work for 5), but I'd like to make it clear that skipping a variable bit array is also not one-to-one. You must map to every possible variable bit array, including `[]`. --- Shortest code in bytes wins. [Answer] ## Python, 20 bytes ``` lambda n:bin(~n)[4:] ``` Test: ``` >> [bin(~n)[4:] for n in range(16)] ['', '0', '1', '00', '01', '10', '11', '000', '001', '010', '011', '100', '101', '110', '111', '0000'] ``` Doing `lambda n:bin(n+1)[3:]` increments the input, then takes the binary representation with the first symbol removed (`[3:]` because the prefix `0b` is two chars chars). Since any positive number starts with 1 in binary, this uniquely gives a binary representation. A byte is saved by instead using the bit complement `~n` to get the negation `-(n+1)`, and removing the negative sign by chopping off one more symbol. [Answer] # Jelly, 3 bytes ``` ‘BḊ ``` Same idea as xnor: maps `0 1 2 3 4 ...` to `[] [0] [1] [0 0] [0 1] ...`; the code is basically `increment → binary → remove first`. [Try it out online](http://jelly.tryitonline.net/#code=4oCYQuG4igooVGhpcyBydW5zIHRoZSBhYm92ZSBhcyBhIGZ1bmN0aW9uIG9uIGFsbCBpbnB1dHM6KQrDkeKCrA&input=&args=MCwxLDIsMyw0LDUsNiw3). [Answer] ## Pyth, 5 bytes ``` t.BhQ ``` Simply a translation of [xnor's answer](https://codegolf.stackexchange.com/a/71925/3808) into Pyth. `Q` is eval()'d input(), `h` increments it, `.B` converts it to a binary string, and `t` takes the "tail" (which is everything except the first character). [Answer] ## Haskell, ~~41~~ ~~38~~ ~~30~~ 29 bytes ``` l="":[b:x|x<-l,b<-"01"] (l!!) ``` Usage example: `(l!!) 4` -> `"10"`. Starting with the empty list as the first element, walk lazily through the list and append the current element with `0` and with `1` in front of it. Edit: @xnor saved ~~3~~ 11 bytes. Thanks! [Answer] ## JavaScript (ES6), 29 bytes ``` x=>(~x).toString(2).slice(2) ``` Same idea as xnor. ``` f=x=>(~x).toString(2).slice(2); [...Array(100)].map((v,x)=>A.textContent+=x + ': ' + f(x) + '\n') ``` ``` <pre id=A></pre> ``` [Answer] # Jolf, 4 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=d0Joag) ``` wBhj hj input + 1 B converted to binary w with first removed. ``` Very simple strategy, also happens to be the shortest. [Answer] ## Haskell, 35 bytes ``` h 1=[] h n=mod n 2:h(div n 2) h.(+1) ``` Haskell doesn't have a binary built-in, so the (reversed) conversion is done manually. To remove the initial 1, the base case has `1` transform to the empty list. Edit: Saved a byte by conjugating by the `+1` instead. ``` h 0=[] h m=1-mod m 2:h(div(m+1)2-1) ``` [Answer] # C, 40 bytes ``` f(n){if(++n/2)putchar(n%2+48),f(n/2-1);} ``` Converts the input to bijective base 2 (with symbols `0` and `1`), like the other answers. [ideone it!](http://ideone.com/ocbmMs) ]
[Question] [ I define the following operators: **Manhattan Addition** a +M b, for single-digit numbers, is the result of concatenating b onto a. So, a +M b = 10a + b. Therefore, the general operator +M is defined as thus: ``` a +M b = 10a + b ``` **Manhattan Subtraction** a –M b, for single-digit numbers, is the result of removing the last b from a. Therefore, the operator –M is defined as thus in pseudocode: ``` a –M b = a remove last b ``` **Manhattan Multiplication** a ×M b is the result of replacing all instances of b in a with b instances of b. Ergo, ×M is defined in pseudocode as: ``` a ×M b = a -> s/b/<b copies of b>/g ``` **Manhattan Division** a ÷M b is defined in terms of ×M: ``` 1 ÷M b = the first character of b a ÷M b = a ×M (1 ÷M b) ``` With all this in mind, create an interpreter that will evaluate infix expressions that use the following operators (i.e., `a + b`, not `a b +` or `+ a b`) ``` + Addition - Subtraction / Division * Multiplication *M Manhattan Multiplication /M Manhattan Division +M Manhattan Addition -M Manhattan Subtraction ``` Each Manhattan operator has a higher order precedence than their normal counterpart. Test cases: ``` > 5 +M 10 + 3 63 // 5*10 + 10 + 3 => 60 + 3 > 10 *M 2 10 // no 2s in 10 > 10 *M 1 10 // one 1 in 10 replaced once > 23 *M 3 2333 // 23 has one 3, which is replaced with three 3s > 23 *M 2 223 // 23 has one 2, which is replaced with two 2s > 232 *M 2 22322 // 232 has two 2s, which are replaced with two 2s > 232 *M 23 23...(23 times)...232 // ... > 123 *M 2 * 3 3669 // 1223 * 3 => 3669 > 5 + 3 +M 2 37 // 5 + (3 +M 2) => 5 + 32 => 37 > 150 /M 3 150 // 150 ÷M 3 => 150 ×M 3 => 150 > 150 /M 53 1555550 // 150 ÷M 53 => 150 ×M 5 => 1555550 > 50 -M 0 5 > 500 -M 0 50 > 5234 -M 5 234 > 12 +M 633 *M 3 6333453 // = 12 +M 6333333 = 120 + 6333333 = 6333453 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=59299,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Perl, ~~100~~ ~~99~~ 98 bytes 97 bytes code + 1 byte command line ``` s/ |.*\K(\d)(\d*)-M\1|\+M/\2/g+s/(\d+)\*M(.)/$1=~s@$2@$&x$&@erg/e+s#/(M.)\d+#*\1#&&redo,$\=eval}{ ``` Usage example: ``` echo "123 *M 2 * 3 + 150 /M 53" | perl -p entry.pl ``` [Answer] # Python, 644 bytes ``` import operator as o,re x,q,t,r,w='*/+-M';mm,md,ma,ms='*M /M +M -M'.split() n=lambda x:x a=lambda a,b:str(10*int(a)+int(b)) v=lambda a,b:a[::-1].replace(b,'',1)[::-1] m=lambda a,b:a.replace(b,b*int(b)) d=lambda a,b:m(a,b[0])if a>0 else b[0] def p(s):s=s.group();ss=s.split();l=s.split(ss[1]);h={mm:m,md:d,ma:a,ms:v,x:o.mul,q:o.div,t:o.add,r:o.sub}.get(ss[1],n);return str(h(*map(int if h in[o.mul,o.div,o.add,o.sub]else n,map(u,map(str.strip,l))))) def u(s):z=r'\d+ (?:\{0}{2}|\{1}{2}) \d+';return re.sub(z.format(t,r,''),p,re.sub(z.format(t,r,w),p,re.sub(z.format(x,q,''),p,re.sub(z.format(x,q,w),p,re.sub(r'\((.*)\)',u,s))))) print u(input()) ``` Accepts input on STDIN (wrapped in quotes). Uses regex to match and parse operations. All work is done on strings, and casting to and from ints is only used when doing normal mathematical operations. I'm pretty sure this could be golfed further, so I'll be working on that over the next few days. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~104~~ ~~81~~ ~~79~~ ~~93~~ 75 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) *Edit:* Now handles `4342343 -M 34` → `43423` correctly. ``` M←{⍎(5|⌊⍺⍺2)⊃'⍺×M⍣(⍺≠1)⍎⊃b'(b⎕R(⍵⍴'&')⊢a)'10⊥⍺⍵'(('(.*)',b←⍕⍵)⎕R'\1'⊢a←⍕⍺)} ``` ### Background This extends APL to include the Manhattan operator. An operator in APL terminology is a modifier of functions (e.g. `÷`). An example of an operator is `⍨` which modifies functions to swap their arguments so `3 = 2 ÷⍨ 6`. So too, `M` modifies the basic arithmetic functions to be their Manhattan relatives. Note that since the resulting language is an extension of APL, APL's strict right-to-left precedence remains. ### Explanation The overarching structure is `M←{⍎(5|⌊⍺⍺2)⊃`…`}` which applies the function (`+` or `-` or `×` or `÷`) to 2 and uses the result to chose which string to evaluate. The strings are: **3 for -M:** `(('(.*)',b←⍕⍵)⎕R'\1'⊢a←⍕⍺)`  regex remove the last occurrence of *b* (string rep. of right arg.) in *a* (string rep. of left arg.) **2 for +M:** `'10⊥⍺⍵'`  evaluate the arguments as base-10 digits **1 for ×M:** `(b⎕R(⍵⍴'&')⊢a)`  replace occurrences of *b* with *b* ampersands (i.e. regex for the **0 for ÷M:** `'⍺×M⍣(⍺≠1)⍎⊃b'`  `⍎⊃b` first digit of *b*  `⍺×M⍣(⍺≠1)` apply ⍺ ×M if ⍺ ≠ 1 `⊃` out of of the above four strings, pick number: `(5|⌊⍺⍺2)` mod-5 of the floor of the function applied to 2, namely:  3 = `5 | ⌊-2`  2 = `5 | ⌊+2`  1 = `5 | ⌊×2` because ×2 ⇔ sgn(2) ⇔ 1  0 = `5 | ⌊÷2` because ÷2 ⇔ 1 ÷ 2 ⇔ 0.5 ### Lots of thanks to my dear friend ngn for amazing shavings. ]
[Question] [ [Pi](https://en.wikipedia.org/wiki/Pi) times [e](https://en.wikipedia.org/wiki/E_(mathematical_constant)) (or Pie if you like ambiguous notation) to 100 decimal places is: ``` 8.5397342226735670654635508695465744950348885357651149618796011301792286111573308075725638697104739439... ``` ([OIES A019609](https://oeis.org/A019609)) ([argument for possible irrationality](https://web.archive.org/web/20180209015900/http://mathforum.org/library/drmath/view/51617.html)) Your task is to write a program that takes in a positive integer N, and outputs Pi\*e truncated to N decimal places. e.g. if N = 2, then the output should be `8.53`. This is an optimization problem, so the submission that can give the correct output for the highest value of N will win. To ensure all submissions are judged using the same computing power, **your code must be run on [ideone](https://ideone.com/)**, using any language they support. According to the [ideone faq](https://ideone.com/faq), there is a 5 second run time limit for not logged in users. This 5 second limit is the one you must use, **not** the 15 second limit for logged in users. (See [faq](https://ideone.com/faq) for other limits like memory, code size, etc.) Specifically, anyone not logged into ideone should be able to run your program on ideone for all values of N from 1 to some maximum Nmax, and see correct output *nearly all of the time*. without any `Time limit exceeded` or `Memory limit exceeded`, etc. errors. The submission with the largest Nmax wins. (Whether the actual time taken is a smidge over 5 seconds doesn't matter as long as ideone doesn't give errors. "*Nearly all of the time*" is defined as more than 95% of the time for any particular N.) # Details * You may use any mathematical method you like to calculate Pi*e, \*\*but you may not hardcode the output beyond the first dozen digits of Pi, e or Pi*e\*\*. + Your program should be able to work for any N, given unlimited resources. + You may use built in Pi or e constants if your language happens to have them. * You may not access websites or resources external to your code (if ideone even allows this). * Beyond hardcoding and accessing external resources, anything that ideone allows is almost certainly fine. * Your input and output must (obviously) work with whatever ideone provides for i/o (stdin/stdout only it seems). It's fine if you need quotes around the input N or the output is something like `ans = ...`, etc. * Please include a link to an ideone snippet of your code with your Nmax as input. * If there happens to be a tie (only likely if multiple submissions hit the 64kB output character limit) the highest votes answer wins. [Answer] ## Python - 65535 <http://ideone.com/knKRhn> ``` from math import exp, log def divnr(p, q): """ Integer division p/q using Newton-Raphson Division. Assumes p > q > 0. """ sp = p.bit_length()-1 sq = q.bit_length()-1 sr = sp - sq + 1 s = [] t = sr while t > 15: s = [t] + s t = (t>>1) + 1 # Base-case division r = (1 << (t<<1)) / (q >> sq-t) for u in s: r = (r << u-t+1) - (r*r * (q >> sq-u) >> (t<<1)) t = u return (r * (p >> sq)) >> sr def pibs(a, b): if a == b: if a == 0: return (1, 1, 1123) p = a*(a*(32*a-48)+22)-3 q = a*a*a*24893568 t = 21460*a+1123 return (p, -q, p*t) m = (a+b) >> 1 p1, q1, t1 = pibs(a, m) p2, q2, t2 = pibs(m+1, b) return (p1*p2, q1*q2, q2*t1 + p1*t2) def ebs(a, b): if a == b: if a == 0: return (1, 1) return (1, a) m = (a+b) >> 1 p1, q1 = ebs(a, m) p2, q2 = ebs(m+1, b) return (p1*q2+p2, q1*q2) if __name__ == '__main__': n = input() pi_terms = int(n*0.16975227728583067) # 10^n == e^p p = n*2.3025850929940457 # Lambert W_0(p/e) a la Newton k = log(p) - 1 w = k - (k-1)/(k+1) while k > w: k = w w -= (k - p*exp(-k-1))/(k+1) # InverseGamma(e^p) approximation e_terms = int(p / w) pp, pq, pt = pibs(0, pi_terms) ep, eq = ebs(0, e_terms) z = 10**n p = 3528*z*ep*abs(pq) q = eq*abs(pt) pie = divnr(p, q) print pie, ``` --- Ideone doesn't seem to have `gmpy2` installed, which is unfortunate for at least two reasons. One, because it would make the calcuation a lot faster, and two, because it makes any formula requiring an arbitrary precision square root impractical. The formula I use for *π* was [listed by Ramanujan](http://books.google.fr/books?id=oSioAM4wORMC&pg=PA38) as Formula (39): ![](https://chart.googleapis.com/chart?cht=tx&chl=%5Cfrac%7B1%7D%7B%5Cpi%7D%3D4%5Csum_%7B_%7Bn%3D0%7D%7D%5E%7B_%5Cinfty%7D%7B%5Cfrac%7B%28-1%29%5En+%284n%29%21%2821460n%2B1123%29%7D%7B%28n%21%29%5E4+14112%5E%7B2n%2B1%7D%7D) which converges at the rate of *~5.89* digits per term. To my knowledge, this is the fastest converging series of its kind that doesn't require the evaluation of an arbitrary precision square root. Formula (44) in the same paper (convergence rate *~7.98* digits per term) is most often referred to as *the* Ramanujan Formula. The formula I use for *e* is the sum of inverse factorials. The number of terms required is calculated as Γ-1(*10n*), using an approximation I found on [mathoverflow](https://mathoverflow.net/questions/12828/inverse-gamma-function). The Lambert W0 component is found using Newton's Method. The calculation of each of these summations is done via the [Fast E-function Evalution](http://en.wikipedia.org/wiki/FEE_method) (more generally known as binary-splitting), originally devised by Karatsuba. The method reduces a summation to *n* terms to a single rational value *p/q*. These two values are then multiplied to produce the final result. **Update:** Profiling revealed that over half of the time needed for the calculation was spent in the final division. Only the upper most *log2(10n)* bits of *q* are needed to obtain full precision, so I trim a few off beforehand. The code now fills the Ideone output buffer in *3.33s*. **Update 2:** Since this is an [optimization](/questions/tagged/optimization "show questions tagged 'optimization'") challenge, I decided to write my own division routine to combat CPython's slowness. The implementation of `divnr` above uses [Newton-Raphson Division](http://en.wikipedia.org/wiki/Division_algorithm#Newton.E2.80.93Raphson_division). The general idea is to calculate *d = 1/q · 2n* using Newton's Method, where *n* is the number of bits the result requires, and compute the result as *p · d >> n*. Runtime is now *2.87s* - and this is without even chopping off bits before the calculation; it's unnecessary for this method. [Answer] ## PARI/GP : 33000 This is basically the program given at [OEIS](https://oeis.org/A019609), modified to take input and format output correctly. It should serve as a baseline to beat, if nothing else. I *assume* this is accurate. I checked it at 100 and 20k against OEIS, and it matched for both. It's quite hard to find further digits online to check against. For 33,000 it takes about 4.5s, so it could probably be bumped a small bit. I just got tired of fiddling with the input and ideone's slow-ass submit/compile/run loop. ``` { m=eval(input()); default(realprecision, m+80); x=Pi*exp(1); s="8."; d=floor(x); x=(x-d)*10; for (n=1, m, d=floor(x); x=(x-d)*10; s=Str(s,d)); print(s); } ``` [Ideone.com link](http://ideone.com/8yTU1i) [Answer] # Python 3 Since the built in pi and e don't have enough digits, I decided to calculate my own. ``` import decimal import math decimal.getcontext().prec=1000000 decimal=decimal.Decimal;b=2500 print(str(sum([decimal(1/math.factorial(x)) for x in range(b)])*sum([decimal(1/16**i*(4/(8*i+1)-2/(8*i+4)-1/(8*i+5)-1/(8*i+6))) for i in range(b)]))[0:int(input())+2]) ``` [IDEOne link](http://ideone.com/pViVIr) ### Output for STDIN = 1000: ``` 8.5397342226735669504281233688422467204743749305568824722710929852470173635361001388261308713809518841081669216573834376992066672804294594807026609638293539437286935503772101801433821053915371716284188665787967232464763808892618434263301810056154560438283877633957941572944822034479453916753507796910068912594560500836608215235605783723340714760960119319145912948480279651779184356994356172418603464628747082162475871780202868607325544781551065680583616058471475977367814338295574582450942453416002008665325253385672668994300796223139976640645190237481531851902147391807396201201799703915343423499008135819239684881566321559967077443367982975103648727755579256820566722752546407521965713336095320920822985129589997143740696972018563360331663471959214120971348584257396673542429063767170337770469161945592685537660073097456725716654388703941509676413429681372333615691533682226329180996924321063261666235129175134250645330301407536588271020457172050227357541822742441070313522061438812060477519238440079 ``` [Answer] # Scala - 1790 IDEOne at <http://ideone.com/A2CIto>. We use [Wetherfield's formula](http://en.wikipedia.org/wiki/Machin-like_formula#More_terms) for π (and Machin-formula code crudely ported from [here](http://en.literateprograms.org/Pi_with_Machin%27s_formula_(Java))). We calculate e using the ordinary power series. ``` object Main extends App { import java.math.{BigDecimal => JDecimal} import java.math.RoundingMode._ import scala.concurrent.Future import scala.concurrent.Await import scala.concurrent.ExecutionContext.Implicits._ import scala.concurrent.duration._ val precision = 1800 def acotPrecision(numDigits: Int)(x: BigDecimal) = { val x1 = x.underlying val two = JDecimal.valueOf(2) val xSquared = x1 pow 2 val unity = JDecimal.ONE.setScale(numDigits, HALF_EVEN) var sum = unity.divide(x1, HALF_EVEN) var xpower = new JDecimal(sum.toString) var term = unity var add = false var n = JDecimal.valueOf(3).setScale(numDigits) while (term.setScale(numDigits, HALF_EVEN).compareTo(JDecimal.ZERO) != 0) { xpower = xpower.divide(xSquared, HALF_EVEN) term = xpower.divide(n, HALF_EVEN) sum = if (add) sum add term else sum subtract term add = !add n = n add two } sum } def ePrecision(numDigits: Int) = { val zero = JDecimal.ZERO var sum = zero var term = JDecimal.ONE.setScale(numDigits, HALF_EVEN) var n = JDecimal.ONE.setScale(numDigits, HALF_EVEN) while(term.setScale(numDigits, HALF_EVEN).compareTo(zero) != 0) { sum = sum add term term = term.divide(n, HALF_EVEN) n = n add JDecimal.ONE } sum } val acot = acotPrecision(precision) _ def d(x: Int) = JDecimal.valueOf(x) def piFuture = Future(d(4) multiply ( (d(83) multiply acot(107)) add (d(17) multiply acot(1710)) subtract (d(22) multiply acot(103697)) subtract (d(24) multiply acot(2513489)) subtract (d(44) multiply acot(18280007883L)) add (d(12) multiply acot(7939642926390344818L)) add (d(22) multiply acot(BigDecimal("3054211727257704725384731479018"))) )) def eFuture = Future(ePrecision(precision)) Await.result( for (pi <- piFuture; e <- eFuture) yield println((pi multiply e).setScale(precision - 10, DOWN)) , 5 seconds) } ``` [Answer] # Java, 15,053 ``` interface M{ static void main(String[]a){ int n=new Integer(new java.util.Scanner(System.in).nextInt()),i=1,x=n/100+9; var t=java.math.BigInteger.TEN.pow(n+=x).shiftLeft(1); var p=t; var s=t.TEN.pow(n-x); var e=s; for(;i<5e4; e=s.add(e.divide(s.valueOf(50001-i)))) p=p.add(t=t.multiply(t.valueOf(i)).divide(t.valueOf(i+++i))); System.out.print((""+p.multiply(e)).substring(0,n-x)); } } ``` Outputs the digits without decimal dot after the leading `8`. [Try it on ideone.](https://ideone.com/9KCa7S) Increasing the `5e4`/`50001` will both increase the run-time and digit-accuracy. With 50,000 iterations, which runs in ~4-5 seconds usually, \$15\text{,}053\$ is the largest amount of digits we can reach with 100% accuracy. With an input of \$15\text{,}054\$, the last couple digits will be incorrect. Uses a combination of [my Java answer for the *Calculate 500 digits of pi* challenge](https://codegolf.stackexchange.com/a/213932/52210) and a port [of this stackoverflow C# .NET answer with BigIntegers](https://stackoverflow.com/a/72295897/1682559). ]
[Question] [ ### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!** [Answer] # JavaScript (E6) 155 ~~174 191~~ **Edit 2** As suggested by @bebe, using recursive function (performe worse but shorter) Slightly changed R function to avoid 'too much recursion' Test suite added. The function performs well for bases < 3000 and exponent in range -50..50. **Edit** Golfed more and better precision Any real number can be approximate with a rational number (and IEEE standard 'real' numbers store rationals in fact). Any rational number can be expressed as a fraction a/b with a and b integers. x^(a/b) is root b of (x^a) or (root b of x)^a. Integer exponentiation is quite easy by squaring. Integer root can be approximated using numerical methods. **Code** ``` P=(x,e)=>( f=1e7,e<0&&(x=1/x,e=-e), F=(b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r, R=(b,e,g=1,y=1e-30,d=(b/F(g,e-1)-g)/e)=>d>y|d<-y?R(b,e,g+d,y/.99):g, F(R(x,f),e*f) ) ``` **Test** In FireFox or FireBug console ``` for (i=0;i<100;i++) { b=Math.random()*3000 e=Math.random()*100-50 p1=Math.pow(b,e) // standard power function, to check p2=P(b,e) d=(p1-p2)/p1 // relative difference if (!isFinite(p2) || d > 0.001) console.log(i, b, e, p1, p2, d.toFixed(3)) } ``` [Answer] # Haskell, 85 ~~90~~ Standard exp-log algorithm. Now with different name, shaving off a few more characters: ``` a%b|a>1=1/(1/a)%b|0<1=sum$scanl((/).((-b*foldr1(\n b->(1-a)*(b+1/n))c)*))1c c=[1..99] ``` `raise` is now called `(%)`, or `%` in infix notation, even making its use consume fewer bytes: `4.5%(-4.5)` The ungolfed version also uses just 172 bytes: ``` raise a b | a > 1 = 1 / raise (1/a) b | otherwise = expo (-b* ln (1-a)) ln x = foldr1 (\n a -> x*a+x/n) [1..99] expo x = sum $ scanl ((/) . (x*)) 1 [1..99] ``` [Answer] ## JS (ES6), 103 bytes ``` t=(x,m,f)=>{for(r=i=s=u=1;i<1<<7+f;r+=s/(u=i++*(f?1:u)))s*=m;return r};e=(a,b)=>t(b,t(a,1-1/a,9)*b-b,0) ``` Examples : ``` e(1.234,5.678) = 3.299798925315965 e(4.5,4.5) = 869.8739233782269 e(4.5,-4.5) = 0.0011495918812070608 ``` Use Taylor series. `b^x = 1 + ln(b)*x/1! + (ln(b)*x)^2/2! + (ln(b)*x)^3/3! + (ln(b)*x)^4/4! + ...` with [natural logarithm approximation](http://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series) : `ln(b) = (1-1/x) + (1-1/x)^2/2 + (1-1/x)^3/3 + (1-1/x)^4/4 + ...` I used 128 iterations to compute `b^x` (more iterations is difficult due to factorial) and 262144 iterations for `ln(b)` [Answer] # Python, 77 As with some other answers this is based on log and exp. But the functions are computed by numerically solving ordinary differential equations. ``` def f(a,b,y=1): if a<1:a=1/a;b=-b while a>1:a/=1e-7+1;y*=b*1e-7+1 return y ``` Does it satisfy the requirements? For the examples in the question, yes. For large a, it will take a very long time. For large a or b, it will become inaccurate. Examples: ``` a b f(a, b) pow(a, b) <1e-5 rel error? 1.234 5.678 3.2998 3.2998 OK 4.5 4.5 869.873 869.874 OK 4.5 -4.5 0.00114959 0.00114959 OK 0.5 0.5 0.707107 0.707107 OK 0.5 -0.5 1.41421 1.41421 OK 80 5 3.27679e+09 3.2768e+09 OK 2.71828 3.14159 23.1407 23.1407 OK ``` Update: flawr asked for more detail on the maths so here you go. I considered the following initial value problems: * x'(t) = x(t), with x(0) = 1. The solution is exp(t). * y'(t) = by(t), with y(0) = 1. The solution is exp(bt). If I can find the value of t such that x(t) = a, then I'll have y(t) = exp(bt) = a^b. The simplest way to numerically solve an initial value problem is [Euler's method](http://en.wikipedia.org/wiki/Euler_method). You compute the derivative the function is supposed to have, and then take a, step, in the *direction* of the derivative, and *proportional* to it, but scaled by a tiny constant. So that's what I do, take tiny steps until x is as big as a, and then see what y is at that time. Well, that's the way I thought of it. In my code, t is never explicitly computed (it is 1e-7 \* the number of steps of the while loop), and I saved some characters by doing the calculations for x with a instead. [Answer] # [golflua](http://mniip.com/misc/conv/golflua/) 120 I use the fact that ``` a^b = exp(log(a^b)) = exp(b*log(a)) ``` and wrote my own `log` & `exp` functions. The values `a` and `b` need to be entered on newlines when run in the terminal: ``` \L(x)g=0~@ i=1,50 c=(x-1)/x~@j=2,i c = c*(x-1)/x$g=g+c/i$~g$\E(x)g=1;R=1e7~@i=1,R g=g*(1+x/R)$~g$a=I.r()b=I.r()w(E(b*L(a))) ``` Sample runs: ``` 4.5, 4.5 ==> 869.87104890175 4.5, -4.5 ==> 0.0011495904124065 3.0, 2.33 ==> 12.932794624815 9.0, 0.0 ==> 1 2.0, 2.0 ==> 3.9999996172672 ``` An ungolfed Lua version is, ``` -- returns log function L(x) g = 0 for i=1,50 do c=(x-1)/x for j=2,i do c = c*(x-1)/x end g = g + c/i end return g end -- returns exp function E(x) g=1;L=9999999 for i=1,L do g=g*(1+x/L) end return g end a=io.read() b=io.read() print(E(b*L(a))) print(a^b) ``` ]
[Question] [ The challenge is to generate an ASCII character count ruler in the following format: ``` +-------------------------------------------------------------------------+ || | | | | | | | | | | | | | | | |0 10 20 30 40 50 60 70 | | | +-------------------------------------------------------------------------+ ``` The length of the ruler should be scalable to any multiple of 10. Rules: * Ruler must be horizontal. * Let's say, to keep things simpler, that the ruler must work until the 1000 mark, all numbers left-aligned, **one space after the final number**. * Asking for a ruler with zero length should print NaR * Negative numbers should print a reversed ruler (-90, -80, -70, ...) with right-aligned numbers, in the exact same format as the one above otherwise And, just printing to console is fine Ready, set, golf! [Answer] Not going to beat the dynamic languages today, but anyway... ## Haskell, 341 ``` import Data.List main=interact$unlines.m.map read.words m[l,r]|r>l=ᴛ.("┌│││└":).(++["┬ ─","┐│││┘"]).ʀ.t.ʀ.t.takeWhile((>4).length).ᴛ$[c"┬",c"│ ",[l,l+10..r]>>=h.show,c" ",c"─"]|True=["NaR"] h s=p s$length s;p s@('-':_)l=r(6-l)ꜱ++s++r 4ꜱ;p s l=r 5ꜱ++s++r(5-l)ꜱ ᴛ=transpose;ʀ=reverse;r=replicate;c=cycle ꜱ=' ';t l@(c:o)|c!!2==ꜱ=t o|True=l ``` I took the liberty of exchanging the actual ASCII characters with better-looking unicode box drawing chars. ``` $ echo "-50 30" | runhaskell def0.hs ┌┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │-50 -40 -30 -20 -10 0 10 20 30 │ │ │ └─────────────────────────────────────────────────────────────────────────────────────┘ ``` [Answer] # Python - 227 232 **Supports entire specification** **edit:** improved generator expression. Supporting right aligned negative numbers adds a surprising amount of code. ``` b,p,d,w,='|+- ' g=input s=''.join(('%'+d[:i>0]+'10s')%i+['',9*w][i==0] for i in range(g(),g()+1,10)).strip()+w m,n=s[0]==d and s.find(w)-1,len(s) t=p+n*d+p print['\n'.join([t,b+(w*m+'| '*n)[:n]+b,b+s+b,b+n*w+b,t]),'NaR'][n<9] ``` Sample outputs: -30 30 ``` +-----------------------------------------------------------------+ | | | | | | | | | | | | | | | |-30 -20 -10 0 10 20 30 | | | +-----------------------------------------------------------------+ ``` -30 -30 ``` NaR ``` 100 150 ``` +------------------------------------------------------+ || | | | | | | | | | | | |100 110 120 130 140 150 | | | +------------------------------------------------------+ ``` -1000 -950 ``` +--------------------------------------------------------+ | | | | | | | | | | | | | |-1000 -990 -980 -970 -960 -950 | | | +--------------------------------------------------------+ ``` [Answer] Python 2.7, ~~342 266~~ 260 chars ``` a,b,c,d,m='+|- \n' def f(y):x=map(str,(range(0,y+1,10)if y>0 else range(y,1,10)));h,g=len(x[-1])+1,len(x)-1;u=a+(c*10)*g+c*h+a;return'NaR'if y==0 else u+m+b+(b+d*4)*2*g+b+d*(h-1)+b+m+b+''.join(i.ljust(10)for i in x[:-1])+x[-1].ljust(h)+b+m+b+(d*10)*g+d*h+b+m+u ``` returns a ~~tuple of each line~~ string, which you can then print or save to a file (I prefer the latter for lengths longer than 70 becuase the console will jsut make it look messed up with wrapping) Assumes `y` to be ~~a string (raw\_input() n python, or sys.argv[1] if you wish to invoke via cmd)~~ an integer (eg with input() in 2.x or int(input()) in 3.x) I made this a function to be more flexible edit: reduced to 266 characters. no longer returns a tuple, but a string instead. Now takes an integer instead of a string as the argument edit2: reduced to 260 chars, single line function note: does handle negative numbers, but doesn't right justify (I don't really htink the justification is too important anyways [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~256~~ ~~253~~ ~~233~~ ~~225~~ 222 bytes ``` param($a,$b)('NaR',$($d=@{} $a..$b|%{$d.$_=' ';0..($l=($s="$($_-$_%10)").Length-1)|%{$d[$_+$s-$l*(0-gt$s)]=$s[$_]}} $d.Keys|sort|%{$e+='-';$p+='| '[$_%5];$r+=$d.$_;$w+=' '} @" +$e-+ |$p | |$r | |$w | +$e-+ "@))[$a-lt$b] ``` [Try it online!](https://tio.run/##VZBBa4QwEIXv@RVBnk1SkxBZZCkS8N7SQ6@LiGK6e7BdMYIU9bfbrC1dmsPLmzcfMzD9dXKDv7iu2/BOLZ23vh7qD45aohGcvdZvTIKjtcW8EtRao1niGa1GZRlludGao7Mc3kaBqxSqODUiEvrFfZ7Hi0rFzp9QJfAK3SM36jzCi9LCh7Rcw9xWP7svv/jrMN5ol1imWI4@/AsNjwUwzsocQ2L33Tmm5LZ/JUVEEjiVkAU9XYIOu05Bf/KoEOKEWnUjmnJbCSk4uc2U3MijEb9eHYw8/FWpMTLN7s1QG6mesn@4uvNHI4MXdKExnfcsQhXt5iHctajIun0D "PowerShell – Try It Online") Less golfed: ``` param($a,$b) ( 'NaR', $( # {key, value} := {position, digit|minus|space} $d=@{} $a..$b|%{ $d.$_=' ' # draw a nearest left number $n=$_-$_%10 $s="$n" $l=$s.Length-1 0..$l|%{ $d[$_+$s-$l*(0-gt$s)]=$s[$_] } } # edge, points, ruler, whitespaces $d.Keys|sort|%{ $e+='-' $p+='| '[$_%5] $r+=$d.$_ $w+=' ' } # output the multiline string @" +$e-+ |$p | |$r | |$w | +$e-+ "@ ) )[$a-lt$b] ``` [Answer] ## Python, 291 241 characters A pretty simple approach. I'm sure it can be improved quite a lot. I tried to follow the guidelines in the comments, but I don't support negative numbers (it was a joke, I hope). This is a program, prints the ruler to standard output. If your screen is wide enough, it should support pretty long rulers. ``` import sys def p(b,a="|"):print a+b+a j="".join l=int(sys.argv[1])//10*10 if l: d=j(["%-10d"%n for n in range(0,l,10)])+"%d "%l L=len(d) h="-"*L p(h,"+") p(j(["| "[n%5] for n in range(L)])) p(d) p(" "*L) p(h,"+") else: print "NaR" ``` [Answer] ## C++, 392 This is programmed using the windows console, therefore I just chose a maximum ruler size is 70, it'll just crash for anything bigger. Negative numbers( up to -70) and 0 are handled correctly. ``` #include<ios> #define q s[2][i #define v ,memset(&s char g,o,i,n,s[5][80];int main(int a,char**b){a=atoi(b[1])v,32,400);n=0<a;for(a=abs(a)v[0][1],45,a+3)v[4][1],45,a+3);i<a+4;++i)o=i-n,!(o%5)?s[1][n?i:i+3]='|',(o%2-1?(n?q]=i/10+48,i>9?q+1]=48:0:((a-i)>9?q+2]=(a-i)/10+48,q+1]=45:0,q+3]=48)):0):0;for(;g-5;g++)for(s[g][a+4]=s[g][i=0]=g&g-4?'|':43;i-80;i++)printf(a?"%c":g+i?"":"NaR",s[g][i]);} ``` [Answer] # Python - 208 (does not support right aligned negative numbers) ``` l,u=map(int,raw_input().split()) n=u-l q="+%s+\n" q=q+"|%s|\n"*3+q print q%('-'*n,(''.join("| "for i in range(n)))[:n],(''.join("{:<10d}".format(i)for i in range(l,u,10)))[:n],' '*n,'-'*n)if n>0 else"NaR" ``` I think my favourite trick was to generate strings that are way longer than necessary and then truncate them, for example: ``` ''.join("| "for i in range(n)))[:n] ``` I just wish there was a more concise [string formatting option](http://docs.python.org/library/string.html#format-specification-mini-language) for left-alignment (unless there is one that I just don't know about) [Answer] Perl 5.14, ~~198~~ 224 chars Probably can be shortened a lot further, but here's a ~~first~~ second attempt (with line breaks inserted for readability): ``` $l=shift||die"NaR\n"; @n=grep!($_%10),$l>0?0..$l:$l..0; $l=9-length$n[$#n]; @f=('-'x10,'| 'x2,'@'.'<'x9,' 'x10); @f=map$_ x@n,@f; map$_=~s/.{$l}$//,@f; eval"format=\n+$f[0]+\n|$f[1]|\n|$f[2]|\n\@n\n|$f[3]|\n+$f[0]+\n.\n"; write ``` **EDIT:** Edited to die with "NaR" when input is `0` and to support negative range. **EDIT2:** I haven't had a chance to work more on this, and I only just now noticed the right aligned for negative numbers rule, which my code doesn't support, so I think another solution should be marked as the answer if the deadline has been reached. ]
[Question] [ [Stevin's Notation](https://en.wikipedia.org/wiki/De_Thiende) is a way to represent decimals in a non-fractional way. > > The Flemish mathematician and engineer Simon Stevin is > remembered for his study of decimal fractions. Although he was not the > first to use decimal fractions (they are found in the work of the > tenth-century Islamic mathematician al-Uqlidisi), it was his tract De > Thiende (“The tenth”), published in 1585 and translated into English > as Disme: The Art of Tenths, or Decimall Arithmetike Teaching > (1608),[3] that led to their widespread adoption in Europe. Stevin, > however, did not use the notation we use today. He drew circles around > the exponents of the powers of one tenth: thus he wrote 7.3486 as 7⓪3①4②8③6④. > > > For example, the decimal number `32.567` can be expressed as `32 + 5/10 + 6/100 + 7/1000`. In Stevin's Notation, circled numbers representing the denominator of the original decimal fraction were inserted after each number. In lieu of formatting the output via parenthesis or using any unicode characters, we will simply output the associated power of ten number. Therefore, the decimal number above would be written as `320516273`. **Task** When given a decimal input, output a Stevin's Notation integer equivalent. **Notes** * For any input containing trailing `0` after the decimal point, the author can choose whether or not to include the zeroes as part of their output notation. This holds true for multiple trailing zeroes as well. + This means for the input `1.0500`, either of the following output would be acceptable: `100152` or `1001520304` * For any input with no decimal point, or any input containing only zeroes after the decimal point, the author may choose to simply output the integer equivalent. + This means for the input `123`, either of the following output would be acceptable: `123`, `1230`. + This also means for the input `123.0`, any of the following output would be acceptable: `123`, `1230`, `123001`. * For this challenge, we can assume the input will be positive. **Test cases:** | Input | Output | | --- | --- | | `123` | `123` or `1230` | | `123.0` | `123` or `1230` or `123001` | | `123.00000` | `123` or `1230` or `12300102030405` | | `123.456` | `1230415263` | | `123.456000` | `1230415263` or `1230415263040506` | | `1.000009` | `10010203040596` | | `0` | `0` or `00` | | `0.0` | `0` or `00` or `0001` | | `0.0001` | `0001020314` | | `123456789.123456789987654321` | `1234567890112233445566778899910811712613514415316217118` | This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # JavaScript (ES6), 64 bytes Expects a string as input. ``` s=>s.replace(/\.(.*?)0*$/,(_,s)=>s&&s.replace(/()/g,_=>i++,i=0)) ``` [Try it online!](https://tio.run/##dY3LCoMwEEX3/QwpktF0jG@ziP2RgoiNkiJGTOnvp0qhFJrMajjnztxH/@rNsKn1eVn0XdpRWCNag5tc536QJLkhwegKLDonlHTUwG7D8CdAIJloJ1oVx1QJBmAHvRg9S5z1REYSpFkeAJz@KTIfP8bjirLyG8/Z5yF3KFecoYcylrqr9@a64fjdeFNXZZFnR9y@AQ "JavaScript (Node.js) – Try It Online") ## How? We first look for the fractional part in the input string: ``` .---------> decimal separator | .------> payload: a non-greedy sequence of digits | | .--> trailing zeros + end of string | _|_ | |/ \/ \ /\.(.*?)0*$/ ``` If the payload is empty, we remove the fractional part entirely. Otherwise, we replace the fractional part with the payload transformed as follows: ``` s.replace( // in the payload, /()/g, // replace each gap (beginning and end included) _ => i++, // with the counter i (incremented afterwards) i = 0 // starting with i = 0 ) // ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 33 bytes ``` /\./&`\.?0+$ /\..+/_`. $&$:& \. ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8/Rk9fLSFGz95AW4WLC8jT09aPT9DjUlFTsVLjitHj@v/f0MiYC4j1DCAkCIBZJqZmMBosBJGy5DLgMtADYwMDQ5ACoLy5haUenGVpYW5mamJsZAgA "Retina – Try It Online") Link includes test cases. Explanation: ``` /\./&`\.?0+$ ``` If the input contains a decimal point, trim any trailing zeros and also the decimal point if there are only trailing zeros (in which case the rest of the script will do nothing). ``` /\..+/_`. $&$:& ``` Number each character starting at the decimal point. ``` \. ``` Remove the decimal point. [Answer] # [sclin](https://github.com/molarmanful/sclin), 46 bytes ``` 99N>d"\."<>"len1>"Q";".' &# c>< 0swap $N","zip ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) For testing purposes: ``` 7.3486 ; 99N>d"\."<>"len1>"Q";".' &# c>< 0swap $N","zip ``` ## Explanation Prettified code: ``` 99N>d "\."<> ( len 1> ) Q \;.' &# c>< 0swap $N \, zip ``` * `99N>d` convert input to decimal representation + necessary to get around sclin's default rational representation, and also to remove trailing zeros (unless spec is more lenient) * `"\."<>` split by decimal point * `( len 1> ) Q \;.' &#` if length > 1 (i.e. decimal values exist), then... + `0swap` place zero as "decimal" + `$N \, zip` enumerate * `c><` join + NOTE: this might be removable if a jagged list is allowed as an output format - e.g. `[123 0 [ 5 1 6 2 ]]` [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 36 bytes ``` s/\.(.*?)0*$/$1&&$1=~s,(),$i++,ger/e ``` Works the same as Arnauld's Javascript answer [Try it online!](https://tio.run/##K0gtyjH9n1upkmn9v1g/Rk9DT8te00BLRV/FUE1NxdC2rlhHQ1NHJVNbWyc9tUg/9f9/QyNjLiDWM4CQIABmmZiawWiwEETKksuAy0APjA0MDEEKgPLmFpZ6cJalhbmZqYmxkeG//IKSzPy84v@6OQUA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ⭆⪪S.⎇κ⎇Σι⁺0⭆⮌II⮌ι⁺λ⊕μωι ``` [Try it online!](https://tio.run/##RUzbCgIhEP0V8WkWbLHrS4/7tA/Bkv2A2FCSmnjZ6OvNsNiBc2Y4l1F3GdRTmlKmoF0Ckeq6naQH4Y1OMDqfUxOhY4T2tPIFg5PhDY/lFNmCrtZkcgTKKSPLpzPOGCLCIGNq9Fd0V@dXMoyMTgW06BJewTbrVfFNHUtZb7b9bn/gnJfVbD4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ⪪ Split on . Literal string `.` ⭆ Map over parts and join κ Current index ⎇ If decimal part then ι Decimal part Σ Digital sum ⎇ If nonzero then 0 Literal string `0` ⁺ Concatenated with ι Decimal part ⮌ Reversed I Cast to integer I Cast to string ⮌ Reversed ⭆ Map over characters and join λ Current character ⁺ Concatenated with μ Inner index ⊕ Incremented ω Otherwise empty string ι Otherwise integer part Implicitly print ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 78 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.75 bytes ``` \.+\./ḣhfJėR ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJkPSIsIiIsIlxcLitcXC4v4bijaGZKxJdSIiwiIiwiXCIxMjNcIiJd) ## Explained ``` \.+\./ḣhfJėR­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌­ \.+\./ # ‎⁡Append a "." to the input and split on "."s ḣh # ‎⁢that[0], that[1] fJ # ‎⁣flatten(that[1]) and merge with that[0] ėR # ‎⁤Enumerate and reverse each sublist # ‎⁢⁡d flag deep sums the list 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Python](https://www.python.org), 77 bytes ``` lambda x,i=0:(s:=x.partition("."))[0]+'0'+''.join(c+str(i:=i+1)for c in s[2]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NTsMwEEb3nCLqxrZCrZnxbyL5CJygdBGKohqBEyWuVM7CJhKid-I2uLRUrObp05tv5uM0vuf9kJbPPjx-HXK_9t8Pr93b03NXHe9jgJbPbTjKsZtyzHFIfCVXQmxgWzNgNWPyZYiJ7-o5Tzy2IdYo-mGqdlVM1byhrbiWnsYppsx7zpCU1MYyEcKZQaMhq5i4uxkgAQB_hTMAgUL9XyhrpcH5Rt6o8c4arQj_ei8xIBIppbUx1jrni9ggeESHZFEZ1OW8QkslQM-u3y7LZf4A) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 13 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` '.+'./2ɱẸsƤŻZ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPScuJTJCJy4lMkYyJUM5JUIxJUUxJUJBJUI4cyVDNiVBNCVDNSVCQlomZm9vdGVyPSZpbnB1dD0lMjIxMjMlMjIlMjAtJTNFJTIwJTIyMTIzMCUyMiUwQSUyMjEyMy4wJTIyJTIwLSUzRSUyMCUyMjEyMzAwMSUyMiUwQSUyMjEyMy4wMDAwMCUyMiUyMC0lM0UlMjAlMjIxMjMwMDEwMjAzMDQwNSUyMiUwQSUyMjEyMy40NTYlMjIlMjAtJTNFJTIwJTIyMTIzMDQxNTI2MyUyMiUwQSUyMjEyMy40NTYwMDAlMjIlMjAtJTNFJTIwJTIyMTIzMDQxNTI2MzA0MDUwNiUyMiUwQSUyMjEuMDAwMDA5JTIyJTIwLSUzRSUyMCUyMjEwMDEwMjAzMDQwNTk2JTIyJTBBJTIyMCUyMiUyMC0lM0UlMjAlMjIwMCUyMiUwQSUyMjAuMCUyMiUyMC0lM0UlMjAlMjIwMDAxJTIyJTBBJTIyMC4wMDAxJTIyJTIwLSUzRSUyMCUyMjAwMDEwMjAzMTQlMjIlMEElMjIxMjM0NTY3ODkuMTIzNDU2Nzg5OTg3NjU0MzIxJTIyJTIwLSUzRSUyMCUyMjEyMzQ1Njc4OTAxMTIyMzM0NDU1NjY3Nzg4OTk5MTA4MTE3MTI2MTM1MTQ0MTUzMTYyMTcxMTglMjImZmxhZ3M9Q0o=) Input as a string. #### Explanation ``` '.+'./2ɱẸsƤŻZ # Implicit input '.+ '# Append a "." in case it isn't there already './ '# Then split it on "."s 2ɱ # And take the first two items Ẹ # Dump both parts onto the stack sƤ # Split the second part into characters and prepend the first part Ż # Push [0..length] without popping this list Z # And zip these two lists together # Implicit output, joined ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes (17 nibbles) ``` `(%$"."+:0!+$,~: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWGxI0VFWU9JS0rQwUtVV06qwgwlDZTdFKMUqGRsZ6JqZmBgYGMUpKsVAZAA) Outputs a trailing zero after integers (as permitted), and retains trailing zeros after the decimal point. --- # [Nibbles](http://golfscript.com/nibbles/index.html), 10 bytes (20 nibbles) ``` `(%$"."?,$+:0!+$,~: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWmxM0VFWU9JTsdVS0rQwUtVV06qwgMlAF66OVYpQMjYz1TEzNYpSUYqHCAA) No trailing zero after integers, but retains trailing zeros after the decimal point. ``` `(%$"."?,$+:0!+$,~: %$"." # split the input string on "." `( # and output the first part ?,$ # now, if there's second part !+$ # zip it together with ,~ # 1..infinity : # by concatenation, :0 # prepend a zero # and output it after the first part ``` --- # [Nibbles](http://golfscript.com/nibbles/index.html), 14.5 bytes (29 nibbles) ``` :`(%$"."+?,;!\`@~`r\+$,~::0$ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWe6wSNFRVlPSUtO11rBVjEhzqEopitFV06qysDFQgSqAq10crxSgZGhnrmZiaxSgpxUKFAQ) Outputs according to the initial test cases: no trailing zero for integers, no trailing zeros after the decimal point. [Answer] # [Scala](http://www.scala-lang.org/), 93 bytes Port of [@SuperStormer's Python answer](https://codegolf.stackexchange.com/a/264580/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##XY4/T8MwFMT3fArLk60gy89/EyRHYmRgYmDpYhK3TUiDRSwUUfWzB5cIpDLd6fR7d29u/ejX99chtAk9@X5CYUlh6mb0EOO5KIpPP6L9PXlOH/10cM2mFLl1cc3C5jj2ieDdjmHKjsF3Jea4vM0JUPbVx5c@HR@nLizs5OO59XMg7d1AXdOWGJdkKIFe2OltG1gRilnTOJE9wSAkU9pg6tzVcwVaGIlpcUNxxjmHH@hquOAS1H8on@cmW9Xsz9WVNVpJAb/9W8wBhJBSKa2NsbbKYA28ArAgDEgNKr8hwYgcQJV3Lus3) ``` x=>x.split("\\.").head+"0"+x.split("\\.")(1).zipWithIndex.map{case(c,j)=>c+""+(j+1)}.mkString ``` Ungolfed version. [Try it online!](https://tio.run/##ZU9NT8MwDL3vV1g9pQJFcZKm3aQhcZwEJ4Q4AIfQdSPQdVUTocLU317cDwYSF8t@79nPz@e2tH1/fHkr8gC31lVwWgBsix3sWLuCu9C4an8JbgWbKsAaRPwD0jBIAT5sCbVtgiek5b4uXWDR0xOP4jM9UKOEYczD8cb5wL9c/eDC66baFi0/2BpOkFtfAMvJbtvGsL6CnMSz2wUwR4UYquOVmej44X1qR7vJRsSkikRE1RPcLeZQB0rIbLP3K7huGvv5OG0@U6r7yoVzpprQUFZsxyKUiuvERPTQGoZJaEykUXO8P0rBhRA4C4dWSKFQ/xfSEbqYZkt@7pZZahKtJP76TIRAlFIprZPEmDTNSLpEkSGmKA2qBDW9o9BIAjAbvbpF1/ff) ``` object Main { def f(x: String, i: Int = 0): String = { val parts = x.split("\\.") val s = parts(1).toList.zipWithIndex.map { case (c, idx) => c.toString + (i + idx + 1).toString }.mkString parts(0) + "0" + s } def main(args: Array[String]): Unit = { println(f("123.456") == "1230415263") println(f("0.0001") == "0001020314") println(f("123456789.123456789987654321") == "1234567890112233445566778899910811712613514415316217118") } } ``` ]
[Question] [ Given a list of fractions, group them so that each group sums to a whole number. This should be done in such a way to maximize the number of non-empty groups. You may assume a solution exists. Order does not matter, both for the groups and their contents. You may output in any order. ## Test Cases | Fractions | Groups | | --- | --- | | `1/2, 1/2, 1/2, 1/2` | `(1/2, 1/2), (1/2, 1/2)` | | `1/2, 1/3, 1/6, 6/7, 8/7` | `(1/2, 1/3, 1/6), (8/7, 6/7)` | | `5/3, 2/3, 2/3, 1/3, 1/3, 1/3` | `(1/3, 5/3), (1/3, 2/3), (1/3, 2/3)` | | `9/2, 3/4, 1/12, 7/4, 2/3, 2/3, 7/12` | `(9/2, 3/4, 1/12, 2/3), (7/4, 2/3, 7/12)` | | `1/10, 1/5, 1/2, 7/10, 1/2` | `(1/10, 1/5, 7/10), (1/2, 1/2)` | ## IO You may take fractions as a tuple or list of `[numerator, denominator]`, and output in the same format. You can also use your language's built-in fraction type if it exists. If there are multiple optimal solutions you may output any of them, some of them, or all of them. Do not output any non-optimal solutions. [Answer] # JavaScript (ES7), 176 bytes Expects a list of `[numerator, denominator]` pairs. ``` a=>eval("for(o=n=a.length,q=n**n;q--;)o[(p=a.map((_,j)=>a.filter((_,i)=>!(q/n**i%n^j))).filter(a=>a+a)).length]||p.some(b=>b.map(([p,q])=>[P=P*q+p*Q,Q*=q],P=0,Q=1)|P%Q)?o:o=p") ``` [Try it online!](https://tio.run/##hVHRboIwFH3fVzATkxYLpSBUZ@p@AZ4JW6oDh8G2qPHJf2etjU6UZX3ouefe5pyc3i0/8cN6X6ujJ@RX2VWs42xZnngDRpXcA8kE435Tis3xG7VMuK5YtJ63gDIHSk92XAHwibaQLblf1c2x3Btea/4KWqzf12PxsYUQXqdank@45la0OJ@Vf5C7EqzYcmX1coXaQivkKUvddqLcDGUuawuUsgBljMBzOs7gu3yTTI1gt5biIJvSb@QGVCDPCQoL5AyAM3wKCB2MHUBwiBx9QXRXv/ypHllIDCSIGphp@Ec9MldiLGaYIifB9NkittphD8gTDFho9RhHNoCuw4f6yWluw0RoakXJhVJL@/7UDK9OcxMmwlMThoQ3I2o6oXGjuj30dySwRvHdauit@7ii32AkMFbxRTjoLaj7AQ "JavaScript (Node.js) – Try It Online") ### Commented This is a version without `eval()` for readability. ``` a => { // a[] = input list of fractions for( // main loop: o = // o[] = output, initially not an array n = a.length, // n = length of a[] q = n ** n; // q = counter, initialized to n ** n q--; // stop once q = 0 has been processed ) // o[ // test o[], using the length of p[]: ( p = // p[] = partition a.map((_, j) => // for each element at index j in a[]: a.filter((_, i) => // for each element at index i in a[]: !( // keep this entry if q / n ** i % n // floor(q / n ** i) mod n ^ j // is equal to j ) // ) // end of filter() ).filter(a => a + a) // end of map(); remove empty slots ).length // get the final length of p[] ] || // abort if p[] is longer than o[] p.some(b => // for each list of fractions b[] in p[]: b.map(([p, q]) => // for each fraction [p, q] in b[]: [ // we add p/q to P/Q by: P = P * q + p * Q, // updating the numerator P Q *= q // updating the denominator Q ], // P = 0, Q = 1 // start with P/Q = 0/1 ) // end of map() | P % Q // trigger some() if Q is not a divisor of P ) ? 0 // end of some(); do nothing if truthy : o = p; // otherwise, update o[] to p[] // (implicit end of for) return o // return o[] } // ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ṖvøṖÞf'Ṡ¨=⌊;ÞG ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJhIiwiIiwi4bmWdsO44bmWw55mJ+G5oMKoPeKMijvDnkciLCIiLCIxLzJcbjEvM1xuMS82XG42LzdcbjgvNyJd) Times out for anything more than 5 fractions if you're lucky. Don't even bother giving it the third and fourth test case. Inputs as a list of fraction objects. Due to technical limitations, this is done with the `a` flag for convenience. ## Explained ``` ṖvøṖÞf'Ṡ¨=⌊;ÞG # We'll call the length of the list N so we can see why this takes so long Ṗ # Permutations of the input - returns a list of N! items vøṖ # To each of the N! permutations, get all possible partitions. Each permutation has 2^(N-1) partitions, so there are now N! * 2^(N-1) sublists but still N! items Þf # Flatten the entire thing by one level. This iterates over each of those N! * 2^(N-1) sublists. ' ; # From those partitions of permutations, keep only those where: (also iterating over each of those N! * 2^(N-1) items) Ṡ # Summating each partition ¨=⌊ # is invariant under flooring ÞG # Get the longest remaining item. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 148 bytes ``` Last@Sort@(y=Flatten)[(a=#;(x=Select)[a~TakeList~#&/@x[Range@n~Tuples~#&~Array~(n=Length@a)~y~1,Tr@#==n&],Tr@Mod[Tr/@#,1]==0&])&/@Permutations@#,1]& ``` [Try it online!](https://tio.run/##RY7BCoJAFEXXfceAKAhm0SoeTJtWBpLuBhcPe6ikY8w8QYnm1yeLoMWByz1wuQNySwNyV6NvwGdoWRajYRkucO6RmXSkQgRxDGcoqKeaI4WuxDtlnWUngkTO6oq6IaldOT16smvpTsbg4kINGemGW4mRW1wal0YKAB1Un3QZb6o0iRRxWgFsgypax3Iyw8TroVHbrwl8bjrNslHPQ7KPdz/SP69q4/0b "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œ€.œ€`éʒε.EOT.òDïQ}P}θ ``` -2 bytes by taking the input as a list of strings `"a/b"` instead of list of pairs `[a,b]`. [Try it online](https://tio.run/##yy9OTMpM/f//6ORHTWv0wGTC4ZWnJp3bqufqH6J3eJPL4fWBtQG153b8/x@tZKhvpKSjZKFvDiQN9Y3BpBmQNAOKxAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5MfNa3RA5MJh1eemnRuq56rf4je4U0uh9cH1gbUntvxX@d/dLSSob6Rkg4GGaujgJAyBpNmQNJM3xxIWgBJsAJTsJQREmmIRkLNMTQA803hdpjDhKBWWYJFjfVNwIKGECUmaIabgyRiYwE). **Explanation:** ``` œ # Get all permutations of the (implicit) input-list €.œ # Get all partitions of each permutation €` # Flatten it one level down to a single list of partitions é # Sort it by length (shortest to longest) ʒ # Filter this list of partitions by: ε # Map over each part of this partition: .E # Evaluate each inner string as Elixir to get the decimals O # Sum them together T.ò # Round it to 10 decimal values to fix floating point errors DïQ # Check that it's an integer: D # Duplicate ï # Cast the copy to an integer (floor for positive integers) Q # Check if the two are equal }P # After the map: check if all parts in this partition were truthy }θ # After the filter: pop and leave the last/longest valid partition # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 92 bytes ``` ≔E⪪S,⁺⟦ικ⟧I⪪ι/θ≔ΠEθ§ι³ηFθ⊞ι×÷η⊟ι⊟ιWθ«≔ΦEX²LθΦθ﹪÷κX²ν²∧κ¬﹪ΣEκ§μ²ηι≔§ι⌕EιLκ⌊EιLκι≔⁻θιθ⟦⪫Eι§κ⁰, ``` [Try it online!](https://tio.run/##ZVHda4MwEH9u/4rgU4QMVx2UsSfZKHTMIbi30gdRZw5j4kdsB2N/u7ukceuYEDnufl@XFDwfCpWLeY7HEWpJk7yjWSdA073sJp3pAWRNfUY85uE/FdNID8BIc2TkMR@1A2PHCzwfP0Z6/2Ht1NJBlVOhrWrPSKz3sqw@DDqyUI7QdzUQ2vsknUZuJm/QViO66yc4QVlRjq6qo2DwrkDWmYOoLO9zvXJuOxC6GqxZqs5YhYy8VLLWHHHIdnMMkmAsoa5MGqPtKNJgQ5svlqUZvSpc4ULJptYaNL/btAuaX/YHjLdEutp4ByhmqPCTqjHwBCS0TvXP6J8YIvH2e9O83PIqxdfR9PCsQC78xRED3vru3Y6I/Zrn@yBkUXDHNsEmZFsswiCyZ4uN@eYkvgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E⪪S,⁺⟦ικ⟧I⪪ι/θ ``` Input the fractions and split them into numerator and denominator. ``` ≔ΠEθ§ι³η ``` Calculate a common denominator that will work for all of the fractions. ``` Fθ⊞ι×÷η⊟ι⊟ι ``` Calculate the equivalent numerator for each fraction. ``` Wθ« ``` Repeat until there are no more fractions to process. ``` ≔ΦEX²LθΦθ﹪÷κX²ν²∧κ¬﹪ΣEκ§μ²ηι ``` Get all of the subsets of the fractions but filter out the empty set and any set whose sum of numerators isn't a multiple of the common denominator. ``` ≔§ι⌕EιLκ⌊EιLκι ``` Find the shortest such subset. ``` ≔⁻θιθ ``` Remove the shortest subset from the remaining fractions. ``` ⟦⪫Eι§κ⁰, ``` Output the original fractions from the shortest subset. ]
[Question] [ Given two sets of strings, \$ D \$ and \$ R \$, find the shortest string which contains every string in \$ D \$, but contains none of the strings in \$ R \$. There are almost always multiple possible outputs; you should output at least one of them, but you can output more. You can assume this is possible with the inputs you are given; i.e., none of the strings in \$ R \$ are substrings of those in \$ D \$. Note that the result \$ s \$ may have to include characters which are not present in any of the strings in \$ D \$. For example, when \$ D = \{\text a, \text b\} \$ and \$ R = \{\text {ab}, \text {ba}\} \$, there must be at least one other character in the output - it would have to be something like \$ \text {axb} \$ or \$ \text {bxa} \$. Furthermore, in order to simplify dealing with the case above, you may choose a character that you can assume to never be present in the input, but is allowed in the output. For example, you may restrict your input to always use letters, but sometimes give outputs containing underscores as well as letters. "String" here is used in an abstract sense: you may operate on actual strings of characters, but also on lists of positive integers, or any other reasonable domain. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases | \$ D \$ | \$ R \$ | output | | --- | --- | --- | | (empty set) | (empty set) | (empty string) | | (empty set) | `a` | (empty string) | | `a` | (empty set) | `a` | | `ab`, `bc` | (empty set) | `abc` | | `a`, `b` | `ab`, `ba` | `axb` or `a$b` or etc. | | `ab`, `bc` | `abc` | `bcab` or `abbc` | | `ab`, `cd` | `bc` | `cdab` | | `ab`, `a` | `c` | `ab` | | `code`, `golf`, `fig`, `egg` | `igo` | `codeggolfig` | | `a`, `b`, `c` | `abc`, `bac`, `ca` | `cba` or `acb` | | `a`, `b`, `c` | `ab`, `bc`, `ac`, `ba`, `cb`, `ca` | `a$b$c` etc. | *This question came to me while attempting to optimise the substring check in [this answer](https://codegolf.stackexchange.com/a/246789).* [Answer] # [Python](https://www.python.org), 150 bytes ``` f=lambda D,R,m=min:m([h for d in D for e in f(D-{d},R,sorted)for x in range(len(d)+2)if(d in(h:=(d+"_")[:x]+e))>any(r in h for r in R)]or[""],key=len) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY89asQwEIXr1SkGVRrWmyJVMCiVT7Dt7hJk_XhFbNlIDthEuUaaNAshuVPIZSLZJtV8zHtvfj6-h3m89u72afj562U0h4efd8Nb0dVKQFUci4531pUdO13B9B4UWAfVgjqjYdXhVb0lY-j9qBVmZcqKF67RrNWOKdzfozUsZ9m15Ezt6RPFUzld9hrxUbiZ-RxZVyx4xEvvT5Reimc98zQFt-t-A6eUkkiiICISUUMtU4E6ZhRbQ9Qyk1RxBRFl9sCiJJsEKYjslYambw0Y24BummibHnYkzyf_f4S7MLR2bK3TgWFJdtbAlMpOFelUDizokc2riSEuL8w5OG09Gili8g_eupGpwqecHjwzmRELCHrg9DzS7cXbba1_) ## Old [Python](https://www.python.org), 152 bytes ``` lambda D,R:min((g:=lambda D:[h for d in D for e in g(D-{d})for x in range(len(d)+2)if(d in(h:=(d+"_")[:x]+e))>any(r in h for r in R)]or[""])(D),key=len) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY9NasMwEIXX0SkGrWaI00VXxaCufIJsk1Bk_UXUkY3tgE3VexS6CZT2TqWXqWW7Xb2PN-8NM-9fzdif63D7sOL4ee3t7uH7rZKXUksosn1-8QHR5eLPyg9nsHULGnyAYkaT0GGxe9GvlIwhGa0MzmBlAmra3pO3mCp4zgXqLX_idMiH09YQPcowYpsqy-YZ93Sq2wPnJ8KCsmczimkTrff9dIJzziKLksnIZAmlmgTKmFCuhixVIqXjAjKqlIF5MsUUKMlUrQ24urJgvQPjXPSuhg1L-9n_L91d11S-r3wwHVLONt7CMMlGZ9O5ArAzPY5LCInmN8ZUHFaPR0405ZvWhx511k4907RoExNl0JlG8GPP1xdvt0V_AQ) ## Old [Python](https://www.python.org), 158 bytes ``` lambda D,R:min((g:=lambda D:[h for d in D for e in g(D-{d})for x in range(len(d)+2)if d in(h:=(d+"_")[:x]+e)and not any(r in h for r in R)]or[""])(D),key=len) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY9NasMwEIXX0SkGrWaI00VXxaCdT5CtE4ps_UTUkY3tgk3VkxRKoLR3Kr1MJdvtaj7evDfMe_vq5vHS-tuHEafP59EcHr7fG3mtlIQiO-ZX5xFtLv6kvLyAaXtQ4DwUC-qEFovDi3qlJExJ6KW3GhvtUdH-npxZInjJBao9f-RU5tN5r0l6Bb4dQfoZ-xRc7y94pHPbl5yfCQvKnvQs4j3avvwZBOecBRYkk4HJCqo6DqhCQrkJsqoT1SqsIEOdPLBsoq2GWrK6VRps2xgwzoK2Njjbwo6l--y_0XA3dI0bG-f1gJSzXew0xbFTWXxXAA56xHk1IdFSY07BadN44ETR3_XOj6iyPuZ016NJTJTBoDvBTyPfKt5u6_wF) [Answer] # JavaScript (ES6), ~~159~~ 157 bytes Expects `[D,R]`. Assumes that the input words are made of letters and uses `0` as the separator. ``` f=(b,a=b[q=0],p='')=>a.map((v,i,g)=>(g=v=>f(b,a.filter((_,k)=>k-i),p+v)&&v&&g(v.slice(1)))(0+v))+[p[q.length]]||b.some((a,i)=>a.some(w=>!p.match(w)^i))?q:q=p ``` [Try it online!](https://tio.run/##nZPdTsMgFMfvfYpKTD1kjM1bE@aDNNUApQzXFdqSTpO9ey01m4mj6uTmBA7ndz7@8Mp73snWOL@sbaGGoWQgCGcia9g6J47d32O24XTPHUBPDNHjFjTr2aYMF2lpKq9agBeyGz27pcHELXqcpn2aauhpVxmp4AFjDOvxHC8ylzW0UrX22zw/HgXt7F4BcGKmRNPuwDa3bszp5RYO@Nlg/NQ8NswN0tadrRStrIYSsiz5YeUk4s5zjJPVKgG1d/496Xxrao1vruQijv7HvQz8Y708ghKIJEhIdC1KyFhdgYVm@/3M9VX9GfYmEtsm/G4yykt6baGj@5vnxBaSizmaLGZoF2lONFnM06KqBJpEs0O8ZMnxAwWatlUZbGl0MEprFFhG23ifIU6HIKNnhQkto5nhTcpMRnJ0hgo@CSOjTY/ji0vy28sphg8 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function using: b, // b[] = [D[], R[]] a = b[q = 0], // a[] = D[], // q = final output (initially not a string) p = '' // p = current output ) => // a.map((v, i, g) => // for each string v at position i in a[]: ( g = v => // g is a recursive function taking a string v f( // do a recursive call to f: b, // pass b[] unchanged a.filter((_, k) => // pass a copy of a[] ... k - i // ... with the i-th entry removed ), // p + v // append v to p ) // end of recursive call && v // unless v is an empty string: && g(v.slice(1)) // do a recursive call to g with v.slice(1) )(0 + v) // initial call to g with a leading "0" added to v ) // end of map(), whose result is coerced to a string + [p[q.length]] || // if a[] was empty and p[q.length] is undefined: b.some((a, i) => // for each entry a[] at position i in b[]: a.some(w => // for each string w in a[]: !p.match(w) // 1 if w is not found in p / 0 otherwise ^ i // XOR'ed with the expected result // (0 for D[], 1 for R[]) ) // end of inner some() ) // end of outer some() ? q : q = p // update q to p if the above test didn't fail ``` [Answer] # [Python](https://www.python.org), ~~172~~ ~~168~~ 164 bytes ``` from itertools import* f=lambda D,R:next(x for i in count()for x in map("".join,product(*[{"$"}.union(*D|R)]*i))if all(j-(y in x)for j,X in[(0,D),(1,R)]for y in X)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PZBBTsMwEEXX9SlGFouZyK1gh5Cy6wm6qlRYOE4iXCW2ZTtSKsxJ2HQBXIRTcBvsNnQ1f77fjL7n49ud4qs15_PXFPv14-9n7-0IOnY-WjsE0KOzPlasrwc5Nq2Erdg9mW6OOENvPWjQBpSdTEQq_Vz6UTrkfHO02gjnbTupiNXhjd_x981ktDVYbdOOXipNpHuQw4DHNZ7K6HzZchT73BzwXmxJ4IPIbLEvxJ5oyfoTas45SyxJJhOTDTQqF2hSkXIxZKOKUm26CplUYeDykjEFSrKyh93yh01wg46DNl1AemKrHHLOZdUK8FADhi7i6QohEdyyzYvHEyfKvPM6H6YVPs91zmNfNJGA0LmaP0e-fOX__H8) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` JDu«æ€œ˜é.Δ¹åy²å_«P ``` +1 byte as bug-fix for test cases that require more than 1 random filler-character (e.g. `[["a","b","c"],["ab","ba","ac","ca","bc","cb"]]`). Assumes the input are lowercase letters, and uses uppercase letters as potential filler-characters if necessary (e.g. for the fifth test case). [Try it online](https://tio.run/##yy9OTMpM/f/fy6X00OrDyx41rTk6@fScwyv1zk05tPPw0spDmw4vjT@0OuD//2ilRCUdpSSlWC4gKwnETFSKBQA) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/71cSg@tPrzsUdOao5NPzzm8Uu/clEPrDi@tjDi8NP7Q6oD/tTr/o6OjY3WiY2N1FMAMpUQlCBvEgIkrJSYp6SglJSOLgASUwBrAcghtCKVAdjKKcHIKWBhNFGyREkIMbLKOEsIIkPEgMjkRlxqIC4BGQZWBXQBkAV0YGwsA). **Explanation:** ``` J # Join the (implicit) first input-list together to a string Du« # Append an uppercase copy of this string æ # Get the powerset of this string €œ # Get the permutations of each inner string ˜ # Flatten this list of list of strings é # Sort it by length .Δ # Find the first which is truthy for: ¹ # Push the first input-list å # Check for each inner string if it's a substring y # Push the string we're filtering over again ² # Push the second input-list å # Check for each inner string again if it's a substring _ # Invert the booleans to check all of them were falsey « # Merge the two lists together P # Check that all are truthy by taking the product # (after which the found result is output implicitly) ``` [Answer] # Python3, 261 bytes: ``` E=enumerate def f(d,c=''): if not d:yield c;return for i,a in E(d): j=d[:i]+d[i+1:] yield from[*f(j,c+a),*f(j,c+'$'+a)] for x,y in E(a): if c[-1*x:]==a[:x]:yield from f(j,c+a[x:]) lambda d,r:min([i for i in f(d)if all(m not in i for m in r)],key=len) ``` [Try it online!](https://tio.run/##hU/LbsMgELz7K/ZQCYhppaiXiopj8hOUA@bhkmKwqCPFX@9CHal1oqoXxM7MzuyM8/Se4vPLmJcjf1uCGjqjwNDMBh@x8OBSBg8@gsOGeAcqBDxATFPFVnqo30wk/bAzDzaS5sBtPA82q8k2xrq6SzVHiLAGikfdNmz2NhjQr9lO5xybNYmqanYoWUUKJ24E87I1wrd7JguyLrmcBrFz@ER1qwi9/tADKlNVVasLnVcr9W1Vc7V43O8uTHKuBLtI9mMGVy9RWLKM2ccJH7GQVEhCmt8zUmgD1XmrQqqj0Gn09DkGP2FEAZFbRRFseVi31Ab9zxRKesFu7ukqqU05q/B/0GpltyTSyVgKfQqOgvM9Bdv3d4m@T@iuDAV930fXQuXRt62WLw) [Answer] # [Python 3](https://docs.python.org/3/), 141 bytes ``` f=lambda d,r,s='':d[len(s):]and min([s*(all(w in s for w in d.split())-any(w in s for w in r.split()))or f(d,r,s+c)for c in{*d}],key=len)or d ``` [Try it online!](https://tio.run/##bY3BCsIwDIbvPkXAQ1utXrwJexLZIWvWWqztWAcyxGef2YShm5eQfP@XpOm7a4qnYbBFwHtFCKRbnQshznQJdZRZnUuMBHcf5SXvJIYgH@AjZLCphamlY26C76RSB4z9Km7nWDGycvqwN2oUDAvPHb1Kfav7gh@OCg1N62MnrRRCC6HU5nvGH4BLAyuozApCNW5yhH9l5LrghpgvMTD/6HzJgJmubefcJKrBpWDBege1c0KD8C6xNbwB "Python 3 – Try It Online") Recursive solution trying all possible permutations and returning the shortest one. Takes each input as a single space-separated string. Also uses [space] as the special character in the output. The longest test-case times out, but should work in principle. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` ⊞υωFυ¿¬ⅉ¿›⬤θ№ικ⊙η№ικ⟦ι⟧F⪫θ_⊞υ⁺ικ ``` [Try it online!](https://tio.run/##VY29CsMwEIP3PsVx0xncJ8gUOhQ6lKwlmOIYh5iamPonpU/v2k6WLgKJT5JapFdO2pyHFBZKHD6sO83OAyUGZga6u0gPYru5ei2j9tRbS28OF5fWSIbDizEO/fql5T8stcGbYkcjyq62QUMbvzmz1gV8YmWO78GmcDS7nMcRJRZkqqJQcChBM5OqKptOjVE7JFGIfN7sDw "Charcoal – Try It Online") Link is to verbose version of code. Brute-force, so exponentially slow in the length of the output. Uses `_` as the filler character. Explanation: ``` ⊞υωFυ ``` Start a breadth-first search of all strings containing the input characters or `_`. ``` ¿¬ⅉ ``` Stop when a string has been output. ``` ¿›⬤θ№ικ⊙η№ικ⟦ι⟧ ``` If the current string satisfies the inputs then print it now. ``` F⪫θ_⊞υ⁺ικ ``` Otherwise, for each character in the inputs or `_`, append that character to the current string and push the result to the search list. ]
[Question] [ Starting at 1-TET, give equal temperaments that have better and better approximation of the perfect fifth(just ratio 3/2). ([OEIS sequence A060528](https://oeis.org/A060528)) The formal description of the sequence, copied from the OEIS: > > A list of equal temperaments (equal divisions of the octave) whose nearest scale steps are closer and closer approximations to the ratios of two tones of musical harmony: the perfect 4th, 4/3 and its complement the perfect 5th, 3/2. > > > Note that by symmetry, the perfect fourth doesn't matter. Let's say we know that 3 is in the sequence. The frequencies in 3-TET are: ``` 2^0, 2^⅓, 2^⅔ ``` Where `2^⅔` is the closest *logarithmic* approximation of `3/2`. Is 4 in the sequence? The frequencies in 4-TET are: ``` 2^0, 2^¼, 2^½, 2^¾ ``` Where `2^½` is the closest approximation of `3/2`. This is not better than `2^⅔`, so 4 is not in the sequence. By similar method, we confirm that 5 is in the sequence, and so on. When given an integer `n` as input, the output must be the first N numbers of the sequence in order. For example, when `n = 7`, the output should be: ``` 1 2 3 5 7 12 29 ``` **Sequence description by xnor** The irrational constant \$ \log\_2(3) \approx 1.5849625007211563\dots\$ can be approximated by a sequence of rational fractions $$ \frac{2}{1}, \frac{3}{2}, \frac{5}{3}, \frac{8}{5}, \frac{11}{7}, \frac{19}{12}, \frac{46}{29}, \dots$$ A fraction is included in the sequence if it's the new closest one by absolute distance \$ \left| \frac{p}{q} - \log\_2(3)\ \right|\$, that is, closer than any other fraction with a smaller or equal denominator. Your goal is to output the first \$n\$ denominators in order. These are sequence [A060528](https://oeis.org/A060528) ([table](https://oeis.org/A060528/b060528.txt)). The numerators (not required) are given by [A254351](https://oeis.org/A254351) ([table](https://oeis.org/A254351/b254351.txt)) **Rules:** 1. Do not import the sequence A060528 directly. 2. The format doesn't matter as long as the numbers are distinguishable. In the example above, the output can also be: `[1,2,3,5,7,12,29]` 3. As this is a code-golf, the shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 18 bytes ``` µ¯ßNLN/3.²<αßDˆ›D– ``` [Try it online!](https://tio.run/##ASgA1/9vc2FiaWX//8K1wq/Dn05MTi8zLsKyPM6xw59Ey4bigLpE4oCT//83 "05AB1E – Try It Online") ``` µ # repeat until counter == input ¯ # push the global array ß # get the minimum (let's call it M) N # 1-based iteration count L # range 1..N N/ # divide each by N 3.² # log2(3) < # -1 α # absolute difference with each element of the range ß # get the minimum Dˆ # add a copy to the global array › # is M strictly greater than this new minimum? D– # if true, print N # implicit: if true, add 1 to the counter ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 60 bytes ``` Denominator@NestList[Rationalize[r=Log2@3,Abs[#-r]]&,2,#-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU1Lz83My@xJL/IwS@1uMQns7gkOggonZ@XmJNZlRpdZOuTn27kYKzjmFQcraxbFBurpmOko6xrGKv2P6AoM6/EIc3BxOA/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~81~~ ~~80~~ 78 bytes -2 bytes thanks Arnauld! ``` n=>{for(d=g=1;w=Math.log2(3),w+=~(w*g-.5)/g,n--;g++)w*w<d?d=print(g)||w*w:n++} ``` [Try it online!](https://tio.run/##DchRDoIwDADQ67SUIUJMjFg5gYdYWFYxZpCx0A@Bq0/f53vb1S5DHOdk1mv2nAM/vn6K4Fj43Ck/bXpVn0kaaLFU4gO0EFNd8CRlMKYTItRC7653PMcxJBDctv/cAtGePTQ15h8 "JavaScript (V8) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` E=k=input() n=0 while k: n+=1;e=abs((3.169925001442312*n-1)%2-1)/n if e<E:print n;E=e;k-=1 ``` [Try it online!](https://tio.run/##DcRBCoMwEADAe16xl0K0WLOrFTTuMQ@xkGKIbINGSl@fOodJv7x@hEpxHDlIOrOulLBR3zVsHuKkQO6M1vPyOrTuHjiMIz2Nwb6nDqmWBqsbXbWiILzBz25Ke5AMYh17GxvGUtD8AQ "Python 2 – Try It Online") Uses the constant `3.169925001442312` for \$2 \log\_2(3)\$. I wasn't sure how many digits of accuracy are required, since the inaccuracy will break the sequence eventually, so I used the full float precision of `2 * numpy.log2(3)`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~128~~ ~~111~~ 108 bytes ``` import StdEnv c=ln 3.0/ln 2.0 ?d=abs(toReal(toInt(c*d))/d-c) $i=take i(iterate(\d=until((>)(?d)o?)inc d)1.0) ``` [Try it online!](https://tio.run/##Dc29DoIwEADgnafowNCaAPVnrSw6kDjJ6nL2qrnYXg0cJr68lekbPx8DcEkZlxhUAuJC6Z0nUaPgmT@Vd5HVvrXdyq61VY8O7rOWfA0QVwYW7TdoTIeNN1VNTuAVFGmSMIEEfUO3sFDU@mh0jyb3htgrNNvWmjIKrJdTtTrY8vOPCM@5NMOlnL4Mifz8Bw "Clean – Try It Online") Should work up to the limits of `Real`'s 64-bit double precision type. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~27~~ 25 bytes ``` 1`@:@/Q3Zl-|X<hY<tdzG-}df ``` [Try it online!](https://tio.run/##y00syfn/3zDBwcpBP9A4Kke3JsImI9KmJKXKXbc2Je3/f3MA) ### Explanation ``` 1 % Push 1. This initiallizes the vector of distances ` % Do...while @: % Range [1, 2, ..., k], where k is the iteration index, staring at 1 @/ % Divide by k, element-wise. Gives [1/k, 2/k, ..., 1] Q % Add 1, element-wise. Gives [(k+1/k, (k+2)/k, ..., 2] 3Zl % Push log2(3) -| % Absolute difference, element-wise X< % Minimum h % Concatenate with vector of previous distances Y< % Cumulative minimum t % Duplicate dz % Consecutive differences, number of nonzeros. This tells how many % times the cumulative minimum has decreased G- % Subtract input n. This is the loop condition. 0 means we are done } % Finally (execute on loop exit) d % Consecutive differences (of the vector of cumulative differences) f % Indices of nonzeros. This is the final result % End. A new iteration is executed if the top of the stack is nonzero % Implicit display ``` [Answer] # [Perl 5](https://www.perl.org/) (`-MPOSIX=log2 -M5.01 -n`), ~~73~~, ~~78~~, 71 bytes Fixed following comment, may be improved... -7 bytes thanks to Grimy ``` $o=abs$d-(0|.5+($d=log2 3)*++$;)/$;;$@=$o,$_-=say$;if!$@|$o<$@;$_&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3zYxqVglRVfDoEbPVFtDJcU2Jz/dSMFYU0tbW8VaU1/F2lrFwVYlX0clXte2OLFSxTozTVHFoUYl30bFwVolXk2tKDUl//9/83/5BSWZ@XnF/3V9A/yDPSPA5gA5pnoGhv918wA "Perl 5 – Try It Online") ]
[Question] [ ## Introduction: In the **northern hemisphere** (i.e. Europe, North America, etc.), the seasons are divided like this: - **Spring:** March, April, May - **Summer:** June, July, August - **Autumn:** September, October, November - **Winter:** December, January, February In the **southern hemisphere** however (i.e. Australia, South America, etc.), the seasons are divided like this: - **Spring:** September, October, November - **Summer:** December, January, February - **Autumn:** March, April, May - **Winter:** June, July, August This difference is due to the position of the sun regarding the equator, where the northern and southern hemispheres have opposite seasons. ## Input: In this challenge, we'll take two inputs: * One for the month (`1 <= m <= 12` or `0 <= m <= 11`) (examples and test cases are all 1-indexed). * And one for the five 'position-groups' at the latitudes of Earth (`-2 <= p <= 2`), where `-2` is the Antarctic, `-1` is the southern hemisphere excluding the Antarctic, `0` are the Tropics in proximity of the equator, `1` is the northern hemisphere excluding the Arctic, and `2` is the Arctic. Although the Arctic, Antarctic and Tropics of course still have seasons, for the sake of this challenge we'll say the Arctic and Antarctic are in a constant state of `Winter`, and the Tropics are in a constant state of `Summer`. Here a visual representation of these five groups, where `-2` is the Antarctic Circle; `-1` between the Tropic of Capricorn and Antarctic Circle; `0` between the Tropic of Capricorn and Tropic of Cancer; `1` between the Arctic Circle and Tropic of Cancer; and `-2` the Arctic Circle. [![enter image description here](https://i.stack.imgur.com/BB40hm.jpg)](https://i.stack.imgur.com/BB40hm.jpg)[![enter image description here](https://i.stack.imgur.com/WzAmNm.jpg)](https://i.stack.imgur.com/WzAmNm.jpg) [Source: COSMOS - The SAO Encyclopedia of Astronomy](http://astronomy.swin.edu.au/cosmos/) ## Output: One of `Spring`, `Summer`, `Autumn`, or `Winter`, following these rules: * Is the position input `2` or `-2` (Arctic or Antarctic), always output `Winter`. * Is the position input `0` (Tropics), always output `Summer`. * Is the position input `1` (northern hemisphere), output one of the four seasons based on the month input: `Spring` (`m = [3,5]`); `Summer` (`m = [6,8]`); `Autumn` (`m = [9,11]`); `Winter` (`m = 12 or m = [1,2]`). * Is the position input `-1` (southern hemisphere), output one of the four seasons based on the month input: `Spring` (`m = [9,11]`); `Summer` (`m = 12 or m = [1,2]`); `Autumn` (`m = [3,5]`); `Winter` (`m = [6,8]`). ## Challenge rules: * Output any four distinct values of your choice indicating `Spring`, `Summer`, `Autumn`, or `Winter` (please state what you've used in your answer). **-15 bytes bonus** if you output `Spring`, `Summer`, `Autumn`, or `Winter` as text (case-insensitive, so can be fully lowercase or fully uppercase as well, instead of the used title-case). * Month input can be in any reasonable format. Can be either a 0-indexed or 1-indexed integer, Date-object, Month-String, etc. * Position input will always be one of these possible five inputs `-2`, `-1`, `0`, `1`, `2`. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters 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. * Also, please add an explanation if necessary. ## Test cases: ``` Position 1-indexed Month Output -2 8 (August) Winter -2 12 (December) Winter -1 3 (March) Autumn -1 5 (May) Autumn -1 8 (August) Winter -1 12 (December) Summer 0 1 (January) Summer 0 7 (July) Summer 1 1 (January) Winter 1 4 (April) Spring 1 7 (July) Summer 1 12 (December) Winter 2 2 (February) Winter 2 9 (September) Winter ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~33 27~~ 25 bytes ``` ->m,l{[6,m,0,m+6][l]/3%4} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5XJ6c62kwnV8dAJ1fbLDY6J1bfWNWk9r@GrpGenpGmXm5iQXVNRY2GoZ6eIYxbWVOgEB1doVMZq6OQFl2pUxEbW1v7HwA "Ruby – Try It Online") Return values are: 0 -> winter 1 -> spring 2 -> summer 3 -> autumn [Answer] # [Python 2](https://docs.python.org/2/), 29 bytes ``` lambda p,m:[0,m+6,6,m][p]/3%4 ``` [Try it online!](https://tio.run/##hc5BDoIwEIXhtZxiNqY0DrEdDCEkngRYYLTaxJaGsPH0FUvE2bn@58ub8Jofo6dozl18Du5yHSCga1qF7lBhha5vQ38s96cYJutnEAVBDd0sEMDkBWEts1/RtKZUNG1JbWZJihm1kRQYIU74DHGyrmRmnMCC9TAN/n7LNepSNtnu@5gWaFF8zPKYRiv/AH6fzuMb "Python 2 – Try It Online") A port of [G B's Ruby approach](https://codegolf.stackexchange.com/a/164757/76162), which turned out to be a few bytes shorter than my own: ### 32 bytes ``` lambda p,m:(p%2*(p+m/3+5)or p)%4 ``` [Try it online!](https://tio.run/##hc5BDsIgEIXhtT3FbBrATiNMNWmaeJNuMIqSCCWkG0@PtY3IzvU/X@aF1/yYPCVzHtNTu8tVQ0A38FDTnofGHbrmJKYIQdTHFKL1M7CWoIdxZghgeEvYi@pXFG1pLYpyktksSRZGZrKGglBJyjdUku1LZZaRFqyHqP39xhWqTgzV7jtMMbTIPmYZptCKP6C8X8/TGw "Python 2 – Try It Online") An anonymous function that returns the seasons as the numbers 0 to 3, where they represent Summer, Autumn, Winter and Spring in that order. As for printing the actual season names: ### 63 - 15 = 48 bytes ``` lambda p,m:"SAWSuuipmtnrmutiemenrnrg"[(p%2*(p+m/3+5)or p)%4::4] ``` [Try it online!](https://tio.run/##hc6xDoIwFIXhWZ7ihoS0lRJpwYQ0cfAZGBzUASNgE1uapgw@fUWI2M35v1/uMS/3GDT33eHin4263RswVIm4Pp7qcZRGOW3V6GSrWm217eMzNgnfYpOqXZHuyWDBkKQUorx6Y6V2gDIOFVwcogAdzjitSPQrjC9pLoyvKV/NlPLA5CuZQ0B4SMI3PCTLl6ibhkqQGmyj@xYzygoios13GENUUvQx0zBGJfkDwvv53L8B "Python 2 – Try It Online") There's the combined string if anyone wants it. [Answer] # [C (gcc)](https://gcc.gnu.org/), 78 75 (-15 bonus) = 60 bytes Using 1-based months. *Edit:* Rearranged mathematical operators and reduced. ``` f(m,a){puts("Summer\0Autumn\0Winter\0Spring"+7*(a*a&1?(++a+m/3)%4:2*!!a));} ``` [Try it online!](https://tio.run/##VYxLDoIwAET3nKJgNP2AApoYP8F4BhYuhEUtvya0EGjZEM5ey8q4e29mMiyoGTMbLlmrixLcR1Xwbt8kzl/U8o/NTAWFT9HcazVCL9VClEMWPrXSQmbhi0u1etoPXNYeOWNIMd1FD0gIJeJwRNvTNcauSxG6LcaugaBcwhXoUDOfNXQAGFueEJgdAHgF1yKJEbCkOr7q9I5y5P8szu2dsxhzMUH0BQ "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 26 - 15 = 11 bytes Uses the approach found by [G B](https://codegolf.stackexchange.com/a/164757/47066) ``` 6¹¾¹6+)sè3÷4%“–„Ž¹Ž€È±“#sè ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7NDOQ/sO7TTT1iw@vML48HYT1UcNcx41TH7UMO/o3kM7j@591LTmcMehjUBRZaCK//9NuHQNAQ "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##AVQAq/8wNWFiMWX/Migyxbh2MTJGTj5V/zZYwr5YNispecOoM8O3NCXigJzigJPigJ7FvcK5xb3igqzDiMKx4oCcI3PDqP9YeSLDvywgw78gLT4gw78iLP8) ]
[Question] [ Write a program that, when run in different languages, outputs a different byte permutation of the code in each language. The exact source code is counted as one permutation. Here "different language" can be different version(Py 2 and Py 3) or different standard flags. It's different output that forces different version. Proper quine rules apply for the program in each language. Your score is calculated as `(Language count)^6/(Code length in bytes)`, with a higher score being better. **Sample:** If your code is `AAB` and running in three different languages returns `ABA`, `AAB` and `AAB`, then its score is `2^6/3`(only one of the two `AAB` count). It's fine if `ABA` is meaningless. [Answer] # [Befunge-98](https://pythonhosted.org/PyFunge/), [><>](https://esolangs.org/wiki/Fish), [Gol><>](https://github.com/Sp3000/Golfish), [Fission](https://github.com/C0deH4cker/Fission), [Wumpus](https://github.com/m-ender/wumpus), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [Beeswax](https://github.com/m-lohmann/BeeswaxEsolang.jl) and [Alice](https://github.com/m-ender/alice) Score: 86/88 = 2978.909 ``` "65*4+059*$!#.39*0jp2+'Wk,@ ''5&.'\d&o@o&88#+\@ol?!,'.'0.6'!+Ox,++tttt=++%-$#}.6~.F4*`*R ``` [Try it in Befunge!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XMjPVMtE2MLXUUlFU1jO21DLIKjDSVg/P1nFQUFc3VdNTj0lRy3fIV7OwUNaOccjPsVfUUddTN9AzU1fU9q/Q0dYuAQJbbW1VXRXlWj2zOj03E60EraD//wE "Befunge-98 (PyFunge) – Try It Online") [Try it in ><>!](https://tio.run/##S8sszvj/X8nMVMtE28DUUktFUVnP2FLLIKvASFs9PFvHQUFd3VRNTz0mRS3fIV/NwkJZO8YhP8deUUddT91Az0xdUdu/QkdbuwQIbLW1VXVVlGv1zOr03Ey0ErSC/v8HAA "><> – Try It Online") [Try it in Gol><>!](https://tio.run/##S8/PScsszvj/X8nMVMtE28DUUktFUVnP2FLLIKvASFs9PFvHQUFd3VRNTz0mRS3fIV/NwkJZO8YhP8deUUddT91Az0xdUdu/QkdbuwQIbLW1VXVVlGv1zOr03Ey0ErSC/v8HAA "Gol><> – Try It Online") [Try it in Fission!](https://tio.run/##S8ssLs7Mz/v/X8nMVMtE28DUUktFUVnP2FLLIKvASFs9PFvHQUFd3VRNTz0mRS3fIV/NwkJZO8YhP8deUUddT91Az0xdUdu/QkdbuwQIbLW1VXVVlGv1zOr03Ey0ErSC/v8HAA "Fission – Try It Online") [Try it in Wumpus!](https://tio.run/##Ky/NLSgt/v9fycxUy0TbwNRSS0VRWc/YUssgq8BIWz08W8dBQV3dVE1PPSZFLd8hX83CQlk7xiE/x15RR11P3UDPTF1R279CR1u7BAhstbVVdVWUa/XM6vTcTLQStIL@/wcA "Wumpus – Try It Online") [Try it in Cardinal!](https://tio.run/##S04sSsnMS8z5/1/JzFTLRNvA1FJLRVFZz9hSyyCrwEhbPTxbx0FBXd1UTU89JkUt3yFfzcJCWTvGIT/HXlFHXU/dQM9MXVHbv0JHW7sECGy1tVV1VZRr9czq9NxMtBK0gv7/BwA "Cardinal – Try It Online") [Try it in Beeswax!](https://tio.run/##S0pNLS5PrPj/X8nMVMtE28DUUktFUVnP2FLLIKvASFs9PFvHQUFd3VRNTz0mRS3fIV/NwkJZO8YhP8deUUddT91Az0xdUdu/QkdbuwQIbLW1VXVVlGv1zOr03Ey0ErSC/v8HAA "Beeswax – Try It Online") [Try it in Alice!](https://tio.run/##S8zJTE79/1/JzFTLRNvA1FJLRVFZz9hSyyCrwEhbPTxbx0FBXd1UTU89JkUt3yFfzcJCWTvGIT/HXlFHXU/dQM9MXVHbv0JHW7sECGy1tVV1VZRr9czq9NxMtBK0gv7/BwA "Alice – Try It Online") [Verification!](https://tio.run/##fVLLbtswEDxHX7G2U1MSZdpIYsMOYNSnXAP00kNTtJRFyUxokuADig7tr7vUKwhgoDyQs7M75HJI3biTkveXCz9rZRwoGw3INjaKjqpgsG8xsa7gkhhGiziJooKVYLz8pY2qDD3HgsrK04olj9FNzd0JlGYyRq0eZYBqlAC1UD5CSWrDHYvbTHJVS/Lyv@WGOW9k6JLoTjQeixF0RyUfDUZUiGfvQvOCWxefqY4/9ZvBj6luSi8rBotFuNp@tw0gZx01zSBkO2NgqbRbltyeuono5ipZKdHlrTmOeCgbtZYrOa4tb3ze9Nran7W3w0JMfrX5kZpgOxUf4PPWr15wusy57FGvyBmzNX3v6AFPfybBkVnamqANly7rzUmyKOriWAQvBw72wbIQWuZGKjyGLCAEsQ0/gxX9a7SFQ0wTKJUBClzCqLlcppt1@oBX6116O5mR@126etV3GH1/yw6A0HpO0EsxVwc1325n@OWgxNdJhghakQ2a4Of3DGMXxh7jL4vb2R@y@UueHtLf6bd/ "Python 3 – Try It Online") Lots of 2D languages, all abusing wrapping string literals. The difference in outputs are thus: ><>, Gol><> and Befunge-98 all print the code backwards (except for the `"`), with the last three characters in different positions, `R*"`, `O"*` and `"R*` respectively. Beeswax also has the code backwards, but the last three characters are interspersed in the first section of the output. Alice is mostly backwards, except for all the escaped characters (`'`,`\` and `"`) moved to the front instead. Wumpus is the only actual quine, Fission puts the `"` at the end of the code instead of the beginning, and Cardinal puts the `"` between the `0` and the `5` near the start. [Proof of different permutations](https://tio.run/##tZTBbqMwEIbP5SmMSWPwuBZqACUHVE69VuKSQ4hUGpyU1osRkG16aF89xQ5IXWnVU/HNY898mvl/u37vnlW1OJ93qhAovrpqCCE4CmkAfriiM9vhixX1X@pbIOtXliBCwjknWTFXiZovlw5kiZJ3NiOc@DwiNjycGEDXrxjg@mbmfPDok98H9JGmfWnLehL7Y3XQLINK@4Pgnn9G/MOZ3VwDxDoXgJ0ewCYR9/vCzL6TKsnAWS4NtsgIn4eEoIS9rgnc1i8@XS24Y8/oKvQhoGGkUfuyfR5bSimejHNQckBpEsXplB21paoG0kQqYU16O/6pj@0o0oR@2OVNUVa5/KcnPAnqSYj2LT@NOtEg1So9/q5MZnq5LHeX14QxzohZPzu95/EL7RtMswzq/ySMLUv8Fc07itFmeFYMaSsyNHjSbLVlGLooytA4cIaGeWwtq27KqnNzKd2NFJXbis41hT0PxTHSoct2C5tWNZ0oXJlXh2N@EObCENNfiIf2qkHjKSorZDK3nnc@fwE) ## Explanations: ### Befunge-98: ``` " Wrapping string literal pushes all other characters + a space to the stack 65*4+ Push " to the stack 059*$!#.39*0j Push 1,27 to the stack p Pops the top three values of the stack (27,1,34) 2+ Adds 2 to the space to make " 'Wk,@ Prints the top 88 characters of the stack and terminates ``` ### ><> and Gol><>: To be honest, I didn't do much here. The only difference between the execution of these two languages is the `@` command, which rotates the top three values of the stack in different ways for each language. ``` " Wrapping string literal pushes all other characters to the stack 65*4+ Push 34 (") to the stack 059*$!#. Jump to cell 45,0 \@ Rotate the top three values of the stack ol?!,'.'0. Output the whole stack, ending in a divide by 0/stack underflow error ``` ### Fission: ``` "............R Spawn a pointer going right " Switch to printing mode and print every other character " Switch off printing mode 6 Teleport to other 6 "........6'!+O Print the " ``` ### Wumpus: ``` " Bouncing string literal 65*4+ Push a (") 059*$!#. Push 0 and jump to cell 0,45 \ Reflect off mirror + Add 0 to top of stack @o&88# Print the top 88 characters of the stack ``` ### Cardinal: ``` % Spawn two pointer going left/right (up/down despawn immediately) -$ Right pointer jumps to cell -1,0 x,++tttt=++ Left pointer prints " " While right pointer switches to print mode and prints the code ``` ### Beeswax: ``` "................*`* Spawn pointers going in every direction Every other * also spawns pointers, but they do nothing ` Turn on print mode for two of the pointers going in different directions This prints everything but the ` #}.6~.F4* Print a ` ``` ### Alice: ``` " Wrapping string literal pushes all other characters to the stack Except 's and mirrors 65*4+ Push " to the stack 059*$!#. Does nothing 39*0j Jumps to cell 39,0 ''5&. Push ' and duplicate it 5 times '\ Push \ d&o@ Print the whole stack ``` [Answer] ## [Perl 5](https://www.perl.org/), [Ruby](https://www.ruby-lang.org/), JavaScript (Chrome), [PHP](https://php.net/), [Python 2](https://docs.python.org/2/), [Python 3](https://docs.python.org/3/), 1206 bytes, score 66/1206 = 38.6865671641791 ``` q=1//2;s=+0;s|0;"/.__id__;#";_="""q=1//2;s=+0;s|0;"/.__id__;#";_={0}{1}{0};R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q={0}{2}{0};print(_.format(Q,_,q[0:-12]+R,"%"))""";R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q="""|;#<?ob_end_clean(); eval($_='"$t"?0?[$q=37 .chr+113 .chr+38 .chr,$p=(96 .chr+39 .chr)*4,$n=10 .chr,$s=39 .chr*12,$S=34 .chr*3]:eval("printf=console.log;c=String.fromCharCode;$q=c(96);$p=c(37,113,38,39).repeat(4);$n=c(10);$s=c(39).repeat(12);$S=c(34,34,34)"):[]?[$q=q(!g)^PA,$p=HARHARHARHAR^od2od2od2od2,$n=R^X,$s=bbbbbbbbbbbb^EEEEEEEEEEEE,$S=hhh^JJJ]:[$q=O^h,$p=str_repeat(RHa3^w9GS,4),$n=R^X,$s=str_repeat(b^E,12),$S=HHH^jjj];//#');printf($x='q=1//2;s=+0;s|0;"/.__id__;#";_=%7$sq=1//2;s=+0;s|0;"/.__id__;#";_={0}{1}{0};R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q={0}{2}{0};print(_.format(Q,_,q[0:-12]+R,"%8$s"))%7$s;R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q=%7$s|;#<?ob_end_clean();%5$seval($_=%3$s%1$s%3$s);printf($x=%3$s%2$s%3$s,$_,$x,$q,$p,$n,$s,$S,"%8$s",![]||([]+[])?$n:"");//#%4$s%6$s%7$s;print(_.format(Q,_,q[0:-12]+R,"%8$s"))%9$s',$_,$x,$q,$p,$n,$s,$S,"%",![]||([]+[])?$n:"");//#`q&%`q&%`q&%`q&%''''''''''''""";print(_.format(Q,_,q[0:-12]+R,"%")) ``` [Validate Perl, Ruby, PHP, Python 2 and Python 3 online!](https://tio.run/##7VRbU@JIFH7nV/S0HUlrTAhhRqGNljW1NZQPsw5UbW0VQgwhkDgxCekwSgm/3T2dgBNu6@iTD6Zyge9cvq9Pnz59m3tPT7GbBEj1w3iSqqkfoTMUR8F0FESpGgeslEz60x3mpM9KeyiMBu4Oh1vOSq7jRQgTHa8bYi9GRwPEvShJrSh2Qyu1R2YUCjCapJDO6k@GQzfxwwzeIdGLIdU09XZ7TJcOxk4Pg5VK9w46cgoeuXS2wFdqsgaJOqxBYoHrgULpOjbdAgkxOfWieO1okjhuA7OSY6dbFN4NPqPTVYUr8Veww8voLV47whH@HqXIRuOJH7oKsgcDLl4@EId2gMrjMsdrRC3olQ0iUZ2tREvDS0TSFqZL@5fddhI/TpH8HRoQCk43mJftt8EsDIvGLWBolkMzBO7rJWxebVZQbOj2EmZN@cr@LkaDhteGb1Wdn4vqpvTpLuXPh6WICTk5@D8sxhYWYyeN8ftQFtFnJmONCvZrD2Wj6qgSuqhMLPM28kOMFQ4F0lRtxLgmq/RaP9Bg2jSwGrjhKPVksk9VfB1ibeSyGIqVYnLR@vbPdUis6xDwcnEoPEs5AMoi28MG273nB658ekYfifdIrLlqZnnnwyiRf7pTLnn0MeMb4twB@RxJ/Jcd@AOgVfwQPcjkAYWuvJaa0rn74KfbhcVB8QCttO9KAxV3b7XsT09jU9e0KuPmYYXxWYVhTbUsf2BZbA8zy8QYv@DxWJk/6nN4s5bpeIksG3XFqNGOrlXPKl16oFfZj3WDaQqLwcZZdDWLzuojWyrU7M5O5R@KpYw7lcaRXu0ethQsYUpBzJtIIG7G9k7Po77lhgPLCVw7lCm0E2yADM1TxiTF55XzDhmbxjFSIdGhrhv5D@Mk@yokNuX6lwVWz770oKaQ0NQrCw9uLgygRyFt06jl/4xuI6PCeQ@YThTyKHDVIBoxx2yn4tiqwyS6@@rZyVcYOwyEOMBGGbA6snGsgBzFOFGMOlUTN3ahQDUwhmDUK/CDC6/fNr0KWFtgNSW7KaaNTjdb4Fj@NKK9qwuxoOZF6/nuRYPq8y2W1er9K5bUL1y9vwqXWKHneb3Ly8tuQ2T@u@eJpDxNrIWOVtM2evf1b22lRgspCx6QUgG1Ilez2ezd3t52mabtlWneD0M4FWb5hQ6Ujgl/J016Qjj0qRD0JiIRuK1Tpc@EL5tVMgiXdHjgW6xShldzXCGWQh4UMob9gLorAmkv5CmfOt3ZTO50Dztdek7CBsZUlFyqQewXeIT4P1xnnfDyLq6dRDfjfan4lAuXOOF/MAhKH2MLOuHmY2y9s7F1UzyQNx9j6/2OrZtXjy1pvF8uPm8YW/8B "Bash – Try It Online") **Note**: running the above program in the Inspector console in Chrome (which appears to support positional arguments to `console.log`) returns the correct program. ### Explanation This turned out a lot longer than I'd hoped and I made my life a little harder too, so I'm likely to keep tinkering with it. I'd like to add in more languages too, but I need to find something that doesn't mind a `$` sigil... This is pretty much a standard quine format where the calculation of the quote to use is a little different for each language: in Ruby `%q&` is used, PHP uses `'`, JavaScript (Node.js) makes use of ``` and Perl 5 utilises `q(`...`)`. Because only the quotes change, the rest of the program is still executable and valid syntax in each language. Python 2 and 3 are wrapped around the previous program using `"""` for Python 2 and `'''` for Python 3. The resultant Perl and Ruby programs aren't standard quines, additional `q`/`%q`s are added each iteration, but the first program returns correctly. The results are: * Perl 5: `eval($_=q&`...`q&);printf($x=q&`...`q&,`...`);//#'%`'%`'%`'%`''''''''''''"""` ... * Ruby: `eval($_=%q&`...`%q&);printf($x=%q&`...`%q&,`...`);//#`'`'`'`'''''''''''''"""` ... * JavaScript (Chrome): `eval($_=`` ...``);printf($x=``... ``,`...`);//#%q&'%q&'%q&'%q&'''''''''''''"""` ... * PHP: `eval($_='`...`');printf($x='`...`',`...`);//#`q&%`q&%`q&%`q&%''''''''''''"""` ... * Python 2: ...`_="""`...`""";`...`q="""`...`''''''''''''""";print(_.format(Q,_,q[0:-12]+R,"%"))` * Python 3: ...`_='''`...`''';`...`q='''`...`""""""""""""''';print(_.format(Q,_,q[0:-12]+R,"%"))` I've re-worked this a lot, I hope I haven't missed anything key here. I still have quite a way to go to be anywhere near [Jo King's score](https://codegolf.stackexchange.com/a/162022/9365)... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), and [M](https://github.com/DennisMitchell/m), 26/14 = 4.57 ``` 1Ɗṙ@“1Ɗṙ@ȮṾ”ȮṾ ``` [Try it in Jelly!](https://tio.run/##y0rNyan8/9/wWNfDnTMdHjXMgbJOrHu4c9@jhrlg@v9/AA) [Try it in M!](https://tio.run/##y/3/3/BY18OdMx0eNcyBsk6se7hz36OGuWD6/38A "M – Try It Online") `Ɗṙ@ȮṾ1“Ɗṙ@ȮṾ1”` in Jelly `1Ɗṙ@ȮṾ“1Ɗṙ@ȮṾ”` in M [Answer] # [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), 26/61 =1.05 ``` s='s=%r;print(s%%s[::(1/2>0)*2-1])';print(s%s[::(1/2>0)*2-1]) ``` [Try it in Python 2!](https://tio.run/##K6gsycjPM/r/v9hWvdhWtci6oCgzr0SjWFW1ONrKSsNQ38jOQFPLSNcwVlMdLoch9f8/AA "Python 2 – Try It Online") [Try it in Python 3!](https://tio.run/##K6gsycjPM/7/v9hWvdhWtci6oCgzr0SjWFW1ONrKSsNQ38jOQFPLSNcwVlMdLoch9f8/AA "Python 3 – Try It Online") Saved 12 bytes thanks to Jo King. **Python 2 prints** ``` s=')]1-2*)0>2/1(::[s%%s(tnirp;r%=s';print(s%s[::(1/2>0)*2-1]) ``` **Python 3 prints** ``` s='s=%r;print(s%%s[::(1/2>0)*2-1])';print(s%s[::(1/2>0)*2-1]) ``` This uses the fact that `1/2` is `.5` in Python 3 and `0` in Python 2. [Answer] # Bash/GolfScript, 72 bytes, score 26/72 = 8/9 (~0.888...) ``` .~0 () { declare "-f" @* ".~0" " () "+@n.; echo '.~0;' } .~0; ``` Contains a single trailing space on the first two lines. [Try it online in Bash.](https://tio.run/##S0oszvj/X6/OQEFDU4GrWoFLAQhSUpNzEotSFZR005QUHLQUlIDySgpKQCVcCkraDnl61mBlqckZ@QrqQDlrda5aLhD9/z8A) [Try it online in GolfScript.](https://tio.run/##S8/PSStOLsosKPn/X6/OQEFDU4GrWoFLAQhSUpNzEotSFZR005QUHLQUlIDySgpKQCVcCkraDnl61mBlqckZ@QrqQDlrda5aLhD9/z8A) Simply modification of [*@jimmy23013*'s answer for the "*Write a Polyquine*" challenge](https://codegolf.stackexchange.com/a/37857/52210). The modification that was done was removing the trailing space after the third line, and changing `\n"+@n.;` to `\n "+@n;`. Bash will print lines 1 and 2 like this: ``` .~0 () <- Trailing space { <- Trailing space ``` And GolfScript will print lines 1 and 2 like this: ``` .~0 () <- No trailing space { <- Both leading and trailing space ``` Here the base program, Bash output, and GolfScript outputs respectively with the new-lines replaced with `\n`: ``` .~0 () \n{ \n declare "-f" @* ".~0" " ()\n "+@n.;\n echo '.~0;'\n}\n.~0; .~0 () \n{ \n declare "-f" @* ".~0" " ()\n "+@n.;\n echo '.~0;'\n}\n.~0; .~0 ()\n { \n declare "-f" @* ".~0" " ()\n "+@n.;\n echo '.~0;'\n}\n.~0; ^^^ Note the difference here ``` ]
[Question] [ # Introduction Given five points in the plane, your task is to compute the area of the ellipse passing through these points. You can assume that exactly one non-degenerate ellipse can be constructed with the given input values. # Rules Input is `10` integers in any convenient form, corresponding to the `x` and `y` coordinates of the points. For example, you could take input as a list of `10` integers `[x1, y1, x2, y2, ..., x5, y5]`, or as `[[x1, y1], [x2, y2], ..., [x5, y5]]`, etc.. You may also handle decimal numbers, but only integers are required. Output is a representation of the area of the ellipse. This may be some symbolic expression, or a decimal value with at least `8` digits of precision. This is code-golf, so the shortest answer in bytes wins. # Example Input and Output Input: > > [-2, 3, 2, 5, 5, 3, 4, 0, 1, -3] > > > Output: > > 62.15326783788685 > > > A depiction of the ellipse passing through these points: ![The ellipse for this example](https://i.stack.imgur.com/xJOpP.png) More examples: ``` f(60, -92, -31, -10, 78, -19, -27, -35, 91, -37) = 9882.59540465108 f(-9, -4, 7, 7, 10, 1, -7, -10, 0, 7) = 269.5966648188643 f(-3, 2, 0, -5, 4, 0, -4, 1, -1, 2) = 98.54937293879908 ``` [Answer] # Mathematica, ~~87~~ ~~80~~ 78 bytes ``` Area@ImplicitRegion[+##Sign@#&@@Det[{1,##,1##,#^2,#2^2}&@@@{x|y,##}]>0,{x,y}]& ``` Takes 5 inputs: `[{x1, y1}, ... , {x5, y5}]`. Returns an exact/symbolic value. ## How? Let `f(x, y)` denote the vector `(1, x, y, xy, x^2, y^2)` for some `x, y`. Then, the determinant of the matrix with row vectors `[f(x, y), f(x1, y1), f(x2, y2), ..., f(x5, y5)]` is zero iff `(x, y)` is a point on the ellipse we are looking for. i.e. the determinant gives the expression for the ellipse. Since the sign of the expression might be inverted, we take the constant term and multiply the entire expression by the sign of the constant. That way, we can set the expression greater than 0 to find the area. [Answer] # [MATLAB](https://matlab.mathworks.com/), ~~130 124~~ 114 bytes The input is takean as two column vectors, one for the x- and one for the y-coordinates. This method uses a least sequares regression, which provides the exact ellipse if all points are exactly on an ellipse, and then applies [the formula provided here](https://math.stackexchange.com/questions/1385426/area-of-the-ellipse-ax22bxycy22dx2eyf-0) (thanks @orlp) to calculate the area. ``` function A=f(x,y);p=null([x.^2,2*x.*y,y.^2,2*x,2*y,0*x+1]);A=pi*det(p([1,2,4;2,3,5;4:6]))/abs(p(1)*p(3)-p(2)^2)^1.5 ``` By appending following lines you can even plot the curve: ``` X=x;Y=y; [x,y] = meshgrid(linspace(-7,7,50)); W = [x(:).^2,2*x(:).*y(:),y(:).^2,2*x(:),2*y(:),0*x(:)+1]; Z=x;Z(:) = W*p; clf;plot(X,Y,'o');hold on;contour(x,y,Z,[0,0]); ``` ![](https://i.stack.imgur.com/XnVfB.png) [Try it online!](https://tio.run/##XZA/b4MwEMV3PoUXq0DPFP@3ixgydurSDRGJJiBFigxqoIVPTw/USFEte7j37vd8uv40Nt/tSrspnMZLH8ih7OIZlqQglEyh67/GKTRje13IT0tOTQj9SM5tdwktuTM3gtzH23s0k5JUTIAADQp4/VREyyZJrCXkwCRK1IiMaymMdRHdCbM5HKwDJiz4naM7yLwAxtHmHls0Posmod45kWmvVa6M5vk9iHmwsLVbyB9C1KbuORtNURPGI26MUY47Z5S8B2xTKkCCPUyBM2jUOYg/3LtMKy@t8NJZ73O30v8nGsowXa9xNWdpNYNIlxqW7Ii7SfcK8nR@5nVSHMrhkp7bMR7iCn8AVQjclS7Uq6mT5KX5vKHDk3SIZcKGWCRHvDzT6/oL "Octave – Try It Online") [Answer] ## Mathematica 84 Bytes I found this to be an interesting problem. Every ellipse is an affine transformation of the unit circle which can be parameterized as {x,y}={Cos(t),Sin(t)}, so the points on the circle can be mapped to the ellipse by {xE,yE}=A{x,y}+B where A is a constant matrix and B a vector. Plugging in the points yields 10 scalar equations and 11 scalar unknowns, but we can decide that the parameterization starts at t=0, so the system is solvable. The absolute value of the determinant of the matrix A is the ratio of the area of the ellipse to the unit circle so we multiply by Pi. Taking Max gets rid of the negative solution. ``` Max[π(a d-b c)/.Solve@MapThread[#2=={e,f}+{a,b}Cos@#+{c,d}Sin@#&,{{0,u,v,w,x},#}]]& ``` Usage: ``` %@{{-2, 3}, {2, 5}, {5, 3}, {4, 0}, {1, -3}} ``` Yields: ``` (1001 π)/(16 Sqrt[10]) ``` [Answer] # Mathematica, 144 bytes ``` x_±y_:=x^2a+b*x*y+y^2c+d*x+e*y+f;n=∞;Integrate[UnitStep[x±y/.FindInstance[And@@(#±#2==0&@@@#),{a,b,c,d,e,f},Reals,2][[1]]],{x,-n,n},{y,-n,n}]& ``` works for all test cases **Input example**: `[{{-3, 2}, {0, -5}, {4, 0}, {-4, 1}, {-1, 2}}]` **Results** > > 9882.59540465108163146329 > > 269.596664818864334050934 > > 98.5493729387989852754258 > > > *-10 bytes from JungHwan Min* ± is 1-byte in default windows encoding [CP-1252] [Answer] # [Desmos](https://www.desmos.com/calculator), 101 bytes ``` u v f(a,b,c,h,k,x,y)=(((x-h)cosc+(y-k)sinc)/a)^2+(((x-h)sinc-(y-k)cosc)/b)^2 f(m,n,o,p,q,u,v)~1 mn\pi ``` Online **Desmos** doesn't like multiline pastes, so you have to enter it in one line at a time, or [Try It Online!](https://www.desmos.com/calculator/oed36zylwm) Input is taken with the two lists `u` and `v`. The output is shown on the last line. ### Explanation: * The first two lines name the input variables. * The third line defines the equation for any ellipse, with radii `a` and `b`, rotation angle `c`, and offset `(h,k)`. + Prettified, it looks like this: [![enter image description here](https://i.stack.imgur.com/91v7T.png)](https://i.stack.imgur.com/91v7T.png) * The fourth line calculates a regression of `f` over the lists `u` and `v`, finding radii `m` and `n`, rotation angle `o`, and offset `(p,q)`. * The last line calculates the area of the ellipse with the formula `A = pi*r1*r2` You can also [Try It Online](https://www.desmos.com/calculator/p5ztt4k1rp) (different link) for a slightly expanded, interactive visual version. You can move around the five points and view the ellipse and area in real time: [![enter image description here](https://i.stack.imgur.com/EXonW.png)](https://www.desmos.com/calculator/p5ztt4k1rp) Alternatively, here is a slightly longer solution using [this formula](https://math.stackexchange.com/questions/1385426/area-of-the-ellipse-ax22bxycy22dx2eyf-0) (same as [@flawr's answer](https://codegolf.stackexchange.com/a/144340/67881)): ## Desmos, 106 bytes ``` u v f(A,B,C,D,E,F,x,y)=Axx+2Bxy+Cyy+2Dx+2Ey+F f(G,H,I,J,K,L,u,v)~0 \pi(GIL+2HJK-JJK-GKK-HHL)/(GI-HH)^{1.5} ``` [Try It Online!](https://www.desmos.com/calculator/6txmjlmf0m) ]
[Question] [ The N-bonacci sequence, originally invented by @DJMcMayhem in [this question](https://codegolf.stackexchange.com/q/70476/61613), is a sequence generated by starting with the integers 0 and 1, and then adding the previous N numbers to generate the next number. The special N-bonacci sequence is an N-bonacci sequence beginning with a pair of numbers other than 0 and 1, which will be named X and Y. If N is greater than the number of terms already in the sequence, simply add all available terms. So for example the normal fibonacci sequence has an N of 2 (takes the previous two items), and an X and Y of 0 and 1, or 1 and 1, depending on who you ask. ## Your Task: You are to write a program or function that checks whether an inputted integer (A) is part of the special N-bonacci sequence generated by the next three integers (using the second input as N, and the third and fourth as X and Y). Ensure that you handle the special case of N=1. ## Input: Four non-negative integers, A, N, X, and Y. ## Output: A truthy/falsy value that indicates whether A is part of the N-bonacci sequence generated by the N, X, and Y inputs. ## Test Cases: ``` Input: Output: 13,2,0,1->truthy 12,3,1,4->falsy 4,5,0,1-->truthy 8,1,8,9-->truthy 9,1,8,9-->truthy 12,5,0,1->falsy [0,1]>[0,1,1]>[0,1,1,2]>[0,1,1,2,4]>[0,1,1,2,4,8]>[0,1,1,2,4,8,16]>etc. ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḣ⁴S;µṀ<⁵µ¿⁵e ``` A full program taking `[X,Y]`, `N`, `A`. **[Try it online!](https://tio.run/##y0rNyan8///hjsWPGrcEWx/a@nBng82jxq2Hth7aD6RS////H22oYxL73/i/oREA "Jelly – Try It Online")** ### How? ``` ḣ⁴S;µṀ<⁵µ¿⁵e - Main link (monadic): [X,Y] µ µ¿ - while: Ṁ - maximum value of the list ⁵ - 5th command line argument (3rd input) = A < - less than? - ...do: ⁴ - 4th command line argument (2nd input) = N ḣ - head (get the first N (or less) items from the list) S - sum ; - concatenate (add the result to the front of the list) ⁵ - 5th command line argument (3rd input) = A e - exists in the resulting list? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` [DR²£O©‚˜³®>‹#]³QZ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2iXo0KZDi/0PrXzUMOv0nEObD62ze9SwUzn20ObAKKC0oY5hLJcRl@XXvHzd5MTkjFQA "05AB1E – Try It Online") --- Uses: `[X,Y], N, A` --- I feel like some unintended functionality made that harder than it needed to be. There's no greater-than-or-equal-to, never noticed that before. And `#³` didn't work, and required a `]`, for +1 bytes `#]³`. [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ 56 bytes ``` a,n,l=input() while l[0]<a:l=[sum(l[:n])]+l print a in l ``` [Try it online!](https://tio.run/##TYtBCsMgEADvvkI8Kd1DNOlF6ksWD1KECNutVEPb19sEWuhxmJn67uud3WhBKTUSMFAoXLeujXiuhbIknOIleQrYtpsm9BxNPJGoj8JdJllY0tjnb259fuWrbmagncEBWphiFGgdzIAL2AMWOP@LH3wA "Python 2 – Try It Online") Takes input as `A,N,[X,Y]` [Answer] # [Perl 6](https://perl6.org), 47 bytes ``` ->\A,\N,\X,\Y{A∈(X,Y,{[+] @_.tail(N)}...*>A)} ``` [test it](https://tio.run/##TY9NboNADIX3cwovqjITzKQkaRaNIHCBrLpIVKqKMpMUiZ8RDFVRSta5S2/Ro@QiFAJqu7Hs58/PtpJFsmyrUsL7kkcrktZwG@VCgtNabuBjsMFgi8Hu6F/OZ7rFHR6fzGfwXrgO44RuWMM5n7g@a9pu1NOy1OBAEmeypIwfCqnoesJ4GqqHIwEwv794lKevdBoIc8oQ1l2ZdVZZSQ1dVPqtNhhpiBCD14r0pz1eM5WEGZijvM@LcZvlAgUvzlSlEW7kh5KRlgIY9Pvi0hJSqqSG/in6OXDsH4jjLD/EndkJDHDcLpz@CNK09hxneIe25Q43EnuGc7RxYbn7MClrssD7a/8X6IlBGogf "Perl 6 – Try It Online") ## Expanded: ``` -> \A, \N, \X, \Y { A # is 「A」 ∈ # an element of ( # this Sequence X, Y, # seed values of sequence { # generate the rest of the Seq using this code block [+] # reduce by addition @_ # of all previously generated values .tail(N) # only use the last 「N」 of them } ... # keep generating values until * > A # it is greater than 「A」 ) } ``` [Answer] # Python 2, 50 bytes ``` a,n,l=input() while[a]>l:l=[sum(l[:n])]+l a in l>x ``` Takes input as `A,N,[Y,X]`. Outputs via exit code. [Try it online!](https://tio.run/##RcvRCoMgFIDhe5/i0JWyc5HVbhz1IiJDwi3hzMSM6uldg2B3Px/88cjTHJqy9FVVFYsBqfchrpkLtk2enLZmIEW9XtYPJ62CEeZGzIIPQMNezo295gTPHyQb3o53QjGAnA4FbncjX8QDYvIhQ32620cXs7pEFtlig1pibZhssEXdoTSsw/sfr/wC "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~69~~ 60 bytes ``` function(a,n,l){while(l<a)l=c(sum(l[1:n],na.rm=T),l) a%in%l} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdPJ0ezujwjMydVI8cmUTPHNlmjuDRXIyfa0CovVicvUa8o1zZEE6iIK1E1M081p/Z/moahsY6RTrKGgY6hpuZ/AA "R – Try It Online") Returns an anonymous function, taking `a,n` and a vector `l=c(y,x)`. Constructs the N-bonacci sequence backwards (i.e., smaller index is further in the sequence), since `while(l<a)` only checks the first element of `l`. [Answer] # Common Lisp, 164 bytes ``` (defun f(a n x y &aux(l(list y x)))(if(= n 1)(or(= a x)(= a y))(loop(if(<= a(car l))(return(member a l))(setf l(cons(reduce'+ l)(if(<(length l)n)l(butlast l)))))))) ``` This function returns `NIL` for false, non-NIL for true (according to the definition of *generalized boolean* of Common Lisp). ``` (defun f(a n x y &aux (l (list y x))) ; initialize a list l for the N values (if (= n 1) ; special case for N = 1 (or (= a x) (= a y)) ; true only if A = X or A = Y (loop (if (<= a (car l)) ; when the last number generated is greater than A (return (member a l)) ; return true if A is in the list (setf l (cons (reduce '+ l) ; otherwise compute the sum of l (if (< (length l) n) ; and push it to l (truncating the list at l ; end if it has already size = N) (butlast l)))))))) ``` [Answer] # k, 29 bytes ``` {x=*(*x>){(x=#y)_y,+/y}[y]/z} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qusJWS0Orwk6zWqPCVrlSM75SR1u/sja6Mla/qvZ/mp66hoahsbWRtYGCoaa1hqGRtbG1oYIJkGlibQoVtABKGyoYaGr@BwA "K (oK) – Try It Online") `1` is truthy, `0` is falsey. Input is `[A;N;X,Y]`. [Answer] # PHP>=7.1, 103 Bytes ``` for([,$n,$d,$s,$e]=$argv,$f=[$s,$e];$x<$n;)$x=$f[]=array_sum(array_slice($f,-$d));echo+in_array($n,$f); ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/dff03f5bcca97ba038cdc02b31a99cd64a345a32) [Answer] # Mathematica, 94 bytes ``` (s={#3,#4};t=1;While[t<#2-1,s~AppendTo~Tr@s;t++];!LinearRecurrence[1~Table~#2,s,#^2]~FreeQ~#)& ``` input format > > [A,N,X,Y] > > > ]
[Question] [ # Challenge Given a valid `goo.gl` shortened link, output the original URL. # Example `goo.gl/qIwi3N` would give something like `https://codegolf.stackexchange.com/`. For input, you can choose to have the `https?://` at the beginning, you can choose to have `www.` before the `goo.gl`, and you can also choose to get rid of the `goo.gl` if you only want the end of the URL. A slash at the end is optional for input and output. So, your input will end up matching the regex `(https?://)?(www\.)?(goo\.gl/)?[A-Za-z0-9]+/?`. For the output, you can choose whether or not to output `https?://`, whether or not to output `www.`, and whether or not to output a trailing slash. However, **you must be consistent with your I/O formatting**. I will say that you do not have to be consistent with `https` vs. `http` for output (but you must be consistent for input), as long as you are consistent with whether or not you include the whole `https?://` part. # Test Cases These are written with no `https://`, no `www.`, no trailing slash in the input; yes `https://`, no `www.`, and yes trailing slash in the output. ``` input -> output goo.gl/HaE8Au -> https://codegolf.stackexchange.com/ goo.gl/IfZMwe -> https://stackoverflow.com/ goo.gl/JUdmxL -> https://chat.stackexchange.com/rooms/240/the-nineteenth-byte ``` # Assumptions * You may assume that the shortened link will not point to another shortened link and that the destination site will return a status code of `2xx` or `4xx` (no redirections). You can go here and enter a URL to apply the inverse operation of this: <https://goo.gl/> [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` lg'"/5= ``` ### Test run ``` $ alias cjam alias cjam='java -jar ~/.local/share/cjam-0.6.5.jar' $ cjam unshorten.cjam <<< goo.gl/HaE8Au; echo https://codegolf.stackexchange.com/ $ cjam unshorten.cjam <<< goo.gl/IfZMwe; echo https://stackoverflow.com/ $ cjam unshorten.cjam <<< goo.gl/JUdmxL; echo https://chat.stackexchange.com/rooms/240/the-nineteenth-byte ``` ### How it works `lg` reads a line from STDIN and makes a GET request to that URL. The shortened URL issues a 301 redirect, which CJam doesn't follow. For the first test case, this pushes ``` <HTML> <HEAD> <TITLE>Moved Permanently</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Moved Permanently</H1> The document has moved <A HREF="https://codegolf.stackexchange.com/">here</A>. </BODY> </HTML> ``` on the stack. Finally, `'"/` splits at double quotes, and `5=` gets the sixth chunk. Output is implicit. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~28~~ 24 bytes ``` curl -I $1|grep -oehtt.* ``` The output ends with a Windows-style newline, which I assume is acceptable. ### Test run ``` $ bash unshorten.sh 2>&- goo.gl/HaE8Au https://codegolf.stackexchange.com/ $ bash unshorten.sh 2>&- goo.gl/IfZMwe https://stackoverflow.com/ $ bash unshorten.sh 2>&- goo.gl/JUdmxL https://chat.stackexchange.com/rooms/240/the-nineteenth-byte ``` ### How it works `curl -I` sends a HEAD request, so it fetches only the HTTP headers of the specified URL. For the first test case, it prints ``` HTTP/1.1 301 Moved Permanently Content-Type: text/html; charset=UTF-8 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: Mon, 01 Jan 1990 00:00:00 GMT Date: Sat, 13 May 2017 05:51:48 GMT Location: https://codegolf.stackexchange.com/ X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block Server: GSE Transfer-Encoding: chunked Accept-Ranges: none Vary: Accept-Encoding ``` or similar. The output is piped to `grep -oehtt.*`, which displays only parts that match the specified regex, i.e., the string **htt** followed by any amount of characters up to the end of the line. [Answer] # Python 2 + requests, 44 bytes ``` from requests import* print get(input()).url ``` `requests.get(URL)` issues a GET request to the specified URL. The response object's `url` field contains the final URL, after any redirects. A protocol (e.g. `http://`) is required for the input, and the input is expected to be in quotes. [Answer] # PHP, 36 Bytes Input with `https://` ``` <?=substr(get_headers($argn)[7],10); ``` [get\_headers](http://php.net/manual/en/function.get-headers.php) 25 Bytes if `Location:` at the beginning must not removed ``` <?=get_headers($argn)[7]; ``` if Google changes the HTTP Header here is a safer version ``` preg_match("#Location: \K.*#",join("\n",get_headers($argn)),$t);echo$t[0]; ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes Has no dependencies and is currently shorter than the other Python answer. *shrug* Input must match `https?://goo\.gl/.*?/?` ``` lambda s:urlopen(s).url from urllib import* ``` [Answer] # NodeJS, 60 bytes ``` u=>require("http").get(u,r=>console.log(r.headers.location)) ``` Input is in the format `http://goo.gl/<id>`. ]
[Question] [ [K-means](https://en.wikipedia.org/wiki/K-means_clustering) is a standard unsupervised clustering algorithm, which, given a set of "points" and a number of clusters K, will assign each "point" to one of K clusters. ### Pseudo-Code of K-means Note that there are many variants of K-means. You have to implement the algorithm I am describing below. You may have some variation on the algorithm or use built-ins as long as you would get the same result as this algorithm given the same initial points. In this challenge, all inputs will be points on the 2D plane (each point is represented by its coordinates in x and y). ``` Inputs: K, the number of clusters P, the set of points Choose K points of P uniformly at random Each chosen point is the initial centroid of its cluster Loop: For each point in P: Assign to the cluster whose centroid is the nearest (Euclidean distance) In case of a tie, any of the tied cluster can be chosen Recompute the centroid of each cluster: Its x coordinate is the average of all x's of the points in the cluster Its y coordinate is the average of all y's of the points in the cluster Until the clusters don't change from one iteration to the next Output: the set of clusters ``` ### Inputs and Outputs * You may take K and P through `STDIN`, or as a function argument, etc. * P and the points in P can be represented using any structure that is natural for set/lists in your language of choice. * K is a strictly positive integer. * You may assume that inputs are valid. * There will always be at least K points in P. * You may output the clusters to `STDOUT`, return them from a function, etc. * The ordering of the clusters and the ordering inside the clusters is unimportant. -You can either return groups of points to represent clusters, or each point labeled with an identifier for the cluster (e.g. an integer). ### Test cases Since the resulting clusters depend on which points were initially chosen, you may not all get the same results (or the same result each time you run your code). Therefore, only take the output as an example output. ``` Input: K = 1 P = [[1,2.5]] Output: [[[1,2.5]]] Input: K = 3 P = [[4,8], [15,16], [23,42], [-13.37,-12.1], [666,-666]] Output: [[[666,-666]],[[-13.37,-12.1],[4,8]],[[15,16],[23,42]]] Input: K = 2 P = [[1,1], [1,1], [1,1]] Output: [[[1,1]],[[1,1],[1,1]]] ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # C++, ~~479~~ 474 bytes Only ~20x as much as Matlab! **Golfed** ``` #define V vector<P> #define f float struct P{f x,y,i=0;f d(P&p){return(p.x-x)*(p.x-x)+(p.y-y)*(p.y-y);}f n(P&p){return i?x/=i,y/=i,d(p):x=p.x,y=p.y,0;}f a(P&p){x+=p.x,y+=p.y,i++;}};P z;int l(P a,P b){return a.d(z)<b.d(z);}f m(f k,V&p){f s=p.size(),i,j=0,t=1;V c(k),n=c,d;for(random_shuffle(p.begin(),p.end());j<k;c[j].i=j++)c[j]=p[j];for(;t;c=n,n=V(k)){for(i=0;i<s;i++)d=c,z=p[i],sort(d.begin(),d.end(),l),j=d[0].i,p[i].i=j,n[j].a(p[i]);for(j=t=0;j<k;j++)t+=n[j].n(c[j]);}} ``` The input/output to the algorithm is a set of points (`struct P`) with `x` and `y`; and the output is the same set, with their `i`'s set to indicate the index of the output cluster that the point ends in. That extra `i` is also used to identify the clusters. In the main loop, the closest centroid to each point is found by sorting a copy of the current centroids by proximity to that point. This handles degenerate cases (empty clusters) by keeping the corresponding centroids' previous position (see definition of `P::n`, which also returns distance-to-previous-centroid). A few chars could be saved by assuming that these will not crop up. **Ungolfed, with main** ``` #include <cstdio> #include <ctime> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; #define V vector<P> #define f float struct P{ f x,y,i=0; f d(P&p){return(p.x-x)*(p.x-x)+(p.y-y)*(p.y-y);} // distance squared f n(P&p){return i?x/=i,y/=i,d(p):x=p.x,y=p.y,0;} // normalize-or-reset f a(P&p){x+=p.x,y+=p.y,i++;} // add coordinates }; P z;int l(P a,P b){return a.d(z)<b.d(z);} // closer-to-z comparator f m(f k,V&p){ f s=p.size(),i,j=0,t=1;V c(k),n=c,d; for(random_shuffle(p.begin(),p.end());j<k;c[j].i=j++) c[j]=p[j]; // initial random assignment for(;t;c=n,n=V(k)){ for(i=0;i<s;i++) // assign to clusters d=c,z=p[i],sort(d.begin(),d.end(),l), j=d[0].i,p[i].i=j,n[j].a(p[i]); // and add those coords for(j=t=0;j<k;j++)t+=n[j].n(c[j]); // normalize & count changes } } int main(int argc, char **argv) { srand((unsigned long)time(0)); int k; V p; sscanf(argv[1], "%d", &k); printf("Input:\n"); for (int i=2,j=0; i<argc; i+=2, j++) { P n; sscanf(argv[i], "%f", &(n.x)); sscanf(argv[i+1], "%f", &(n.y)); p.push_back(n); printf("%d : %f,%f\n", j, p[j].x, p[j].y); } m(k,p); printf("Clusters:\n"); for (int q=0; q<k; q++) { printf("%d\n", q); for (unsigned int i=0; i<p.size(); i++) { if (p[i].i == q) printf("\t%f,%f (%d)\n", p[i].x, p[i].y, i); } } return 0; } ``` [Answer] # Matlab, 25 bytes ``` @(x,k)kmeans(x,k,'S','u') ``` Given a `n x 2` matrix (one row per point e.g. `[[4,8]; [15,16]; [23,42]; [-13.37,-12.1]; [666,-666]]`) this functions returns a list of labels for each input point. [Answer] # J, ~~60~~ 54 bytes ``` p=:[:(i.<./)"1([:+/&.:*:-)"1/ ]p](p(+/%#)/.[)^:_(?#){] ``` Defines a helper verb `p` which takes a list of points and centroids and classifies each point by the index of the nearest centroid. Then, it uses that to repeat the process of choosing new centroid by taking the averages of the points in each cluster until it converges, and then to partition the points for output. ## Usage The value of *k* is given as an integer on the LHS. The list of points is given as a 2d array on the RHS. Here it is specified as a list of points which is reshaped into a 2d array of 5 x 2. The output will be the label for which cluster each point belongs in the same order as the input. If you desire to use a fixed seed for reproducible results, replace the `?` with a `?.` at `(?#)`. ``` p =: [:(i.<./)"1([:+/&.:*:-)"1/ f =: ]p](p(+/%#)/.[)^:_(?#){] 3 f (5 2 $ 4 8 15 16 23 42 _13.37 _12.1 666 _666) 0 1 1 0 2 ``` ## Explanation ``` [:(i.<./)"1([:+/&.:*:-)"1/ Input: points on LHS, centroids on RHS ( )"1/ Form a table between each point and centroid and for each - Find the difference elementwise [: *: Square each +/&.: Reduce using addition Apply the inverse of square (square root) to that sum [:( )"1 For each row of that table <./ Reduce using min i. Find the index of the minimum in that row Returns a list of indices for each point that shows which centroid it belongs to ]p](p(+/%#)/.[)^:_(?#){] Input: k on LHS, points on RHS # Count the number of points ? Choose k values in the range [0, len(points)) without repetition ] Identity function, get points { Select the points at the indices above ] Identity function, get points ( )^:_ Repeat until convergence p Get the labels for each point [ Identity function, get points /. Partition the points using the labels and for each +/ Take the sums of points elementwise # Get the number of points % Divide sum elementwise by the count Return the new values as the next centroids ] Identity function, get points p Get the labels for each point and return it ``` [Answer] ## CJam (60 bytes) ``` {:Pmr<1/2P,#{:z{_:+\,/}f%:C,{P{C\f{.-Yf#:+}_:e<#1$=},\;}%}*} ``` This is a function which takes its input in the form `k p` on the stack. It assumes that the points are represented with doubles, not ints. It doesn't implicitly assume anything about the dimension of the points, so it would cluster equally well in 6-D Euclidean space as in the specified 2-D. [Online demo](http://cjam.aditsu.net/#code=3%20%5B%5B4.0%208.0%5D%20%5B15.0%2016.0%5D%20%5B23.0%2042.0%5D%20%5B-13.37%20-12.1%5D%20%5B666.0%20-666.0%5D%5D%0A%0A%0A%7B%3APmr%3C1%2F2P%2C%23%7B%3Az%7B_%3A%2B%5C%2C%2F%7Df%25%3AC%2C%7BP%7BC%5Cf%7B.-Yf%23%3A%2B%7D_%3Ae%3C%231%24%3D%7D%2C%5C%3B%7D%25%7D*%7D%0A%0A~%60) [Answer] # Mathematica ~~14~~ 12 bytes Since built-ins are allowed, this should do it. ``` FindClusters ``` --- ## Example ``` FindClusters[{{4, 8}, {15, 16}, {23, 42}, {-13.37, -12.1}, {666, -666}}, 3] ``` {{{4, 8}, {-13.37, -12.1}}, {{15, 16}, {23, 42}}, {{666, -666}}} [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` _ÆḊ¥þ³i"Ṃ€$ ẊḣµÇÆmƙ³µÐLÇ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@cNvDHV2Hlh7ed2hzptLDnU2PmtaocD3c1fVwx@JDWw@3H27LPTbz0GYgc4LP4fb///9HR5voKFjE6ihEG5rqKBiagVhGxjoKJkYglq6hsZ6xuY6CrqGRniFIwMzMDMgDkrGx/40B "Jelly – Try It Online") Uses features that were implemented after this challenge was posted. Supposedly, this is no longer [non-competing](https://codegolf.meta.stackexchange.com/questions/12877/lets-allow-newer-languages-versions-for-older-challenges). ## Explanation ``` _ÆḊ¥þ³i"Ṃ€$ Helper link. Input: array of points (Classify) Given a size-k array of points, classifies each point in A to the closet point in the size-k array þ Outer product with ³ All points, P ¥ Dyadic chain _ Subtract ÆḊ Norm $ Monadic chain i" Find first index, vectorized Ṃ€ Minimum each ẊḣµÇÆmƙ³µÐLÇ Main link. Input: array of points P, integer k µ Start new monadic chain Ẋ Shuffle P ḣ Take the first k µ Start new monadic chain Ç Call helper (Classify) ƙ Group with those values the items of ³ All points, P Æm Take the mean of each group ÐL Repeat that until the results converge Ç Call helper (Classify) ``` [Answer] # [R](https://www.r-project.org/), 273 bytes ``` function(K,P,C=P[sample(nrow(P),K),]){while(T){D=C U=sapply(1:nrow(P),function(i)w(dist(rbind(P[i,],C))[1:K])) C=t(sapply(1:K,function(i)colMeans(P[U==i,,drop=F]))) T=isTRUE(all.equal(C,D))} cbind(U,P)} w=function(x,y=seq_along(x)[x==min(x)])"if"(length(y)>1,sample(y,1),y) ``` [Try it online!](https://tio.run/##TVBNa4NAEL37M3KagYmwmtgSmF5Me5GClHgSKRs1ZmGzGjWohP52uw1N2svM8Jj3MdPOFc@Hi8l7VRuIKKaQ47STp0aXYNp6gBgpQsrwOhyVxXZ43XLoJNzJptETiM1966GicIBCdT20e2UKiFNFGYWIqdhEGaITcg8PdvSfl9f6vZSms5yEWREVbd3wmyWhs2PV7T6SV5Bau@X5IjWEtEX8cvKbTUKxnQd@yI00cVeeP6WuTQUjpiPzSVkcM1yowwJ0aar@CBO@CPq9eCKBNOFcgU8n2bdqhBxW9ExiTSIgz6eVR0vhu/6TbZ4rKAgCWtqCtKb9ZF/BPyFt3gq8u0RbNmA3kfwbLv6kBXnuGq0pzt8 "R – Try It Online") Takes `P`as a matrix, with `x` and `y`coordinates in the first and second column respectively. Returns `P` with a first column added which indicates cluster index (integer). I had to redefine `w` by copying the source from `nnet::which.is.max` to conform to the requirement that cluster is chosen randomly in case of ties. Otherwise I would use `which.min`from `base` for a total of 210 bytes. There is still room for golfing but I did not want to obfuscate it to much to give others a chance to spot possible issues within my code. [Answer] ## Julia 213 bytes ``` function f(p,k) A=0 P=size(p,1) c=p[randperm(P)[1:k],:] while(true) d=[norm(c[i]-p[j]) for i in 1:k, j in 1:P] a=mapslices(indmin,d,1) a==A&&return a A=a c=[mean(p[vec(a.==i),:],1) for i in 1:k] end end ``` Returns an array of the same length as `p`, with integers indicating which cluster the corresponding element of `p` belongs to. I think there is still a fair bit of scope to optimize the character count down. (Of course I could just use the Clustering.jl package to do it trivially) ]
[Question] [ You should complete four tasks in a language which: * must return no results\* when searched for on this (codegolf.se) website, for example [ToffeeScript](https://codegolf.stackexchange.com/search?q=toffeescript); * must have a page listed at [Esolang](https://esolangs.org/wiki/Language_list), [Rosetta Code](http://rosettacode.org/wiki/Category:Programming_Languages) or [Wikipedia](http://en.wikipedia.org/wiki/List_of_programming_languages); * be a distinct language, rather than a distinct version (e.g. python 2.1 would be valid iff python satisfied the first two criteria). \*The exception being this hit for ToffeeScript. The four tasks you should complete are: 1) Write a tweetable (<140 characters) description/promotion of your chosen language. 2) Print "Hello World! This is written in `<programming language name>`." 3) Print all the odd numbers in a user specified range. (e.g. a stdin of `20 25` should return `21 23 25`). 4) Write a program which you feel best demonstrates an interesting feature of your chosen language. Scoring: * This is a popularity contest * Bonus of 10 points if listed in two of the above directories, 25 if in all three. * Score is the summation of votes received at midnight UTC on July 1 2015, plus the bonuses. Clarifications: * Task 1) can be a tweetable program but plain text is also acceptable. * Many languages do not have an existing interpreter; solutions to these are fine, but will be taken in good faith. * The second criterion for language choice forbids pages whose creation dates after this post. If, for a given language, X, a solution to a problem exists on Rosetta Code but it does not have a distinct page of its own somewhere, it is still acceptable. [Answer] # BlooP Bonus: 10 There are pages for BlooP on [Esolangs](https://esolangs.org/wiki/Bloop) and [Wikipedia](http://en.wikipedia.org/wiki/BlooP_and_FlooP). A PPCG search for BlooP returns no results. If you're feeling particularly loopy, you can [try it out on repl.it](https://repl.it/languages/Bloop). --- ### Task 1: The Tweet > > BlooP: Nothing but bounded loops. ;) #programming #goodtimes > > > This uses standard Twitter styling including hashtags and emoticons. This would appeal to any Twitter user.\* --- ### Task 2: The Hello World ``` DEFINE PROCEDURE ''GREETING'' [N]: BLOCK 0: BEGIN PRINT['Hello World! This is written in BlooP.'] BLOCK 0: END. GREETING[0]; ``` As you can see, this is a prime golfing language.\* --- ### Task 3: The Odd Numbers ``` DEFINE PROCEDURE ''IS-ODD'' [N]: BLOCK 0: BEGIN OUTPUT <= 0; CELL(0) <= 2; LOOP AT MOST N+1 TIMES: BLOCK 1: BEGIN IF N+1 = CELL(0), THEN: BLOCK 2: BEGIN OUTPUT <= 1; ABORT LOOP 1; BLOCK 2: END; CELL(0) <= CELL(0) + 2 BLOCK 1: END; BLOCK 0: END. DEFINE PROCEDURE ''ODDS-IN-RANGE'' [A,B]: BLOCK 0: BEGIN CELL(0) = A; LOOP AT MOST B TIMES: BLOCK 1: BEGIN IF CELL(0) > B, THEN: ABORT LOOP 1; IF IS-ODD[CELL(0)] = 1, THEN: PRINT[CELL(0)]; CELL(0) <= CELL(0) + 1; BLOCK 1: END; BLOCK 0: END. ODDS-IN-RANGE[20,25]; ``` The only available operators in BlooP are assignment (`<=`), addition, multiplication, greater than, less than, and equals. Because of its painfully verbose syntax, it's actually pretty easy to tell what's going on even without a deep understanding of the language. --- ### Task 4: The Interesting Note: My snippet for this task is subject to change should I come up with something more interesting. ``` DEFINE PROCEDURE ''MINUS'' [M,N]: BLOCK 0: BEGIN IF M < N, THEN: QUIT BLOCK 0; LOOP AT MOST M + 1 TIMES: BLOCK 1: BEGIN IF OUTPUT + N = M, THEN: ABORT LOOP 1; OUTPUT <= OUTPUT + 1; BLOCK 1: END; BLOCK 0: END. DEFINE PROCEDURE ''FIB''[N]: BLOCK 0: BEGIN IF N < 1, THEN: QUIT BLOCK 0; OUTPUT <= 1; IF N < 3, THEN: QUIT BLOCK 0; OUTPUT <= FIB[MINUS[N,1]] + FIB[MINUS[N,2]]; BLOCK 0: END. FIB[10]; ``` Behold, the Fibonacci numbers. --- \*May not be true [Answer] # [jq](http://stedolan.github.io/jq/) None of the [14 results on codegolf.se](https://codegolf.stackexchange.com/search?q=jq) is about the language. (`jq` (and uppercase variants) seems to be frequent statement in Pyth.) There is [jq category on Rosetta Code](http://rosettacode.org/wiki/Category:Jq). You can [try it online](https://jqplay.org/) but some of examples below need latest version 1.5. ## Task 1: The Tweet > > jq is like sed for JSON; you can use it to process structured data with the same ease that sed, awk, grep and friends let you play with text > > > (Shamelessly twittified the first paragraph from its site.) ## Task 2: The Hello World ``` bash-4.3$ jq -n -r '"Hello World! This is written in jq."' Hello World! This is written in jq. ``` ## Task 3: The Odd Numbers ``` bash-4.3$ jq -R 'split(" ") | range(.[0] | tonumber; .[1] | tonumber + 1) | select(. % 2 == 1)' <<< '20 25' 21 23 25 ``` ## Task 4: The Interesting The ~/.mozilla/firefox/\*.default/extensions.json file containing information about the installed Firefox extensions has 0 newlines in 171 Kb on JSON data, which makes it somehow difficult to read. Pretty print the JSON data: ``` bash-4.3$ jq '' ~/.mozilla/firefox/*.default/extensions.json ``` Doh. 8000++ lines are too long, so pass it to pager, but keep the highlighting: ``` bash-4.3$ jq -C '' ~/.mozilla/firefox/*.default/extensions.json | less -r ``` Ouch. How many extensions are there anyway? ``` bash-4.3$ jq '.addons | length' ~/.mozilla/firefox/*.default/extensions.json 58 ``` Ok, but some of them are disabled. How many exactly? ``` bash-4.3$ jq '[.addons[] | select(.active | not)] | length' ~/.mozilla/firefox/*.default/extensions.json 7 ``` Some of them are quite abandoned and not work with current Firefox anymore: ``` bash-4.3$ jq -r '.addons[] | [.defaultLocale.name, (.targetApplications[] | select(.id == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"))] | select(.[1].maxVersion | gsub("[^\\d.]"; "") | tonumber < 38.0) | .[0]' ~/.mozilla/firefox/*.default/extensions.json Unity Desktop Integration Unity Websites integration Ubuntu Firefox Modifications ``` (This later is not true. For some reason extensions.json contains other version ranges than the extensions' install.rdf. But that is not jq's fault anyway.) [Answer] # [Mond](https://github.com/Rohansi/Mond)\* * \* Searching for 'Mond' gives [one result](https://codegolf.stackexchange.com/search?q=Mond) (this answer notwithstanding), but it's a false positive and doesn't actually mention the language. * [Rosetta Code page](http://rosettacode.org/wiki/Mond). This was actually created after the challenge was posted, however a solution to the [QuickSort](http://rosettacode.org/mw/index.php?title=Sorting_algorithms/Quicksort&oldid=190099) task has existed since September 2014. * Although mond looks very similar to JavaScript (indeed, it's quite easy to write Mond/JS polyglots), it is not a subset, superset, or re-implementation. It is its own distinct language. [Try it in your browser](https://fpp.literallybrian.com/mond/) ***Full disclosure***: I'm involved with the development and design process of Mond to a degree and have personally implemented several major language features including [user-defined operators](https://github.com/Rohansi/Mond/wiki/Functions#user-defined-operators) which are demonstrated in tasks 3 & 4. ### Task #1 The pipeline operator (`|>`) is syntax sugar that transforms the function call on the right-hand side to a function call with the value on the left-hand side inserted as the first argument. `foo |> bar()` is the same as `bar( foo )`. ``` "Simple, elegant scripting language implemented in C# for .NET/Mono" |> printLn(); ``` ### Task #2 ``` "Hello World! This is written in Mond." |> printLn(); ``` ### Task #3 The code for this task assumes several things: 1. The range of numbers will be entered on a single line 2. The upper and lower bounds will be separated by a single space 3. The numbers given are integers in base-10 and contain only the chars `0-9` [Try it here](https://fpp.literallybrian.com/mond/#429cd3be05d355c7004698f3cb06bc569fdd8442) ``` // parse a string to a number fun toNumber( str ) { var n = 0, pow = str.length(); for( var i = 0; i < str.length(); ++i ) n += ( str.charCodeAt( i ) - 48 ) * ( 10 ** --pow ); return n; } fun map( arr, fn ) { var ret = [ ]; foreach( var item in arr ) fn( item ) |> ret.add(); return ret; } // user-defined operator to create an upper-bound inclusive range a-la Ruby // (i.e. 1 .. 5 produces [ 1, 2, 3, 4, 5 ]) seq( .. )( start, end ) { for( var i = start; i <= end; ++i ) yield i; } // read a line from STDIN, trim leading and trailing whitespace, // split the string to an array, map the array to parse all strings to numbers. var nums = readLn().trim().split( " " ) |> map( toNumber ); // nums[0] .. nums[1] makes use of the user-defined operator declared on line 22. // nums[0] is the lower bound, nums[0] is the upper bound. foreach( var n in nums[0] .. nums[1] ) { if( n % 2 != 0 ) printLn( n ); } ``` ### Task #4 This task demonstrates [user-defined operators](https://github.com/Rohansi/Mond/wiki/Functions#user-defined-operators), which allow the programmer to define any arbitrary operator (so long as it doesn't already exist) just like a function, and use it as they would any other operator. They come in unary and binary flavours. [Try it here](https://fpp.literallybrian.com/mond/#8f5daaec5f3fd8f4768352fb25a0818cb5d49aa6). ``` // forward function compositing user-defined operator. // the function on the right-hand side is called with // the result of the function on the left-hand side. fun( >>> )( fn1, fn2 ) { return fun( ...args ) { return fn1( ...args ) |> fn2(); }; } // the mythical "goes down to" operator of legend. // a lazy sequence that returns all numbers starting from 'hi' // down to (and including) 'lo' seq( --> )( hi, lo ) { for( var i = hi; i >= lo; --i ) yield i; } seq map( iterable, callback ) { foreach( var item in iterable ) yield item |> callback(); } // doubles the value of n fun double( n ) -> n * 2; // squares the value of n (** is the power operator, a-la Python or Ruby) fun square( n ) -> n ** 2; // gets the sequence for 10 down to 0, passes it into // map, which maps it through the composited function of // double and square, which first doubles the given value // then squares it. var nums = ( 10 --> 0 ) |> map( double >>> square ); foreach( var n in nums ) printLn( n ); ``` [Answer] # [ooc](http://ooc-lang.org/) Yeah, I'm about a month late. So what??? * Searching for ooc currently gives no results. * [Link to ooc at Rosetta Code](http://rosettacode.org/wiki/Category:OOC). ## Task 1 > > ooc is a programming language that compiles down to C99 that has an elegant syntax, and supports both high- and low-level development. > > > 135 bytes! That was close! Also, fake bonus points for ooc's [insanely cool ASCII-art logo](https://github.com/fasterthanlime/rock/blob/master/docs/art/logo.txt): ``` +(NNhBBhss+' ~+'(sNBND=~. -(=NDhNN+=+=' . . . . .+='+~DNND+=. .+-DBDDh+(D-<' ..... -<+ (=~DNh+<( '+<NNNB=~=z-(<-<<(+('-'~<<=- .+'sBNh~+ (~=NNND+=DB~(-. . . ...(=BNB+s-- ALL YOUR .=-=DBDz-'~. . ..'. .... ' '~s<<szh<. <(~'. . . ..sD='-~'-'-DDs.. . .~sD( CODEBASE . ~+' ' .-(-..sBNB~(~~+=hNNNz'<<z='-z( . .=. -DDz<~s~ 'BNNN=~+<shNNNND(sNNNh~(+ ARE BELONG .=<.(NNNNDDs. (hhs+=s=hNDNNBNBBs<BNND<<=. .'-'~sNNs((- .''. ' -~NNDz+((~---~sB<'''. TO US! '=(++(-.. . ...-~+B~'....'.''-+( . -=z<<'.. .'-...'-~hz~-'.''''-~-<= .~+~s~ ~z<~'-'--hN=~((~'---(~~z~ (+<-.'+=''''~(+=Bz--~(((=+s+~(s IT'S OVER . '+-..~<----~-+(sBNh+zBNNBNh+<z' .<-'--''(<~=B=hDDD=<<<++=++<=. 9000 BUGS! .. s~..'h=++ss=D<<~+B(<(+<=Nz=+ +'.''+NNDN(+z(((sB<((s+hNh<+ .= -~(~(zDNz+z+zhNDz=szhhBz++. MADNESS? '+. ss<'~=NBNBBDzBzhshDD=+<<- -= . +s~-(+==hhDBNBDDs==hz+< THIS! IS! LLAMA! '(<- . '~~(<+<=+<sz=+sshzs(.. .+<. '('-~(((((<++(<<((= . .--.. ....'.'.'.'..''..'-.. ``` ## Task 2 ``` "Hello, world!" println() ``` ## Task 3 ``` import text/StringTokenizer import structs/ArrayList input := stdin readLine() split(' ', false) (begin, end) := (input[0] toInt(), input[1] toInt()) for (i in begin..end+1) { if (i % 2 != 0) { "%d " printf(i) } } println() ``` Pretty straightforward implementation. Also, this showcases an interesting aspect of ooc: method calls use spaces as delimiters, not dots. For instance, notice `stdin readLine() split(' ', false)` above. In most languages, that would be written as `stdin.readLine().split(' ', false)`, but ooc reserves that for [call chaining](http://ooc-lang.org/docs/tutorial/#when-features-creep) (scroll down to the code example). ## Task 3 This showcases my favorite ooc feature: type matching. It's like pattern matching. In an OO language. Awesome. ``` import structs/ArrayList import math/Random Animal: abstract class { makeNoise: abstract func } Sheep: class extends Animal { init: func makeNoise: func { "Baaaaaaa!" println() } } Wolf: class extends Animal { init: func makeNoise: func { "Hooooowl!" println() } } animals := [Sheep new(), Sheep new(), Sheep new()] as ArrayList<Animal> badNumber := Random randRange(0, 3) animals[badNumber] = Wolf new() animal: Animal "Enter a number between 0 (inclusive) and 3 (exclusive)" println() inputNumberString := stdin readLine() for (chr in inputNumberString) { if (!(chr.digit?())) { "NUMBER, not CHARACTER! Can't you read!?" println() exit(1) } } inputNumber := inputNumberString toInt() try { animal = animals[inputNumber] } catch (e: OutOfBoundsException) { "I said a number between one and three, you idiot!" println() exit(1) } "Animal noise:" println() animal makeNoise() match (animal) { case sheep: Sheep => { "It's a stupid, annoying sheep!" println() } case wolf: Wolf => { "AHH! A WOLF! You got eaten. :/ R.I.P." println() } } ``` ]
[Question] [ My coworker and I work on a legacy piece of software that we hate sometimes. Whenever you run it, debug asserts come flying everywhere, and it's never a guarantee that anything will work. The motivation for this round of code golf came from my coworker saying **the following about our software**. *"It's like every time you run this program, you're agreeing to some terms of service that says every 17th bit on your hard drive will be turned into a 1"* **Goal: Write a program that will make an exact copy of a file and turn every 17th bit of a text file into a 1** * You may **NOT** turn **EVERY** bit of the file to a 1. i.e. your program must show some intelligence that it is only targeting every 17th bit * You may **NOT** write to the original file in any way shape or form * The **Winner** is the smallest program submission at the end of the month Have fun with this one! Go! [Answer] # CJam, 22 bytes ``` q256b2H#b1f|2H#b256b:c ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") Touches every 17th bit, counting from the last. I've used STDIN and STDOUT since CJam has no file I/O. If that's not allowed, the program can be wrapped in a Bash script at the cost of 24 extra bytes: ``` cjam <(echo q256b2H#b1f\|2H#b256b:c)<"$1">"$2" ``` ### How it works ``` q " Read from STDIN. "; 256b " Convert to integer by considering the input a base 256 number. "; 2H#b " Convert to array by considering the integer a base 2**17 number. "; 1f| " Set the LSB of every integer in the array element to 1. "; 2H#b " Convert to integer by considering the array a base 2**17 number. "; 256b " Convert to array by considering the integer a base 256 number. "; :c " Turn character codes into characters. "; ``` [Answer] ## Perl 59 regex substitution on bit strings: ``` $/=$\;$_=unpack"B*",<>;s|(.{16}).|${1}1|g;print pack"B*",$_ ``` usage: ``` perl this.pl < infile.txt > outfile.txt ``` [Answer] # C, 125 **Assumes big-endian and 16-bit integers**. Works by applying a bitwise-OR on every two bytes. Input file is `y`, output is `z`. ``` unsigned a,b;main(c){void*f=fopen("y","r"),*g=fopen("z","w");while(b=fread(&c,1,2,f))c|=a,a?a/=2:(a=32768),fwrite(&c,1,b,g);} ``` Ungolfed ``` // The commented out /* short */ may be used if int is not 16 bits, and short is. unsigned /* short */ a = 0,b; main(/* short */ c){ void *f = fopen("y", "r"), *g = fopen("z", "w"); while(b = fread(&c, 1, 2, f)){ // __builtin_bswap16 may be used if you are using GCC on a little-endian machine. //c = __builtin_bswap16(c); c |= a; if(a) a >>= 1; else a = 32768; //c = __builtin_bswap16(c); fwrite(&c, 1, b, g); } } ``` [Answer] # Python 2, 112 bytes ``` b=open('i').read().encode('hex') open('o','w').write(('%x'%(int('1'+b,16)|16**len(b)/131071))[1:].decode('hex')) ``` This sets every 17th big-endian bit, starting 17th from the beginning. It uses no libraries. It works by converting the input file to a gigantic `n`-bit integer and bitwise ORing with `2**n/(2**17 - 1) == 0b10000000000000000100000000000000001…`. [Answer] # C - 139 Reads from a file named "i", outputs to a file named "o". ``` c;main(){unsigned char b,m=1;void *i=fopen("i","r"),*o=fopen("o","w");for(;(b=fgetc(i))<129;fputc(b,o))((c+=8)%17<8)?b|=m=(m-1)?m/2:128:0;} ``` With line breaks: ``` c;main() { unsigned char b,m=1; void *i=fopen("i","r"),*o=fopen("o","w"); for(;(b=fgetc(i))<129;fputc(b,o)) ((c+=8)%17<8)?b|=m=(m-1)?m/2:128:0; } ``` Counts bits of input and then uses a floating bitmask to set every seventeenth bit. [Answer] # Java - 247 Uses a `BitSet` and a simple loop instead of handling/masking the bytes manually. Of course this being java, the boilerplate is half the program, so it's not exactly short. Still, *not last!* :D ``` import java.util.*;import java.nio.file.*;class F{public static void main(String[]a)throws Exception{BitSet b=BitSet.valueOf(Files.readAllBytes(Paths.get(a[0])));for(int j=0;j<b.size();b.set(j),j+=17);Files.write(Paths.get("o"),b.toByteArray());}} ``` No-scroll version: ``` import java.util.*; import java.nio.file.*; class F{ public static void main(String[]a)throws Exception{ BitSet b=BitSet.valueOf(Files.readAllBytes(Paths.get(a[0]))); for(int j=0;j<b.size();b.set(j),j+=17); Files.write(Paths.get("o"),b.toByteArray()); } } ``` [Answer] ## Python - 98 bytes Read from i, write to o. Uses bitarray library <https://pypi.python.org/pypi/bitarray> ``` from bitarray import*;a=bitarray();a.fromfile(open('i','rb'));a[::17]=1;a.tofile(open('o','wb')) ``` ungolfed ``` from bitarray import * a=bitarray() a.fromfile(open('i','rb')) a[::17]=1 a.tofile(open('o','wb')) ``` [Answer] # Cobra - 308 ``` use System.Text.RegularExpressions class P def main t,b='',File.readAllBytes('x') for n,i in b.numbered,for l in 8,b[n]=if(l,b[n],0)+if(Regex.replace(t+='00000000'[(j=Convert.toString(i,2)).length:]+j,'.{17}',do(m as Match)='[m]'[:-1]+'1')[n*=8:n+8][7-l]<c'1',0,2**l)to uint8 File.writeAllBytes('y',b) ``` Every time I do one of these 'manipulate the individual bits of something' challenges, I wish that either Cobra or the .NET standard library had a `binary string => integer` converter. [Answer] # Javascript (+HTML5), 282 Probably not the shortest, but it's user friendly :D It's cross browser, but it seems that chrome is the only one allowing it when the html file is a local file (= access with `file://...`). For the other browsers, you need to put it on a web server. The output file should be saved to the default download directory, maybe with a file prompt (depending on your configuration). ``` <input type=file onchange="r=new FileReader();r.onloadend=function(){w=window;a=new Uint8Array(r.result);for(i=17;i<a.length*8;i+=17)a[i/8>>0]|=1<<8-i%8;w.location.replace(w.URL.createObjectURL(new Blob([a],{type:'application/octet-binary'})));};r.readAsArrayBuffer(this.files[0])"> ``` Ungolfed version : ``` <input type=file onchange=" var reader = new FileReader(); reader.onloadend = function() { var arr = new Uint8Array(reader.result); for(var i = 17 ; i < arr.length * 8 ; i += 17) { arr[Math.floor(i / 8)] |= 1 << (8 - (i % 8)); } window.location.replace( window.URL.createObjectURL( new Blob([arr], {type: 'application/octet-binary'}) ) ); }; reader.readAsArrayBuffer(this.files[0]); "> ``` [Answer] # Python 3 - 187 bytes --- Reads in from `i` and writes to `o`. Code: ``` o=open;j="".join;f=list(j(format(x,"08b")for x in o("i","rb").read())) f[16::17]="1"*(len(f)//17) with o("o","wb") as f2:f2.write(bytes(int(j(f[i*8:(i+1)*8]),2)for i in range(len(f)//8))) ``` Ungolfed: ``` # read file and convert to binary string e.g. "101010010101010101" f = list("".join(format(x, "08b") for x in open("in.txt", "rb").read())) # set every 17th bit to 1 f[16::17] = "1" * (len(f)//17) with open("out.txt","wb") as f2: data = [] for i in range(len(f)//8)): # for each byte byte = "".join(f[i*8:(i+1)*8] # get each byte data.append(int(byte),2) # convert to int f2.write(bytes(data)) # convert to byte string and write ``` [Answer] # Python 3 - 103 chars Change `f` to the path of the file you want to read and `o` to path of the file you want to write to. ``` l=open;t=list(l(f,'r').read()) for i in range(len(t)): if i%18==0:t[i]='1' l(o,'w').write(''.join(t)) ``` ]
[Question] [ ## Explanation Two strings can be shuffled by interspersing their letters to form a new string, much like two piles of cards can be shuffled to form a single pile. For example, the strings `HELLO` and `WORLD` can be shuffled to form `HWEOLRLLOD`, or `HEWORLLLDO`, or perhaps simply `HELLOWORLD`. It is **not** a shuffle if the original order of letters is not preserved. For example, the `D` in `WORLD` cannot ever appear before the `R` after being shuffled. This means that `EHLLOWRDLO`, for instance, is not a shuffle of `HELLO` and `WORLD`, even though it contains all the original letters. A string is a *shuffle of twins* if it can be formed by shuffling two identical strings. For example, `ABACBDECDE` is a shuffle of twins because it can be formed by shuffling `ABCDE` and `ABCDE`. `DBEACBCADE` is not a shuffle of twins because it cannot be formed by shuffling two identical strings. ## Program Details Given an input string, output `0` if it is not a shuffle of twins, and output one of the twin strings if it is a shuffle of twins. You may assume that the input string has a length inclusively between four and twenty characters and is composed entirely of uppercase alphabetic characters. It should be able to run in a reasonable amount of time, say, under 10 minutes. This is code golf, so the shortest solution wins. ## Example I/O ``` > ABACBDECDE ABCDE > DBEACBCADE 0 > FFFFFF FFF > FFGGG 0 > ABBA 0 > AABB AB > AABAAB AAB ``` I have an [example (non-golfed) implementation](http://jsbin.com/owixen/2/edit#source). [Answer] # Haskell, 114 ``` main=getLine>>=putStrLn.f.p;f x=head$[a|(a,b)<-x,a==b]++["0"] p[]=[([],[])];p(x:y)=do(a,b)<-p y;[(x:a,b),(a,x:b)] ``` **Ungolfed:** ``` main :: IO () main = getLine >>= putStrLn . findMatch . partitions -- | Find the first partition where the two subsequences are -- equal. If none are, return "0". findMatch :: [(String, String)] -> String findMatch ps = head $ [a | (a,b) <- ps, a == b] ++ ["0"] -- | Return all possible partitions of the input into two -- subsequences. Preserves the order of each subsequence. -- -- Example: -- partitions "AB" == [("AB",""),("B","A"),("A","B"),("","AB")] partitions :: [a] -> [([a], [a])] partitions [] = [([], [])] partitions (x:xs) = do (a, b) <- partitions xs [(x:a, b), (a, x:b)] ``` **Explanation:** Most of the work is being done in the `partitions` function. It works by recursively generating all partitions `(a, b)` of the tail of the list, and then using the [list monad](http://en.wikibooks.org/wiki/Haskell/Advanced_monads#The_List_monad) to prepend the initial element `x` to each of them and gather all the results. `findMatch` works by filtering this list so that only partitions where the subsequences are equal remain. It then returns the first subsequence in the first partition. If none remain, the list is empty, so the `"0"` appended at the end gets returned instead. `main` just reads the input, feeds it through these two functions and prints it. [Answer] # R, 113 chars ``` l=length(x<-charToRaw(scan(,'')));max(apply(combn(l,l/2),2,function(i)if(all(x[i]==x[-i]))rawToChar(x[i])else 0)) ``` Ungolfed (and instead a function that takes the string): ``` untwin <- function(x) { x <- charToRaw(x) indMtx <- combn(length(x),length(x)/2) res <- apply(indMtx, 2, function(i) { if (all(x[i]==x[-i])) rawToChar(x[i]) else 0 }) max(res) } untwin("ABACBDECDE") # "ABCDE" untwin("DBEACBCADE") # 0 ``` The solution relies on the `combn` function that generates all combinations of indices as columns in a matrix. `apply` then applies a function to each column (dimension `2`) in the matrix and returns a vector of strings or zeroes. `max` then find the biggest string (which trumps 0). A cool feature in R is the ability to select a subset of a vector given a vector of indices, and to then select the *complement* of that subset by negating the indices: `x[i] == x[-i]` [Answer] ## Mathematica, 87 This is directly based on hammar's post, but hopefully it is distinct enough to merit posting. ``` <<Combinatorica` f=Catch[Cases[Characters@#~KSetPartitions~2,{x_,x_}:>Throw[""<>x]];0]& ``` Test: ``` f /@ {"ABACBDECDE", "DBEACBCADE", "FFFFFF", "FGG", "ABBA", "AABB", "AABAAB"} ``` ``` {"ABCDE", 0, "FFF", 0, 0, "AB", "AAB"} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` {;Ẹp}ᵐzcᵛ.∨ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv9r64a4dBSBmVfLDrbP1HnWs@P8/WsnRydHZycXV2cVVSUdBycXJFch1doTw3MAAwnJ3dwcxHJ2cHME0kAGlgUgpFgA "Brachylog – Try It Online") Using an unbound output variable as 0 might be cheating, so +1 byte if that's a problem (even though ideally it could just be allowed to fail and we could drop the `.∨`). ``` { }ᵐ For each character of the input, ;Ẹ pair it with an empty string p in either order. z The zipped pairs cᵛ concatenate to the same thing, . which is output. ∨ If that's not possible, leave the output unbound instead of failing. ``` [Answer] ## D ``` string c(string in,string a=[],string b=[]){ if(in.length==0)return a==b?a;"0"; auto r=c(in[1..$],a~in[0],b); return r=="0"?c(in[1..$],a,b~in[0]):r; } void main(){writeln(c(readline));} ``` using depth first recursive search I can make it faster with a `int i = min(a.length,b.length);if(a[0..i]!=b[0..i])return "0";` guard clause [Answer] ### Ruby, 89 characters ``` s=->a,x,y{a=="\n"?x==y ?x:?0:[s[b=a[1..-1],x+c=a[0],y],s[b,x,y+c]].max} $><<s[gets,'',''] ``` This code implements a plain recursive search algorithm. The input must be given on STDIN. [Answer] ## Perl, 68 chars ``` /^((.+)(?{local($x,$,)=($,,$x.$^N)}))+$(?(?{$o=$,eq$x&&$,})|x)/?$o:0 ``` The input string assumed to be in the `$_` variable, the output is the value of the expression. Trailing newlines in input are ignored. You can run this from the command line like this: ``` perl -lne 'print /^((.+)(?{local($x,$,)=($,,$x.$^N)}))+$(?(?{$o=$,eq$x&&$,})|x)/?$o:0' ``` This code makes use of Perl's regexp engine (and specifically its [embedded code execution](http://perldoc.perl.org/perlre.html#%28%3F%7B-code-%7D%29) feature) to do the backtracking. Basically, it matches the input string against the regexp `^((.+))+$`, keeping track of the odd- and even-numbered submatches in `$x` and `$,`, and rejecting the match at the end if the two aren't equal. [Answer] ## Python, 168 characters ``` def f(s): c=s[0] d=i=r=0 if s==c+c:r=c while i+1 and i<=len(s)/2 and not r: if i:d=f(s[1:i]+s[i+1:]) if d:r=c+d i=s.find(c,i+1) return r print f(raw_input()) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œ€ιJ.ΔË}θ< ``` [Try it online](https://tio.run/##ASYA2f9vc2FiaWX//y7Fk@KCrM65Si7OlMOLfc64PP//QUJBQ0JERUNERQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf72jkx81rTm300vv3JTD3bXndtj81/nv6OTo7OTi6uziyuXi5ApkOzsCmW5gAKTc3d25HJ2cHLkcgSSIACIA). If a more flexible output would have been allowed which outputs `-1` instead of `0`, and `["ABCDE","ABCDE"]` instead of `"ABCDE"`, it could have been **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` .œ€ιJ.ΔË ``` [Try it online](https://tio.run/##yy9OTMpM/f9f7@jkR01rzu300js35XD3//@OTo7OTi6uzi6uAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf72jkx81rTm300vv3JTD3f9rdf47Ojk6O7m4Oru4crk4uQLZzo5AphsYACl3d3cuRycnRy5HIAkigAgA). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string # i.e. "AABB" → [["A","A","B","B"],["A","A","BB"],["A","AB","B"],["A","ABB"], # ["AA","B","B"],["AA","BB"],["AAB","B"],["AABB"]] €ι # Uninterleave each partition # → [[["A","B"],["A","B"]],[["A","BB"],["A"]],[["A","B"],["AB"]],[["A"],["ABB"]], # [["AA","B"],["B"]],[["AA"],["BB"]],[["AAB"],["B"]],[["AABB"],[]]] J # Join the inner lists together to a single string # → [["AB","AB"],["ABB","A"],["AB","AB"],["A","ABB"], # ["AAB","B"],["AA","BB"],["AAB","B"],["AABB",""]] .Δ # Find the first result for which: # (will result in -1 if none are valid) Ë # Both strings are equal, thus a twin }θ # Afterwards, only leave the last value (the single string if we've found a # twin; or 1 if it resulted in -1) # i.e. ["AB","AB"] → "AB" # i.e. -1 → 1 < # And decrease by 1 (no-op if it was a string with just uppercase letters) # i.e. "AB" → "AB" # i.e. 1 → 0 # (after which the result is output implicitly) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` g=([c,...x],p,q)=>c?g(x,[p]+c,q)||g(x,[q]+c,p):p==q&&p ``` [Try it online!](https://tio.run/##LY3LCoMwEEX3@QpXmrRpdFlaYkl8fUCXIkViFItofBUL/rtNrMPMcM8dmPvOP/kohlpNl7Yr5LZVFKYCE0KWDCvcI@qLRwUXnKrsLDSv6069IYVuitLettV2B4Ps53qQ0ClHB5FB5kVcN/L5bQX0sDNP5XW3VZMLCV3fguSE3ArDF15MSNeOXSNJ01VQByCENt9inAU8jIIwAoybDXwr5JE2A6bJMxzvBczslCTJ/8A4Z4fSUj84pG6g5wc "JavaScript (Node.js) – Try It Online") Try each split [Answer] # [Scala](http://www.scala-lang.org/), 431 bytes 431 bytes, it can be golfed much more. --- Golfed version. [Try it online!](https://tio.run/##fZFfb9sgFMXf@RR3kVqBmjhuH60xyU7SaNK2l2pPUTQRB9u0GEeAJ02RP3t2Men/boiHe@75AQdwpdDipNpDZz24IJKy01qWXnUmaXsvdlomubXiT9FXlbSEdLt7tOG7UAaOp72soKYm@2o840cSpI5yasdm9mLx5ptyfoPd7ZarilrOU/bCpsGmjEntJETfvPJpCr3xSoNhie8CHVk8cXY9tbNrlrTiEESW/WJXV@c@I1hMzfyGDWPAnrrszltl6hD5t9CguUu0NLVvCJ6rL24@YbJJOiFh@4iUvKaaYWnB8mCFquUpqTpLd59nJYuc4jvMdif9qAR/yqxZUintpf3RearYaDdcnS@SOPwBuR/zu6RshM19ZPZcfGxi0obz/eVlc87@pcUMLX@UxGLZPsSbkmEgdhhOAOEFWvw8KmztMhjfdxOhLcvgp1EeOBwJ4Dhg12tDezrJi3xRLFeL5WrCGMzngJ0g3nLLYoXgIn/m0nfM7Tge/VC@J9br9b83yIsi/4@L9nPIj2ycT0AkBjKQ018) ``` def g(n:Int)={ def l(n:Int,r:Int):ArrayBuffer[List[Int]]=if(r==0)ArrayBuffer(List())else if(r==n)ArrayBuffer((0 until n).toList)else l(n-1,r-1).map(n-1::_)++l(n-1,r) l(n,n/2)} def u(s:String)={ val l=s.length if(l%2!=0)"0" else{ val c=g(l) var r="0" var m=0 for(b<-c){ val i=b.toSet val a=(0 until l).filterNot(i) val h=i.toList.sorted.map(s.charAt) val d=a.sorted.map(s.charAt) if(h==d&&h.length>m){ m=h.length r=h.mkString }} r}} ``` Ungolfed version. [Try it online!](https://tio.run/##jZPbbtswDIbv/RRcgBUW2jpZL41mgJ1k2YBuN8WugmBQHDnVJkuBJO@AIc@eUZYcK0UPCwJYJr@fpEjaVFTQ45E3e6UtGPeWVUoIVlmuZNa0lm4Eywqt6Z@yrWumk0RtvqMbPlMu4W@SAGxZDTtmZ6rZcEmd0KQyh0/Skhwi6eqOG7tC83oNU5QCeK1Qah8EV6D/UwjAa0g1TKcwITGcOjglJFBMGDag8hxNJ9BKywXaM6uc8EzmC4NreId1uQfJGhoskOfwjcDl5Tnl9Yeke3jPFUgYw43zHPp2YdZfXKYmh3urudyR/nC6308qQDC5sw9oMpk/Jv29g@ct3MCbrgF9UzSzrZYwmoziQlywKhoPhnw8MB@R9LzGSKYVNqqrj@mcDf19xyQaJ52pVhpSlwBur88SDYW5EjgKnBd7fc9s5MBcFn2ncYRispoLy/QXZVNOIrzm2tiPVNSo4WFwmcENZttuQCarHqgubKwxrFJyG0Qu30sC1@IoyTRWX1wM@cNY4H1oyHBdGFr0mD4RvsNnRPPDtzswh3iIHo@3qMFPMKV6Z8LXsvLiNW7TV8ntaZf2aLVCpmHrRkVZzMr5YjZfjAiB8RjQ4l6ehOflAulZMcCTp8EP3a@H3PEZbLlcvhKqKMviNQSZofpnGfyfKI8dkkNyPP4D) ``` import scala.collection.mutable.ArrayBuffer object Main { def getCombinations(n: Int): ArrayBuffer[List[Int]] = { def loop(n: Int, r: Int): ArrayBuffer[List[Int]] = { if (r == 0) ArrayBuffer(List()) else if (r == n) ArrayBuffer((0 until n).toList) else loop(n - 1, r - 1).map(n - 1 :: _) ++ loop(n - 1, r) } loop(n, n / 2) } def untwin(s: String): String = { val length = s.length if (length % 2 != 0) { return "0" } val combinations = getCombinations(length) var result: String = "0" var maxLen = 0 for (comb <- combinations) { val i = comb.toSet val rest = (0 until length).filterNot(i) val firstHalf = i.toList.sorted.map(s.charAt) val secondHalf = rest.sorted.map(s.charAt) if (firstHalf == secondHalf && firstHalf.length > maxLen) { maxLen = firstHalf.length result = firstHalf.mkString } } result } def main(args: Array[String]): Unit = { println(untwin("ABACBDECDE")) // "ABCDE" println(untwin("DBEACBCADE")) // "0" println(untwin("FFFFFF")) // "FFF" println(untwin("FFGGG")) // "0" println(untwin("ABBA")) // "0" println(untwin("AABB")) // "AB" println(untwin("AABAAB")) // "AAB" } } ``` ]
[Question] [ *[There was a previous perceptron question but it was closed](https://codegolf.stackexchange.com/questions/171296/single-perceptron-implementation). Also it required a lot of extra stuff that's not normally part of the perception algorithm like I know it. This question will be much simpler* The [Perceptron](https://en.wikipedia.org/wiki/Perceptron) is a extremely basic classification algorithm. While it still has some limited use it's been mostly overtaken by gradient descent based algorithms that can match much more complex functions. Still its fun and easy to implement, and is the foundation for many more complex algorithms. The dot product is defined as follows: $$(A\_0, A\_1, \dots, A\_n) \cdot (B\_0, B\_1, \ldots, B\_n) = A\_0 B\_0 + A\_1 B\_1 + \ldots + A\_n B\_n$$ ## Algorithm Description Percepron can classify vectors into 2 categories, simply by taking the dot product with some vector. If this is positive, you are in category A, if negative, then not. The algorithm to compute this vector works as follow: ``` set the initial vector to <0, 0, ..., 0> while not every data point is classified correctly: let p be the first incorrectly classified point if the dot product is positive or zero but it should be negative: add p to the vector if the dot product is negative or zero but it should be positive: subtract p from the vector ``` [Sample Implementation](https://gist.github.com/mousetail/c58aa000b80596283ac84c5d926d72b9) Among the many weaknesses of this algorithm is that it runs forever if no solution exists, that it can only classify categories separated by a straight plane, and that that plane must pass through the origin. You *do not* need to follow this exact algorithm as long as you can guarantee a correct vector in all the cases this algorithm would. ## The task Take as input a list of positive tuples and a list of negative tuples. All tuples will all be the same length, and can contain any real number representable by a 32 bit float. Then output a vector that perfectly classifies them. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins. You may also take input as a single list of `((x0, ..., xn), category)` tuples. You may take the length of the tuples as a extra input if desired. You may assume a solution exists for the input given. The tuples in the input will *always* have 1 as their last value, representing bias. ## Test Cases Note: There are many vectors that can classify the data, any of them would be a valid result. Your code may still be correct if it produces very different values from this. ``` [ { "positive": [[1,0, 1]], "negative": [[0,1,1]], "result": [1,-1,0] }, { "positive": [[12.12958530911699, 71.71547437602891, 17.615042787292396, 1.0], [22.894324259518754, 7.747740085241489, -16.379692578583914, 1.0], [-77.19508767650036, 26.391457800328325, -34.128081828012256, 1.0], [96.46713849700853, 8.223882871718914, 95.59810235088628, 1.0], [95.47166665625838, 36.07081574287895, 20.660512993212635, 1.0]], "negative": [[-41.92974660410673, -42.941790456679854, 21.407959882725905, 1.0], [-99.40397441836177, 26.174868779681844, 56.51788064358769, 1.0], [34.482060088467364, -96.36102804944655, 1.5810491199434153, 1.0], [-43.06995918058733, -65.8456447109237, -99.04122951157478, 1.0], [7.7462310407688335, -10.894130800401939, 77.86204331190197, 1.0], [44.47180923569721, -93.53543659179937, 6.715910740415197, 1.0], [71.16273132699712, -80.16856861976358, 48.05726245445331, 1.0]], "result": [78.64936114023355, 237.2180619264857, -42.5708443640236, 10.0] }, { "positive": [[19.891204296811196, 10.95935510782877, 25.985095341720097, -39.87626202198886, 13.054847014298801, -0.8134570474536389, -54.24129976411458, 1], [-16.576268085926657, 4.5002152868197385, 6.698984554370156, -49.780067496976976, 3.9392362908185703, -11.457246915347255, -3.84485029930714, 1], [-6.424223219895211, -67.86203596702003, 0.6670934629448197, -67.56926034741468, -34.71326779844648, -19.40781793399796, -38.93217338522913, 1], [-55.06122442753092, -46.49216596542017, -28.522294222446035, -30.89448675440849, 25.85546157303159, -28.753484757197114, -67.37074950075419, 1], [12.753734640663126, -42.688681313433065, -37.073894323478854, -22.678023584770216, -12.23724620287598, 4.467063264393019, -28.749388172615724, 1], [-25.894264060028036, -4.384289071814308, 25.545930397049247, -53.005653882689884, -17.7501576060518, -19.66585588898353, -33.29502103119091, 1], [-32.104636572417846, -61.44888846917201, -41.89407929533455, 20.32097494020971, 8.703788581939762, 12.493571659393822, -35.255247777162495, 1], [24.15536843650885, -25.610207061176325, 16.08185788882571, -34.478497500787185, -18.915615320612233, 24.782283056323323, -24.770226555932894, 1], [6.765979248514711, -1.6248990886835486, 19.091220818794667, 14.715692506417057, 7.953257187955259, 12.722665623234263, 14.914783085366352, 1]], "negative": [[-2.7270414497182855, 8.676310678740919, -72.98709301742022, -7.70910010724549, 10.477333664984855, -17.506198964389014, 18.233248667960424, 1], [-43.3010158973477, -20.807005424922295, -77.5083019019948, 16.126838313178908, -40.490353240152864, -11.81562605632648, -8.902497984641357, 1], [-31.71159835398403, -14.73301578999785, 13.902967116929815, -21.834371921202447, -40.86878402777407, 6.742152812766307, -16.213431636063206, 1], [-66.57071699396832, -2.6930106603672783, 24.856421108284607, 26.02555433076685, -45.195502153813656, -60.583102046347044, 18.622821621702442, 1], [-47.07567023723187, 8.668277396085415, -55.64099369519978, -24.3651014072761, -77.50500543887348, -29.67008512028478, -27.6004244984169, 1], [16.02465948636585, -64.28947887797132, -18.663992818184852, 11.001922130635734, -65.96111461946506, -70.07973218635979, -41.525576739268594, 1], [-33.6451045267202, -8.496296235717935, -20.129571219612984, 9.152732883489037, 10.242775447179753, -61.865587395289765, -32.78507965995476, 1], [-59.32306321222039, 12.522731642519034, 22.026994802405454, -18.062615366497297, -8.713470639955815, -44.04186584475624, 27.84951438666559, 1], [15.30669132488326, 4.865567302204951, -2.782248675090557, 24.252984759612147, -31.883249650258065, 0.5697927616565579, 22.431436239098076, 1], [1.0357436812954433, -32.44164907799862, 13.942522314820707, 16.30751529733827, -12.905194523861582, -22.446463524560656, 12.651474924205772, 1], [-56.03563699153419, 12.024854226295957, -39.90028407341309, 26.9268535257967, 23.808505964904285, 0.34968582027003947, -29.362006601750707, 1], [-85.14402438073334, -15.501824729148709, -63.38128746811267, -42.15734961052637, -4.1615796887736565, -7.25189532732314, -27.223088213381402, 1], [2.7529807581849184, -23.668062096200217, -9.028343561579462, 2.5495275958544283, 15.88901518194605, -59.28742737700396, 25.402434735936126, 1], [-49.514159298902705, -24.01610873489301, 19.949647054069544, -41.1158129509881, -53.808681913915706, -11.175092994514387, 16.753648710377945, 1], [13.052884356788013, -29.298799492103925, -11.675938518634197, -11.229831992030299, -82.661335125941, 0.4488670991709114, 15.5168860373427, 1], [-10.923814330565236, -44.964063927868544, -38.9909686186201, 15.763631832856007, -44.00734436715622, -54.69686019599016, -52.81999206838163, 1], [-43.815947420234714, 19.90446963235277, 4.773988726751696, -47.12560089860667, 13.028054180292472, -39.81105100874389, 16.639915018971934, 1], [-60.88215048423795, 18.63815015768826, 27.157195120177462, -31.93335885907136, -6.562377024790365, 20.3179674395969, 9.210423673803817, 1], [-20.199358866077134, -50.594347683405196, -65.49273675929138, 19.37323156150201, -13.877303200574588, 19.536120330891066, -17.908737459942998, 1], [-11.03148069515855, 18.400073052625856, -65.34212863735566, -5.32988003172234, 0.7010084382675785, 26.36787095325562, 22.718825279142763, 1], [-30.028696420764177, -20.038640467728513, -47.66006964061526, 1.669739637216125, 3.3366149257696947, -20.495524621115493, 11.79886970131642, 1]], "result": [53.402165827630355, -96.34048665666451, 46.75018310196545, -58.648563298215464, 167.65173848467344, 54.84963473487821, -66.47771531555354, 6.0] } ] ``` [Answer] # JavaScript (ES6), 102 bytes *-1 by [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects `[ positive, negative ]`. ``` A=>(g=V=>A.some((a,j)=>a.some(v=>!(q=v.map((c,i)=>(x=V[c*=1-2*j,i]||0,t+=c*x,c+x),t=0))>=t))?g(q):V)`` ``` [Try it online!](https://tio.run/##jZjLblzHEYb3foqJN5qRZg6qu6tvMoaBF95kEQMJoA1DwAxNKRRkUZYYQUHsZ1e@vw45dJzECCHIFmdOX6r@W53Xlx8vP1y9v3l3d3h7@/3155fHz18fz7avji@OZ18vH25/uN5uL/evd8ezy/VfH49nv9v@ePy4/HD5bru92t/w0fbT8cX51dNjOuSnr/c3Fz/9ZPu7Z8erp5/2V88@7fZ3R9vtzo53u93vX21/3D1/sfvuu89fnX@x4eef8bd@vnx3@@Hm7ubj9ZfPN@fnaW/7Tbq42D9@/vb61eXpc9un/b9//P76w9/f3OnDtD/w@EV89PP@t7fJS8qzjlpsptTm3G96Wnqq3r30ZnnMxDn60lI1z330PHOZjd8tdrHfnOe8jOkle66zptGrs8LSvXc3GzV78sGih9SW0mebufZRR5nJT0scel/SrDZ6662aFVbPfJ3v8GX@nUfJlTWKc9hhIw3@TjnXx2PMtnjrqQyfXfuW/WYsOZfBV3vqacSGsy51jmS5sNtoeTw@XxfvqfFTW@Z8fFLaYp3NanfWGJMTZFtas0rFZskpt1LXBf5nlw6elplndx7zZK1zroPnZXrq07y21udQyXJa3PrkdCN3Smn1sTxz8llhEU@jtNR7lCd1H210ako9nCVqW2rqY1jzUqnlPK1A3XxkaxRmUKXS@PaBirEYDTaf7q3GhpXiOECYtNSTqvhwCC@LAY860zBWL7pIq8vgDk7lDFR0rToXLpqBVFLh@mOFBYqWC@tbb2MU1e6QTOhJxWizW5pF@OsLrTEvhXPwu35awl1NGtqrttlz0oZlqaV6aZys0xa@3YTfmQwEcodfLgC0U8u9pJK5S0@ZBYbxu1HbaHyTjnJiH4vVnlv26l45x392@ZFsfSzNJ6VMDq6K6kgplsw5WTE3H7WvTa@gyTmpvifk2vJ/cnRSpERFsnpNUdaH6QW7cU1BXJioC1iyWelcz2a696HwbG9cxXICW0OP0snqw7slVgQvKiN9SAW6GbyvpZXgbPUF/gL23pzrqTQpwACZq1aFi5UrNt3QF6ibU82gkkqWUdWJNscEIzSI7cTXg89FpG7dUYOuP1BtofMUJU@Rm1MIXQlK0AVvEyA6pAgJAHFU1MRA6yEicSLojwTlolvOmpPu1FYglTpbNwrCouJvt1lAIqAfgQ19DzjlZuyCXLWxSk0XSuAXG9JEHUg87AOYlUJN1IZDGYukAD6gdXmm8nCgWuELRHBEU@IqqDmnnDkB1VY9W9LmeSw8yGmyvssZ4pZBC/iNnDqgmdHdQRmR4V6sgO/1WdZWK2vnKknl0G2oNdWlHTye5v2JUHq@3Lm6W2sF9VpRCRdpGJSAcNZi947wlVB1KjJCnw7ofKNvMI/tKGfS46wJ1mkR8EL6p7gjHbZG6bzQovRwTigyKF3WBfKpbboVV9eRTFJU4lALMo7x0N@RHG2I21cH75JBBCq7SlcBstVWJfINmA2dE6vqFajhXVLq@74BUaoH/ucoUrVDKQsaxTUsVCZMLk5UMETzhp5wTOTUdaIGFJ2nh8AIt4QulJ2jo9msU6DOag8lwzsE1fTfJBMCzKrhkLjBGfbJoKDQMXBAiUYWNEpdADj34geJcrlNHCjjeRVGDkkc@q0GUQ0pN@6E6qBZMkcouXJHx8Rk0wpi@ocjCgrYYDycQCxMhFM5AColZxNUBJulnDSdP9qFX9LojDVwUPrx0DX0laNzcYiYEGRtlRYOPeaUrVJiD6HBC9CtrHP1iQVKiMUrsa1iU6mblKMjZUVH5lvUQNAWWHMOMxYIcdp4FBPvHBJ7B8E1/2ZAOmgJwJKcAigxqENoNfWSEQ/cYQY6O3Y8JAoQElZGOwARn5qhrjKBGYJLc0phZ0cSYjWBrUrlxwTtADb0iNxBBakA3o7rP4IdC2UPsDmQR@/BfohOG9FjWi4Z0Kpdqw5xx2TEI5oLX0kl0BRMTlHi4JxoohfsZSG7voomiQVpjk6uukXDjeWlZNS8qOT3WFfSQ0rECT5cVZcGIQQQiG7OLshgGCyAiCog4hgpMMhGSAa6QxBi@WAkR1ImYancFQBXM/ZwhZQ7TdOvZB9ZepOgmaTC2knGZSzwHncmZBL7tBMmoroRoUqjpWMFLJbNwsnoLLK5ZiKDQ1U6xlYBdq9KluI5KpFgULDZyDlFBILn2KCvXWsQAFlDzHWdfOqa1LDKQVC6AkYDRY2Y1jkiWPSoB3qPinHsRvRR4VYGsSUdpxLcPj30tqrhqBYoiK@hTxFaVcjh66MkbhN4BLbUTiKuOxLWQIUkKu7YcGnICfExK5nWSnKKPSdlVzocwRUyDIDKlJ6iYyO@RriJiOB6CYZWdeLQCSashK2xiYi@qh3MRFW5NEisJzGQkjbnkl5xSy4QgMPbAUyWyuGWdUW6Bg0yF/mF/5NYT6SNNJZJg2iHKbtBM3y8y/f0aA@xRn4HKkS9sHbIs7oU/CYIwLFKLPV@wlCdqLCuCDARn7LKCSZL7gMydMd0dQzNlAIdU3P6ES5H3azJo4LmzDo9rkNVXabGRnWFP1EUaeFUpAPQIZLTMrQWRSxDY0Q99axC@4ZxSBSAdJNJ6j7UErUxPRMwlwSH5xvxXywFP7mqVFgrNUvBMUirVagwsK4jLNsUYBBkMAbEeXbG/WAYrsG4ZhOVeSgQMKAvfDDUEAJpWavJeMGdDRDNET4F7SkXDpE0PXRxTFMcbKBtU5En9zUEcF7gUxm3KN3Ia1xQbJJKMyFYEI8vNhmG/Duj/P3EMUYXzgSiZ2S9tLbMZDDkIqDEbHmfZqdyAnwqmhpmsD4AyUZcWxaTyYiQyagZ1yFIRIEKBcOFAShUKzNKCfEoj0lZElVfbxgHGugGySvTS5PoBzbIIIaREEXxITmGoImmU0fcRNE8t/uor5TGhskgRcxFuLiSD2eApdKhEHray2SKgkOCEukNEFFwXBSWsrDbQ42U3rLaWEVoprD4dpESgVibukeORInrZklzjQ1drQT@oIwgqkkfbZOEcp0hy@IEor6FiM1FV@E4ParUInlFHbwjBUw5@cQzgjzdxD441lRZ6yp5xk0ttE2yHTFgUgsIVIl5QtyqJzhPIBBwjrTGOfqm4SEx@mMDbfUztYY9wJeotYIQXcDbGDs5KB88IFuTDWqiu2sQTmVtMgcE1Ire3CneJLAsPCN8VWmcr3MAv8SBcQZ004pGDJEf0DZ6gTgjeklQUhTUFEEU1EsTj1rWpCBtCtj5BCNNaVltLEpWNa/xlhyjwMtROtdd66E5AppqCtXMkmJNogphBbLjdRbOKdkR9mGvYlRkFaa0pgfRdpTQIpjXTAyYuodSQ2rlFxkEAQP@Sjo0NU4vVsHWqewHSmKYk7uBVRDNzWLUwQipgV4ioA@2prkirNFXht2sVJ7vR058GUsABR6TJB2TeCbxB4ua5XFuIzGA9WpMMRhsxF68izOvIV7RPqQ1acSRQ6beA9MSQgYx5hHciMgQtSU@oHeKrd6R@XYfypOUgXkESZiyHYDAbugvE8dIp3bJo3BwVkQRukRfpURc9TaEsxSXzrXVNoETRO6Cf9LrIqpYgsbina0zAvUR3Y2Ig94xQK/fq@KRgQnGegq5BskpzvAdgAryHkdtyTVyI@akGrGTArkJBlIXLKDenwjkoUToTcFbAgUYoQZ8FiBN6zZGrlVfaIs6G/FOr9qUhy1SeA29QG2SxojckTps5YQfJlM6DiDAj94KPKRY6gimGf06YA3eAReqaC2wjmHEuzpsUKmJJIVIiInIJ1abXO8F@eq9LivZahoijKESTEuRXgiw7MwFwsd/Hf4f38ggJK4BFbXn5BavZOJ1FwccmimaAgsgbzEqKgomTeShgHqbM5Sdp2DpCtWJkRrjAi0er8/iZZvL7BUf0TmMO943NI0I8BIMVL2UUvp9eMXzxcXy8vb9N5dXf9ve/vX15ngWr3uubt9@uH1zvby5fbV98qe4wWbz/Ml@84c/f/vH5cPd@5u3r25e/mP7cnu@4bHl4b3QPv71MO9sLna73Ve/Xu6bT@@ur@6uv/8vy@nhtV67zbPNk7@8fcLjP@8@/ws "JavaScript (Node.js) – Try It Online") ### Commented ``` A => ( // A = [ positive, negative ] g = V => // g is a recursive function taking the vector V A.some((a, j) => // for each array a[] at position j in A[]: a.some(v => !( // for each vector v[] in a[]: q = v.map((c, i) => // for each value c at position i in v[]: ( // x = V[ // set x to V[i], or 0 by default c *= 1 - 2 * j, // multiply c by the expected sign i // (+1 if j = 0, -1 if j = 1) ] || 0, // t += c * x, // add c * x to t c + x // set q[i] = c + x ), // t = 0 // start with t = 0 )) >= t // end of map(); trigger both some() if t <= 0 ) // end of inner some() ) // end of outer some() ? // if truthy: g(q) // recursive call with V = q : // else: V // stop the recursion and return V )`` // initial call to g with a dummy vector ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~35~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¬[©¹.Δ®*O(d}DÄi².Δ®*Od}DÄi®qës\-ë+ ``` Naive port of the example implementation. Takes two separated lists of lists as inputs, the first being the `positive` list and the second the `negative`. [Try it online](https://tio.run/##RZI9jtRQEIRzToLgudX/Pzk5BzAbgCDYCKGNyTgCl0ArbUBGQDKTI240lGFGOLD07O5X1V/1x4e37@4/XC6/f@6nb6cf9Ovr6enF6@fvP786f7k/fb@er8enT@fHhzfb@fHl5bLvoiQ60WE8IjmzSqgkvNwqWXtkSVFKsGt16ahNLiG@W7sq9bipa0xIV/gqKq9y5g518Z61SZLV5GhUR9uIX9u3KpIJ7srKYLZciloUoBJHbdNYmzksNrc03qIaN/lJ8iyx9qlD0FaTqjXqSkr6UJqgmBZWg06n9q03yEsST6TCVS9L4oJKlKO/J5YyZXKAz5iKpsXf5rtn@7650OiUo8CFs2xtrjQuNeyRWdOgoULONXDQWoDEcRt9Bn8MF7i0pVQdo0t5ZxdgYVj3FUkh1c3pFqA0124Q8VZODN0gYOlrAwzcg8DYxz3jUAoM7oh1EJIL@FzF3YgRdYw0416D@Qxq@HZAYURc63CI0RTLIQeTupE7Ek413MyV3QYqm/CxCGKM2JxlDGtUBNzsZtDHp7q2ux/g@xCJnFKBklFYuCUMFVjXymMFRxiLBN//m7GbklompvBfomtrxqeO7EQZIurlTRylqR7uAf1/qf0B) or [verify all test cases](https://tio.run/##XZjNjl1HEcf38xQjiwWCc0@qqqv6A1mwASRWXhEFTSzhxJZiCdkBO2LFjkfgJVCkLNmxsfeINzK/f987IGFZ9sydc7qrq/5fPV@9ePfNp69fvL//@f3Xb1@@Ot@@e/HV61f3T5/e/@rZr@8@/OMXT37z5tvv3v/s/slx3D159t372zdf/v7z337x6d//fPjw9y/Of/3tww8/efbjl3/55ce/vv7d7dvrdx9@OP748ft3X14@fv/TT1ry7s/fvP7Dq/s/vXrx8v71m7uXb@/u7z97@@37z6473/77v2Ke3v9oP/vm1aeHhwc/7PDnz4/7hwe@0JfP7/RxnB6rZjVb7n2tY/g5vHJkG91iLp4dZ/eyjDFHrGirH37a8@Mh4pwrW2TUKp@j8hjnyDHSbFak51zHxfvZxuorasyabXneXr@Mcfoqm6OPXmatH8GzPMCTfBuzRR2XlpQ4bfrkX4@ox@1XP7MPbzPX0IbtmGdEmzw3fPjUTqvOWtMtGvvMHvPx3TpzeOdP9aCqebR@2mCXGsn7c9URdvZuRX9WC4/ear@8e3hJP1eskTyRbn2045JxrvSxLKv3sSbtCD/TxqKEGYMuWT2efS1@0lggfbbuY@jsPnL2OegWp808qp/lY07r2Yo2rdvbtCRnWOfUkxa0nseFbrAOE7Ncmb20U3HyZK6LKaXToNvm2U5j1rV8Gus2iu91TupOumLMeByqkKMF6HA1ZTy2TiPu0VjZRp@z0ZaLm5DgzZhbmq8GjsZJvy1bY38@GrfXM9X5qU2qrxHOTu2sVtk6BQ2aPY4uDC43kETd/3sZcHqP0bwF9Q@P4zKNj2b12XmMGc0j52k1okdWZrH/dWxXvC8KdcoK9ZjKAJOddKJVsZ2gwyTqZHq2iqaNMGP7S@PF0VnUwpnm5D2aWDlzmLMaQ@IktMEb8DX4U6034b/yhAqAaPR0sE0fNQNoUVoQZNcKcDiOPGFBeAUg4DBtFo3oay4mQ3vYCOxfcp2iRx8JqYb@Hu2k49F6LNGE7RmoAz26kH0x@AR8ohIzTk4mRNsQEVUJNILC0XSwVeGco1@H12r1YXSgHeLCsNUYPfBSefspRhjdWB@y97nJOjQcMMxWPfnIhfQxmWxrNIGOX9o8RSmAh0zE8nYtpApYgrhEaiRITDcpboWDjF4Z5uwa8@Qlqgg9yeY62MYf5EGD0hAEzXDSNIRrNGuAab/IsppYDepnFvsI9JVW0nne9bUrQRV5cnDYtN4b3N/sBu0MBvABauvadqAZbWsgLZhi/AVR7MwHdLMRzXPeZT0oxSxADzK5wKikyzqdysYs/FZeLuQLzKnsuI1HJ@GwKsVE76ZiTlQPcWaI0xPa6byVwFiaAucj6VSBUKteksQOiiblIeajABLiLm27zgf00SxQvWZDJS6tndCe2m2TVx6gShpmYdnhKcWhS0klHZglb04BDbIAHqSRgpE91miwYStpC2iEMpn@d5QakKpjU2IBDw56xOmZDLOmJTOYfqsT3HIW/sB7prQLCRyhoNeUZCCBTILjS/xQ8O6ODGAcEOzKBlWH@fhGJ2PCLjRtTEJvOliEV5AkNvgQQ9ZHCbAfmsdk@csGfMY0A2GlPlp/nQ5CRb0cFVo5usYmflLpXEt@QztTUoGUojqhesbCM9AzEUXsKcTdB4KFd9IvFcoznBrICocR26OEMCxI7@Frg9owPLBZ8WjrFz3M7D05oMySxk@wCH4Ri4mULsFs4FJTTIZMMEptBhL8zAwBlGYuSSI9b40NEh5rJQGHUiURQBbkST3wW7rDCbE7fPARsdgLqwOyiYixEN2Dn8wGvWSIIi8LDi04hX2TQU0NDKbhxTAMdNFAsEQlC4qzi21hzK1s2DTSucezNYYZGitLdOgmKLoBVlkG7gvV/GjLIn2HvRCAES0SiXSclxE65R@E3AUntoDlyATGz8piE6XInFkmhiLOdqnccu0xGAWfSNVD@uCwRPS2ftNYqT1sxbXITwQb9kDa1SYSROtMbm7g4WSs6cb80LadCgwOlCSHTYTYLMUm0RNmOxQQDQ2zb2IA/MSSck@nA2IECKXVGeI2HYlWSdeRpAbYhJJOPhlUBqpSDUCKERyK7di/@rQZwF6MlaNzXr9NsDRVFIZJ6yHEZIcxtW3mfo/4aAKHoOT9prA6FimFuUtPdKyOT0Ir6Ip5yEQ2N@nrWnRYgWgK7Hg5eAm6TH8R99zZZUF7HMghFyilNOOQoC@c9UXQLUuQCuHjnMCsbgyW2PXkXFnYFlULTVgriAjJEbZVG8DKySQOIgNfIaULESKKBBEIuqNmog1GOuRBem9IStHHiWbQHqwVPmzbgKm4MJwpQliOG0ZqoZI6FZhDK9rmP1ZH3AETjAGfPbAXU/ZJLCbpvCyHNlmXZ2y@ktGHzkALUxbDFrVBTfJCHagGZwYAsJXRoIYIV5tKwnWbTUHfjpyL2kC141Y6A41DLkwvCL2SyO24RqyFceAjSp3B4GiRizMQUCvQTuBaU6ZpygwIJggCuby4dCYYg5hzt7CFUFwbwqQZAB9PtT5TMZXWkZg5pQGSNeUb0JfuINyuTAzJJCSQpRjPUsSIsR2YKoFHcUGgUzO2UyuiSENJviYe8ViXjstAA00eN84QxKkFpK6dpnyPxiT6pBCgwv3nmhGXLBqCNIXhJfZurLEFB0X2gwgGO4wWcQYsXA1p9AcnBHtQpy01Dh7RDpM4OB3ep1IhE@6TcIKJmQRa08f5Db0n4@EMknZQhwLTNURfKRdc7/yiLMRWbiBdCR8bVdBgcygnHZEqM0SuTggu0G6KSICE5uJmUI5F2fxqwuSI0LBK1OQmoUeblAQs2lLxobiG9YW0tPZWRKADUIMhIp7uncgSwscZpjyFrUVhkwKtU/VTxthd6Yo4@@Q5YDR3nbjxhkDMzJB5ylnqYW2xMg5nW5Yks/LgxeGhRJGkhKctCdjDhhe4m74jE/NR/HYuokh2336jGbA88BFXNsJgN9bDbYn6@PyKWF0JEASdVtc2b3uS1AVYlWM5h660rAhvCDklecodpvkMX0TDkTtriuiQGDh2uo6aIldc4XfWUg4na@nCnupcuYKpKa/GDSa604SG1ZRhwHzf9F8KkZQwOOFugII4lNPlSXnftRyBgcgAa7Eik6dJN4RomKjIosTAnabrLZQYCTNl3Apceal4Wbj39t8sgPiAaWUNRqeSRROYtxSuwIEuPjIfUAhSOY2uCLgUh9YNF5bbTkxNSGJ6XB5DATeutzLMEvVm0oolmowkz0UJXIQLy82AcW8QXEb@x/iUJDEXCr2GYSVkyaHraiDz4kYurErBuLcQ5jEM/FuNxMpRKqXB5LIPb3a@dfGbMA@zF97ArNkHySSwk@hvUR4XwVNZDF4PCTR9QxB1PaeGlpKovg0NtEDJIVB7m@pZ24QUjWzHbPoh2hohA6XiXrmfKhHDGDvXXNq2c9sSDXgCDAKrx/un5BW9EBdc8V8NSdOkpQ@odV0rAVUoCYLBFVkL8sm@7vI24ZQjGPFRA6D/mp8ylX6Po8xpO9GWSI9euHJ4DFQK9b/hg5sbU2Xk4EMX5FtapGlglTvSAIaiEXigZ9Y3hFF2/RIIj1JmIcZAdXiF6OGAnvpVEw9ehVQBUncIUhBc54qhCEFQZE/K3tZ6/W3YfwA). **Explanation:** ``` н # Get the first tuple of the first (implicit) positive input-list [ # Start an infinite loop: © # Store the current vector-list in variable `®` (without popping) ¹ # Push the first positive input-list .Δ # Pop and find the first inner list which is truthy for: # (or -1 if none are truthy) ® # Push the vector-list * # Multiply the values in the two lists at the same positions O # Sum this list together ( # Negate this sum d # And check if this -sum is non-negative (>=0) # (the `(d` is basically a sum<=0 check) }D # Duplicate the result of the find-first Äi # If it's -1 (thus none were found): ².Δ®*Od} # Do another find-first on the second negative input-list, # but this time with sum>=0 check instead of sum<=0 DÄi # Again similar; if it's -1 (thus none were found): ® # Push the vector-list q # And stop the program # (after which this vector-list is output implicitly as result) ë # Else (a result is found for the negative list): s\ # Discard the positive result from the stack - # And subtract the values of the negative result from the vector- # list at the same positions ë # Else (a result is found for the positive list): + # Add the values of the positive result and the vector-list together # at the same positions ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes ``` 0~LinearOptimization~{a=#~Join~-#2,-1^Tr/@a}& ``` [Try it online!](https://tio.run/##XZjLjh23EYb3fooBBHg1p1NFFlnkwoDWRoBkkZ3hwIPAhmchORC08mD06sr3k32UaQuCL@d081L13@p8ePr8@68fnj4//@fp628PP3y1L39//vjr06d//Pfz84fnP/nij49fXp5@ePflxz@eP365vSuPN//3vz797f3T6/df//np@ePnn3776d27n39@@P7h/fv3373wxx8f7PHBX18fH15e9F/rf14fv3vQl@XwMtto1aZ7n/OXx4f0I71FRs1uZUznM8@je7MoObLMUmfXh8cvWubh4aWUY8yoJUqbzUe20DpHRmaYjVbCY2jtm/ej5uyztBxt1OlxWeiWefhsNrJnb2ZV@xTe4UHe4IMyamlaqQZHHzZ88E8vpV2PNPsRPb2OmKkjVL4dRyl18Hx6@th7z3a0OdxKZdfRy7iu0o5I7/xpvXBefVv7Ycm@LYOVxtRpih29W6OWsxYvvbZzmbXOy8st/JhlZvBUuPXUcW5Rjhme06L1nnOsshU/wnJyqFGSelq7VmhOvq8sFT5q98xdIc8YfSS1pSKhhVo/mucY1qM2Cjov61C@GMU6tRkUqna9cqNqrEnXLWZEb3vvRn0CfEx6HL5K@eZAUQ8DOW36MPap62q9HYNbBdUz8JJr8Xlw@QLeXMXLa6kFl14qO1n2Meoq4c1NyPJq9D7MZ10IzYNOWdTKmfgwLwtFqGdD27Y@s/jaux6ttqidYyZN0itdOJ9uYJRb/XUZaOC9ZPVauF160TLD@HC0PjqP02VdIcZhLUsv0SIaZ7q3/s6xyRWc4xb1hhMvoNpBxWprbC9Ari62AwzYbBQ5i9k60K3yenaWt@JgYqy3KXmLEWnOqrR43ZFSeYUmBndb7XUzrsUB/QBm9nBYtKp@7x10bFocHrVZQLm2jAPmFW8FQHHNOtoqVp9j0lOKyLaLbbeYh0jZM6B06q/4cdClUnuZIifHWYBwYE2Vok8AFAB7kxiUBHcWbyy3GNzPBoERlFJ17dmKrzv23fraZk@jRlpb3EubFfgA2rEbqSdpf@nGbshPH6dopBoKT9i4x/rQxagc4KJWyrT6c6vjEJWBM/JVpte3R2sNyIPkQBAlnQsbwYFncRDWWxTzdYoyDl7nXEVPc5h97YVqCItShiFRu/uD4iKzWa0CzPN1NlCnW3IvXxXS1egBRadPrODzzdlQdN5IihHWe0WLTqWBU7QTOEMb6/sYiZLVpdwUaWz9uSHmna7CHralyL5WYF1oTP/AIQI/F/IlsdapZ1T659@OHBOZBcO6TLk0VbekGDqcSWbqPt6BTmM1QGB4QPZdjxZQRFqH@pRY9Wwg31pvkvEOHsc6MvaUDVBiWFLhe1fBMyWFM3PUpVq3Wg/khzvZko7tbfezVczQoqMRHBrljHW2DnCDNYagCy0XDJFzroFMs1qFc6cH1AJpUU7Tv305DvBXZYekC6ZpvwJOKv0EKZRtlIWe2g44wS35g@7EspX70Qpe16D0kIAh2Kt7FEhSjRd1d8Ro2SKE3qzTiTFZP1FPezFC4QXz2@87CIfH0LEsMC/hZif0CJOlyKCCv2srPgUJBUPgzDTqbU@RUW5CKSCyo7xrSz@4w5hTnkrxY8sWBoASFp0wJ164FFeUFFMbRuVpS4ISdaw6Ps9RlUUGIbuU5cTCKya738bHk/Ni8eC9rQp/s129Ano8uLyCwmrUAN8wA9kaSP/csE28eEhFIC7s3U0BVnxvhkhL3ecWbnpUK5sFGrJXFAA5voQKKoDjrWTkDSrI3TF3fP/KBGyTvQDtQGIjt1qgC/QTbQcAko21eGrxIX6ZLHjsNsNs8gh8BqlzMeYWnG0iMexpS77jVF7CCiK/WnpqHr039pAMUvW6iv5/IigBokBiDQ@cAk6fUA5IRltnLgzhQyyDFCs7YkS@gcmGqAyCRRRil81cDqeAwnIlFQtPB45lNF6S5q3P5ElFKuUwUeJi/eIKcix0Ak8mhRIG146Yk4pJuqqdjo8Tyjg167vRebT3TEoGz5pEkC03E6IpdEoW0BWHYpv4RvCpYhiagNXG2dMOPRBFvEF3K5eeSlCbnAmprIB3o62T5JLTgtHYJcJAkECu0AlDqubJMvYGEhSHevi33jchAsUDJ/tBpG2FWpV3xPk2Ed0EMsHS@8UTdGnSHNiRuu1Ld3IBREYoMEOZ4qkJ9GFOOqIYOTadHM2lmXSFfmBPcSa8ifDgrA6V2@rSLY0CgOfi7CRROMUSCiPO1ADQtot6SJJ7cOto2DL32egkUICrIpnElttJDs0qJDEiFP@1pH8ijIS0QmBEbmzlOihKcEh5q97OLf3o@EC/KCJhAs6dFohCkD/gZyPCRl6w1iaKrjuDY1SrniqEoRMLQRats1UMLNOUEgPbDHq1jZRiWpcHLq1gbsp9N4odsk02bCdlyKyoFOcjlQCgpRQ0FM1GUuvQ/NEuHW2IR8eQJC@QoC831v0oMuJlenEzQ3K@koYxSiyeg7PSVD9snEL65iek10oUHiK0sSOCKUMh7aARVvD63LeFnVgRc6BNBOtt0cAKTePLoWZF7HGAMjOvUAUDbHNsH0Q8qCHG45pEcvFT8yEUoqlT0avkmT04OzBrjG/Uc5QzpyjCSfOZNGyzlke7XEiBoeAleeEnIxGngwNzpVA/G2qyLhIakGN@vafuqYACFavGj7m1Y@GXDSnEMq9CgIWHRiG5GxFmF61SRTwfNEPTOneBYS0lM4mU043zvvejDTSILFjotsleNoLIQIZvkZdxOdnTQjLOQXUxL80TpeeZ8JQc2dgNJu2Ji9igCMZhILl0bfsJ7Wf8xSYgTt2RErDRCNwakrN42Nu6KVIWNbpJFJjz9itVygbCbepaZQdeLL5I/dvaOFanoQx4JCrrlwYkc8kzdxtySo4iAbGti/PQvThYrsr1HQRXXSJRFKbTcuEoIwj9xqw44FS92ymlxtVtSaasYaePSXmgXiN9CpunOGF1C6xgefgZMumqhh@vACW3tiGD6hsbAUSx8sQr@oKpMudyZr55ywWNaUiTqqFB3OuJA84KDTQtcMf9cwarw1HiYJN0xjnE8CkpABdCkq1qTFoSAsg7fUL/EVNfkFNG1RRERtVPObEr3Fyx3zQPlAvcNH8WNboq6cGrfsrQVDTnUMn9zxJpFILoGno1e/lemghFiEIxMFnbzi0VE19gvyLdzlDMn13v4iBIrO1pohUyydSlFGK8178kI2QR1iiH0fZ9GRESvk/FUrC0B1XZKtiGA9x0D254MGXR7xrojJ0ZswqV9N0RaI0S5T5ZEw7wHnASe1ymnxJmF@1wxVmvIykZBoY0YyLD4ndGxzK5wh4/NJVs6XYNbDJoz9wskMIyYTJWYYEkmF1y4gw6qnQdiZv0@yThUhjGKpRlLp8DK@yJvDM0Db80U85IlmBhtCVlL6vGiLd@sOFUNSSf/bRtcIcYpCjj6xctaluXFIi0do441EyiYQQwdDRYfD/ZREEDNmMqcJ3pd4pqPAWqAen1NwZZAuolznnbgZmihQkr0ircpt3PBk5RNuSrYmUbKniwfuJgDeL/upoRy9U0eqbO7yyqXwmV6G1NDm0LD8rlmoNKop@42AVnTOGgAtiAM/048i2DU2BYwGybgHuTFlRRW@uLHrjT/rERB1auI@whNovHSDNu76EfOHn4Lv0K5pruSI2oDePfjlXEb/bnMitO7Mnl9fXr/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~41~~ 39 bytes ``` ≔⁺AEA±ιθ≔§θ⁰ηWΦ講ΣEκ×μ§ην⁰UMη⁺κ§§ι⁰λIη ``` [Try it online!](https://tio.run/##TZLNjlpJDIX3eYq7vEhQsl3@VVZRpBllkSjSzA5lgRIUUIBOGjozb8@cIulmWHBVZdfn42N/3m0ePz9sDtfrm/N5//U0fzw8ned3p@9Pl3mxnN5vvt8PH7ZfN5ftvF8scPixeP3q95M3l3enL9t/5x/LiRDZIfLPbn/YTvMf@8Nl@zgCHx4u85@P2804/vV0nAf423L6e3/cnufjcnpm7JbTaXErQOMzBLx9OB43py8jdBP37Z79/N3/qnzAi9evPj7uT5f57eZ8mXc4X6/r9ZqlsZSldSpmr1pOwS3YNLSHk2TxcuJozkYqkSElvRx3jT4tp7VIy9IuKlbGGaYgtNAIJUoTZU1AV@ytR3mJRVr2Yn1BrCIal1GGhxtRB12Qjhwk4yzZxcDoCrFJyYl/FrG7jPKmHtxTK0bdvpyyifREanBw3gqWNatkko5q6ZL399Y02PEzF@hDpHujQDELBSMLCoSaOxkcqy4s3u0XYBDWK@VWUqFIUSYPaFiptFKOIjX3qBz2CDelKChJCdhGdreiCrEOiHJ254ibFRyangH/0LsCYd6MI5Ncu8G3eiHAI00hhwkJR7ojewV3AMMwSUvV7VbQYIRi6IXxKQ/HnkVob4RVsOIk0PtoxK0lelC4RNiAGNRqaFSwPjxMirubYwFcOvgUntmHTyumsSncCSNV4upj16JhDKS9Qwfu4gWhOgaSo5Z5hfAo2Jt10@5QFhgBsn3sajFh29DD/wFYY3aJzl3QS7AAkIS7NE9HJqYHxZqNLMRFTdWg4/dEP11XPw//AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁺AEA±ιθ ``` Concatenate the two lists of input vectors but negate the second one. ``` ≔§θ⁰η ``` Edit: Saved 2 bytes by stealing @KevinCruijssen's trick of using the first input vector as the initial output vector. (This works because a vector of all zeros incorrectly classifies all of the input vectors so the first step is to add the first input vector to the vector of all zeros.) ``` WΦ講ΣEκ×μ§ην⁰ ``` While the list of input vectors that do not have positive dot products with the output vector is not empty... ``` UMη⁺κ§§ι⁰λ ``` ... add the first such vector to the output vector. ``` Iη ``` Output the final vector. ~~34~~ 33 bytes using the newer version of Charcoal on ATO: ``` ≔⁺A±Aθ≔§θ⁰ηWΦ講Σ×κη⁰UMη⁺κ§§ι⁰λIη ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVO7jhxHDAyc6R8MDBTNAbsNks0nLhIE2FAgQYCdLS5Yn9a6hff2pNs9W_-iRIEM-yP8I_LXuPqenmAGTVYXi0XO57_PL9bX51fr3Zcvf94cf13mt39eHA7b9_v57e7mML_af7g5zieL6c3m_fq4eTifIPLx5PTZPfTF8dX-3ebT_HExETIXyPxxsd1tpvmH7e64uR6JN1fH-cfrzXocf7q5nH_eXm4O828DfTKu4Zlerz-8vLq8XO_fzReL6VYAAA_sD9_tXZUdbpw-e3u93R_nl-vDcQbR6dfDL-eH-07-Wj1f_r57fvbvd9-vViuWxlKW1qmYvWoxBbdg09AeTpLFi4mjORupRIaU9HLEGp0tppVIy9IuKlbGGaZgaKERSpQmypogXbK3HuUlFmnZi_WRYhnRuIwyPNyIOtgFcGAAxlmyi4GjK8QmJSfeLGJPMsqbenBPrRh1-2LKJtIT0ODgvC1Y1qySSTqqpUs-3bemwY7HXKAPme6NAsUsFBxZUCDU3MngWHVh8W53BINhtVRuJRUKiDJ5QMNSpZVyFKm5R-WwR7gpRUFJSsA2sicrqpDrIFHO7hxxawWHpmfAP_SuoDBvxpFJrt3gWz0ywCNNIYcJCUe6A72EOyDDMElL1e22oMEIxdAL41Mejj2I0N4Iq2DFSWDvoxG3luhB4RJhA2KwVkOjgvXhYVI8uTkWwKWDn8Iz-_BpyTQ2hTthpEpcfexaNIyBtHfoQCweKVTHQHLUMq8QHgV7s27aHcoCIwDax64WE7YNPfyfAGvMLtG5C3oJFhAkIZbm6UBielCs2chCXNRUDTruJ3p297f8Bw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: Saved 2 bytes because Negate fully vectorises. ~~Saved 1 byte because Times fully vectorises.~~ Saved 4 bytes because Times can pairwise multiply vectors. ]
[Question] [ Inspired by [this](https://codegolf.stackexchange.com/questions/237085/swap-every-two-elements-in-a-list) question. ## Challenge Let `L` be a list of `n` distinct elements. Let `P` be the set of all (unordered) pairs of positions in P. Let `R` be a result of applying a pair-swap operation on `L` by every pair in `P` in any order. Example: `L = [1, 7, 8]` `P = {(1, 2), (0, 1), (0, 2)}` `L = [1, 7, 8] -> [1, 8, 7] -> [8, 1, 7] -> [7, 1, 8] = R` Your task is to output every possible `R` (without multiplicity) in any order. ## Constraints * `L` can have any length, including 0 and 1 * All elements of `L` are guaranteed to be distinct ## Examples 1. Input: `[1, 5]` Output: `[5, 1]` 2. Input: `[0, 1, 2, 3]` Output: `[3, 2, 1, 0]` `[1, 0, 3, 2]` `[2, 3, 0, 1]` `[3, 0, 2, 1]` `[1, 2, 0, 3]` `[1, 3, 2, 0]` `[2, 0, 1, 3]` `[2, 1, 3, 0]` `[0, 2, 3, 1]` `[3, 1, 0, 2]` `[0, 3, 1, 2]` `[0, 1, 2, 3]` 3. Input: `[150]` Output: `[150]` ## Rules * this is `code-golf` challenge, so the shortest code wins * [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/) * [default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒcżU$Œ!y@ƒ€⁸Q ``` **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//xZJjxbxVJMWSIXlAxpLigqzigbhR////WzAsMSwyLDNd "Jelly – Try It Online")** ### How? Since the elements are guaranteed to be distinct we can swap pairs of elements rather than elements at pairs of indices and otherwise follow the description in the question. ``` ŒcżU$Œ!y@ƒ€⁸Q - Link: list of distinct integers, L e.g. [1,7,8] Œc - pairs [[1,7],[1,8],[7,8]] $ - last two links as a monad: U - upend [[7,1],[8,1],[8,7]] ż - zip [[[1,7],[7,1]],[[1,8],[8,1]],[[7,8],[8,7]]] Œ! - all permutations € - for each: ƒ ⁸ - reduce by, starting with L: @ - with swapped arguments: y - translate Q - deduplicate ``` [Answer] # [Factor](https://factorcode.org/) + `koszul math.combinatorics`, ~~60~~ ~~52~~ 65 bytes ``` [ natural-sort [ reverse inversions even? ] filter-permutations ] ``` [Try it online!](https://tio.run/##JYyxDoIwFEV3vuL@AAQ0LDo4GhcX40QYavPUBtri68NECd9eC07n5N7ce1daPMfr5XQ@7hDoNZLTFND58B17WCVPdMSO/l5ob2/GqbQxOmBgEvkMbJwgeBbjHthn2YQJFWrMiWWyDbarV3WZOMcG6WFk1efLCA2Y3sSBYNxC411AStwBLe6mF@J8ILajKFm7Nlo1oIg/ "Factor – Try It Online") Uses the following observation by @xnor: "Alternatively, these are all even-signed permutations of the reverse of the list." (Although I found it actually seems to be the reverse of each permutation of the list, not the reverse of the list.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œʒRøãε`›`›}OÈ ``` -4 bytes thanks to [*@chunes*' corrected version](https://codegolf.stackexchange.com/a/250428/52210) of [*@xnor*'s insight](https://codegolf.stackexchange.com/questions/250419/swap-every-two-elements-in-the-list-every-possible-way#comment558243_250419): "*These are all even-signed reversed permutations of the list.*" [Try it online](https://tio.run/##yy9OTMpM/f//6ORTk4IO7zi8@NzWhEcNu0C41v9wx///0QY6hjpGOsaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PTj41KejQuuLDOw4vPrc14VHDLhCu9T/c8b9W5390tKGOaaxOtIGOoY6RjjGQZWhqEBsLAA). **Explanation:** `øãε`›`›}O` is taken from [my 05AB1E answer in the related "*Parity of a Permutation*" challenge](https://codegolf.stackexchange.com/a/250434/52210) (which could alternatively be `øDδ›Æ0›˜O` for the same byte-count). ``` œ # Get all permutations of the (implicit) input-list ʒ # Filter it by: R # Reverse the current permutation ø # Create pairs with the (implicit) input-list ã # Cartesian product of itself to get a list of all pairs of pairs ε # Map each pair of pairs to: ` # Pop and push the pairs separately to the stack › # Vectorized larger than check: [a,b] and [c,d] → [a>c,b>d] ` # Pop and push the pairs separated to the stack again › # Larger than check again: a>c and b>d → (a>c)>(b>d) }O # After the map: sum to get get the amount of truthy values È # Check if this sum is even # (after which the filtered list is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` 2ḋṖƛ?$(nnṘĿ;U ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIy4biL4bmWxps/JChubuG5mMS/O1UiLCIiLCJbMCwxLDIsM10iXQ==) Port of Jonathan Allan's new Jelly answer. [Answer] # [JavaScript (V8)](https://v8.dev/), 76 bytes This is based on [xnor's insight](https://codegolf.stackexchange.com/questions/250419/swap-every-two-elements-in-the-list-every-possible-way#comment558242_250419). ``` f=(a,k,...p)=>a.map((v,i)=>f(a.filter(_=>i--),i-~k,...p,v))+a||k&1||print(p) ``` [Try it online!](https://tio.run/##bcrBCsIwDIDhu0@xkySYhk09CNK9iAwJw0KcSqilp@KrV2XH7fh//HfJ8h6jWnL5VGvwIDQRMxv6XvgpBpBJfxFAOOgj3SJcfa/OIan7zC9lxJ2UMm27UizqK4FhDXBpBzw3M@Dm39QthfZrRod1peOA9Qs "JavaScript (V8) – Try It Online") [Answer] # [Python](https://www.python.org), ~~124~~ 121 bytes ``` def p(a,k=0,t=0): if a[(i:=k):]: while a[i:]:c=[*a];c[k],c[i]=c[i],c[k];p(c,k+1,t+(i>k));i+=1 elif~t%2:print(a[::-1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVFBbsMgEFSvfsUqUiVwSGW3jRo5pS_IDxAHgnFC7BiCsZpc-pFecmn_1L6m4LiNugfYGYZl2H3_tCe_Ne35_NH7arb4OpWqAosEqWlGPM1wkYCuQDCkC1rjggcMr1vdqMDpACVlqeBLyWpOJNOcxoVEuLRIknqaEz9F-qXGeKmnNE9ANbp687f3hXW69UiwopjlHF8MfN-oypk9aK-cN6bpQO-tcR7SJDrboGN0FOIAFDrlER6QC8iJdqNQo9qgubBdYINxssNQGQchAd2CdabspUeOOBz_pp93fJAPmkGh3L73wmvTdqgbH4whY8H0yP-IeEWQdbykC8lE_Pk69mAdM3EVHu5EWSLf20YhOdpzyveuhUOSxDKrWISxfJ5xAiwnMB_3JwKLmGYEAron8PAfEXjkw1gsWsXCl7Z2oWmqRCzdBJbj68GEUjoZu_079h8) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~86~~ 36 bytes ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻⎇﹪λ²⮌θθκ⁺κ⟦μ⟧υEΦυ¬﹪κ²⭆¹ι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY69CsIwEIB3n-LolEIKWhfBycWtUqxbyRBrbEPTRvMj-CwuDori4Pv4Nl78OTgO7r777k73quGm0lydz1fvtsnk9ci9bYinULJ4OthqA2Qfw8xaWfek8B3J-C6MQ8lk7y1ZCdNzcySZ3niliaKQxhSW4iCMFbhMIWSLmSvEW1R3LMag4PFEbmTvPta5VE6YIF9o99e1QRfYwiFYB25EQWJrerHryv7-vpVRclARe5blkAISKYUxY9_hGw) Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻⎇﹪λ²⮌θθκ⁺κ⟦μ⟧υ ``` Generate all the permutations of the input, alternating between even and odd permutations. This is based on my answer to [Hankel transform of an integer sequence](https://codegolf.stackexchange.com/q/260324/) but operates directly on the input instead of a range. This works because the elements in the input are guaranteed to be unique. ``` EΦυ¬﹪κ²⭆¹ι ``` Pretty-print only the even permutations. ]
[Question] [ In this challenge you will write a piece of text which when viewed from two different angles will create two different programs. Your string as viewed from above must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from above. Additionally your program when viewed from the left must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from the left. A string **viewed from above** will be the first non-space character in every column of the string, or a space if no such character exists, in the order of the columns. Here is a Haskell program that implements this: ``` stitchZip (' ' : b) (c : d) = c : stitchZip b d stitchZip (a : b) (c : d) = a : stitchZip b d stitchZip [] x = x stitchZip x [] = x main = getContents >>= (putStr . foldr1 stitchZip . lines) ``` [Try it online!](https://tio.run/##fY@xCsMwDER3f8VtSZZA10Ky9BO6tXRwbDUxdRwTq@C/T2UoJF16i07HQ5wmnV7k/bYldmymm4uoK1Q4Y2hQG5m2QYdidmKAVQde/9IQXv/h7w9kQfIhyiUskZq1C@JG4ssSmAIn9H2HOr75yitaPBdv19PheAvvAqVGXjAAgTLmCFIYFb7Sxa1KSQ3s8rIsHw "Haskell – Try It Online") A string **viewed from the left** will be the first non-space character in every row of the string, or a space if no such character exists, in the *reverse* order of the rows. We reverse the order of the rows since our left hand would be towards the bottom of the string. Here is a Haskell program that implements this: ``` stitch ' ' y = y stitch x y = x main = getContents >>= (putStr . reverse . map (foldl stitch ' ') . lines) ``` [Try it online!](https://tio.run/##RY1LDsIwDET3PsXsaDfcoN1wBE4QtaaNcD5KDEpP3xpUwXjzZkYar64@WWTfq3qdVlzsNgzY6Aza1zai4Hw0WlhvKSpHrRjHAV1@6V0Lrij85lLZKLiM7pFkFvxneyvER669PZsABjeEDCYshFPuQ4UI8y8yiZl0AA "Haskell – Try It Online") Your program may use characters outside of that ASCII range, but for layout purposes all characters (other than newlines) are considered to have a width of 1. As a side effect of how the views work, your programs cannot have newlines in them (although your string almost certainly will). ## Scoring Your score will be the number of non-space characters in your submission plus the number of space characters that appear in the two programs. For example if your program were: ``` sc e ex mp e g a r d l o ``` you would score **16** since there are **14** non whitespace characters in the submission, and each program (`score example` and `old rags`) has **1** space. Your goal is to have as low a score as possible. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score [9 + 0](https://github.com/DennisMitchell/jelly/wiki/Code-page) = 9 ``` Z ⁶ € ɗ o Ḣ ḟ Ṛ Ỵ ``` From the top: ``` ỴZḟḢoɗ€⁶ ``` **[Try it online!](https://tio.run/##y0rNyan8///h7i1RD3fMf7hjUf7J6Y@a1jxq3Pb//391dfUYruJkBYVUhdQKhdwChVSudC4FKEgEsYq4uFLgIkCQA@TkA7UBAA "Jelly – Try It Online")** (or see it [self-operate](https://tio.run/##y0rNyan8///h7i1RD3fMf7hjUf7J6Y@a1jxq3Pb//391dfUYLoUoLgUIAApCmUAVENbJ6WA6H0QCNXOByPlcCg93zuICGgnUDwA "Jelly – Try It Online")) From the side: ``` ỴṚḟḢoɗ€⁶Z ``` **[Try it online!](https://tio.run/##y0rNyan8///h7i0Pd856uGP@wx2L8k9Of9S05lHjtqj///@rq6vHcBUnKyikKqRWKOQWKKRypXMpQEEiiFXExZUCFwGCHCAnH6gNAA "Jelly – Try It Online")** (or see it [self-operate](https://tio.run/##y0rNyan8///h7i0Pd856uGP@wx2L8k9Of9S05lHjtqj///@rq6vHcClEcSlAAFAUygQqgbBOTgfT@SASqJsLRM7nUgAaxwU0FagfAA "Jelly – Try It Online")) ### How? ``` Ỵ Z|Ṛ ḟḢoɗ€⁶ [Z] - Link list of characters: Ỵ - split at newline characters Z - | top: transpose to get columns Ṛ - | side: reverse the lines ⁶ - set the right argument to a literal space character € - for each (x = column (top) OR line (side)): ɗ - last three links as a dyad - i.e. f(x, space) ḟ - filter discard (spaces from x) Ḣ - pop & yield the head (first remaining character or 0 if none left) o - logical OR (with space character) (replace a 0 with a space) - | top: no code remaining Z - | side: transpose (at this point a no-op since we have a flat list) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 score ``` z .T. ; d + ! \ D < h m s _ ``` The two programs are: ``` smh<D\!d.T.z ``` [Try it online!](https://tio.run/##K6gsyfj/vzg3w8YlRjFFL0Sv6v9/BQSo4oKxgFJwtjWMlQJjaEMZihA6Bky5gEgbIJHBpZDLVcwVDwA "Pyth – Try It Online") ``` _smh<D\!+d;.z ``` [Try it online!](https://tio.run/##K6gsyfj/P744N8PGJUZRO8Var@r/fwUEqOKCsfRC9OBsaxgrBcbQhjIUIXQMmHIBkTZAIoNLIZermCseAA "Pyth – Try It Online") I attempted to make the code as similar as possible between the two programs, hence a few inefficiencies in each. Both programs filter out unwanted spaces by sorting the rows/columns by if the character is less than a `!`. Since the sorts are stable this preserves the rest of the line. The rest of the programs are fairly straightforward. The main save that I think could be made for this approach would be to make the code that converts from empty lines to a space more similar. I haven't found a way to do that that isn't wastefully long. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 31 + 2 = 33 ``` & ) # @ / ] & 2 # > - " " . / # [ d l o F ( @ e s r e v e R ``` From the top: ``` Fold[#/." "->#2&]/@(#)& ``` [Try it online!](https://tio.run/##hVDBasMwDL3rK4wMpoUkHj2vwTDWc2mPrg8mcZNA0hTHlMJYrzvuU/cJmb11I6EpfWCh954tWWq0K02jXZXpfr/sV22dS8oTJBindMEUFzP69fkxZ313rCu3XOt8UxWlEy@ltjpzxnaSXrbOVodiG25ccHdAxRPyFKe@CgOAtTedRHxO9/I1K1tJI8QocMoU44KqEN/gp4PALiPEEHMmzZEYKIBcoUNmAfJ/xaP2pMUI/h6TO2Bwx5hPGmHmCUPcavxGUvCg92LM6YimQxYPyA4BBvk1S2D0jd9aMsSwJr@dFlZTE85AgIEOrI8nfzYI7/03 "Wolfram Language (Mathematica) – Try It Online") From the side: ``` Reverse@(Fold[#/." "->#2&]/@#)& ``` [Try it online!](https://tio.run/##hVDLasMwELzvV4gViAT8CDk3RhCac3COig7CVmyDHQdZhEJprj32U/MJrtSmxSYOWdCyM6OdlbZRttSNslWm@sOqT/VZm07z2aatc0HjCAmGCV0yGXM6Z313qiu72qo8rYrS8nWpjMqsaxH0srOmOhY7f@OC@yPKOCKLMHEODAC2TrQC8SU5iNesbAUNEAOPKZPMuUuf3@FnAscuI0QT/UaaE9FQALmF8pUByP8ZF7UDLQbw10weBIMHwnxSoNevzwmB33PxHSXhyezlGNMRTIYoHIA9AgzqWxXB6Bm/XsJnvya3nRY2Uz@cAQcNHRiXz@6kCB/9Nw "Wolfram Language (Mathematica) – Try It Online") Takes a matrix of characters as input. If the rows are not guaranteed to have equal length, add another \$18+2\times2=22\$ by replacing `#` with `(PadRight@#/. 0->" ")`. If input must be a list of strings, add \$11\$ by replacing `#` with `Characters@#` If input must be a single string, add \$29\$ instead by replacing `#` with `Characters[#~StringSplit~"\n"]` In these cases, if lines are not guaranteed to have equal length, add an additional \$15\$ instead of 22 by replacing `Characters` with `Characters@StringPadRight`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), score ~~22~~ 18 ``` κ→ P ! K K ‹ ¿ ι F ← «J⁰¬¹ S W ``` Note: This is designed for a pleasant input format i.e. at least one character on each line, then a completely empty line to terminate the input. Replace `W` with `F` and `S` with `A` for a JSON-like input format which allows for empty lines. Additionally, the variable width characters that Charcoal uses (even in a fixed width font, sigh...) mean that the columns don't quite line up nicely. Check the output of the sample link for the expected result. From the top: [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1OhmovTqzS3ICRfw0BHwS@/RMNQU9OaizMtv0hBI1NTITNNQcMntbhYIyA1NVtDU0dBSVEJqCsAqL1EI1vTWiE1pzhVwTe/LFXDKigzPaMEqLn2/38FFHBu16O2SVyoYu/3bEAVUeRClV7NhZP7qGEngndoP5x9Di78fs8yGPNR2wQg89Dq93tWPWrccGjNIaCi93s2c73fs53rv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS« ``` Repeatedly read the input. ``` J⁰¬¹ ``` Start at the top left of the canvas each time. ``` Fι ``` Loop through the characters on each line. ``` ¿‹KK!κ→ ``` Output the current character unless it would overwrite something already there in which case simply move right. From the side: [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1OhmovTN78sVcPKJzWtRNOaizMtv0hBI1NTITNNQcMntbhYIyA1NVtDU0dBSVEJqN63NKckswCou0QjG6i89v9/BRRwbtejtklcqGLv92xAFVHkQpVezYWT@6hhJ4J3aD@cfQ4u/H7PMhjzUdsEIPPQ6vd7Vj1q3HBozSGgovd7NnO937Od679uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` WS« ``` Repeatedly read the input. ``` ← ``` Move left for each character, thus reversing the output. ``` Fι ``` Loop through the characters on each line. ``` ¿‹KK!Pκ ``` Output the current character without moving the cursor unless it would overwrite something already there. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 10 (10 non-space [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) + 0) ``` ø q н « ð Û ð ε R B . ``` Outputs as a list of characters. Top view: `.BøεðÛð«нq` [Try it online.](https://tio.run/##MzBNTDJM/f9fz@nwjnNbD284PPvwhkOrL@wt/P9fSUmpOFlBIVUhtUIht0AhlSudSwEKEkGsIi6uFLgIEOQAOflATQA) Side view: `.BRεðÛð«нqø` [Try it online.](https://tio.run/##MzBNTDJM/f9fzyno3NbDGw7PPrzh0OoLewsP7/j/X0lJqThZQSFVIbVCIbdAIZUrnUsBChJBrCIurhS4CBDkADn5QE0A) EDIT: I now notice it's very similar to the Jelly answer, although I've came up with this independent.. Great minds think alike I guess. **Explanation:** Uses the legacy version of 05AB1E because the zip/transpose builtin `ø` works on a list of strings (whereas the new version only works on 2D lists). ``` .B # Split the (implicit) input-string by newlines, # and at the same time append spaces to make all lines of equal length ø # Top view: Zip/transpose the lines; swapping rows/columns R # Side view: Reverse the list of lines ε # Map each string to: ðÛ # Remove all leading spaces ð« # Append a space н # Only leave the first character q # And exit the program (although it still finishes the map first) # Top view: nothing more ø # Side view: no-op since we've already stopped the program with `q` # (after the map, the resulting character-list is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), score 11 + 2 = 13 ``` 1⍉ ⍤ ) ' ' ∘ ~ ⊃ ( ⌽ ``` Top view: ``` (⊃~∘' ')⍤1⍉ ``` Left view: ``` ⌽(⊃~∘' ')⍤1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBLmP2iY8apuoXpysoJCqkFqhkFugkKquoJ4OxApQkAhhFwEpIEpBkgGCHDA3X50rl6sMaJbGo67mukcdM4Cimo96lxg@6u3kKgfZ0bMXXYqrTCGXqxyI1XVxAKChUOfBrQMZiOQAoDkIniacqa4OcSucDVIKtllBoQ5EAp0CpDSAGOgwsNshbgEA "APL (Dyalog Unicode) – Try It Online") ### How they work ``` [⌽] (⊃~∘' ')⍤1 [⍉] ⍉ Top view only: Transpose the given char matrix ( )⍤1 On each row: ⊃~∘' ' Remove all spaces and take the first char ⌽ Left view only: Reverse the string ``` The lack of one-byte shortcut for a space adds 3 to the score; otherwise it'd be a tie with 05AB1E. [Answer] # [Python 3](https://docs.python.org/3/), 98 + 9 + 5 = 112 ``` )).strip() ] - : : [ ) ' n \ ' ( t i l p s . s n zip(* i+' '*len(s)for i in i i r o f ' ' r o ] 1 : [ ) ( p i r t s . i)) ( j(j : n i o j . ' ' = j , s a d b m a l ``` Top view: ``` lambda s,j=''.join:j(j(i).strip()[:1]or' 'for i in zip(*[i+' '*len(s)for i in s.split('\n')])).strip() ``` Left view: ``` lambda s,j=''.join:j(i.strip()[:1]or' 'for i in s.split('\n')[::-1]) ``` [Try it online!](https://tio.run/##1ZfNioMwEMfveYogyCStFcreBK/7AHu1HmyrbCRNJEkXdl/ejS272y8/Aga6PaRo4i8zY@Y/Y/Np3qV4aXdyX6YKALDHH6WxNoo1hCKPu@Q@4Wuf8JVPePKc8MyjWR6PGXhDC1/kDfpXoSBesMYHlXmA8vmZzexIPTcxRnMb6A4U@MuWqAVmS8Cw4KUgmlZSYYaZe24yVwMcH1Auq6XD4go5CACaWSomejXNn0n9wJS6PqHIjVez0Zo0pnsjWTysRYOBHdLGgUzvzVlG@5x96GNNajQp6PdZeOf07cm4IV@bfHUqLy9S9AAQoRttKU5/@27c2uGA7B1uO@nWpCrgxWG7L7CO6hQgriUTifWTsN9OOEvWuVRWaX4k5qw@2SP1wTrWDWeGwEYAzf/a6QDxvr1Y/0ZXtCxJVuucBm03XXXTJuLn4DeKCbvq9Sh2hkmRYMBLXNHLubdSH7mxb@s0V34UnAAJNSUqCIJQ24FCSKqo@8yglLbf "Python 3 – Try It Online") ]
[Question] [ I'm trying to get the shortest way (character possible) to obtain List 3. List 1 and List 2 are already given to me as arguments and are the same length. ``` l1 = [1, 2, 3, 4, 5] l2 = ['a', 'b', 'c', 'd', 'e'] ``` And List 3 should look like (yes, it needs to be a list): ``` l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5] ``` [Answer] # Zip and Sum ``` [*sum(zip(l2,l1),())] ``` [Try it online!](https://tio.run/##Fcg7DoAgDADQnVN0a2u6ADp6EsLgL5EEkSgOenkMyxtefst@JlujhhGcFjACVqAXGLyKpiVOKIBzY2msjQ29yldIharr7uegL2SKRqJmIWZfuf4 "Python 3 – Try It Online") Zips the two lists together then adds all the tuples to make one combined list. The zip only works if the lists are guaranteed to be the same size, otherwise it truncates the longer list. Added the surrounding `[* ]` to transform it into a list as FryAmTheEggman suggests. [Answer] # Slice assignment ``` c=a*2 c[1::2]=a c[::2]=b ``` This is three bytes longer than using Jo King’s solution `c=[*sum(zip(b,a),())]`, but it’s nifty. It might be shorter situationally (I can’t think of where, though). ]
[Question] [ # Challenge: In a hypothetical scenario, the countdown timer for a race has *random intervals* between the counts, to prevent premature starting, e.g. ``` 3 (0.82 seconds pass), 2 (0.67 seconds pass), 1 ``` --- # Input: nothing --- # Output: Write a program (or function) that prints the 3 numbers with a random time interval from 0.50 seconds to 1 second between each count. --- # Note: * The program must output each number (3 , 2 , 1) with the random (*any* number between 0.50 and 1 to the hundredths; no hard-coding) time interval between each. The precision of the random interval must go out to the hundreds (e.g: 0.52). You are not required to output the interval, only the count. * As @JoKing clarified, I mean uniformly random (you can use the pseudo-random generator of your language. * As many people have clarified, I really mean any 2-decimal number between 0.5 and 1. (0.50, 0.51, etc, all the way to 0.98, 0.99, 1) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the lowest byte count wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` 3LRε=₄D;ŸΩ.W ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f2Cfo3FbbR00tLtZHd5xbqRf@/z8A "05AB1E – Try It Online") --- ``` 3LR # Push [3,2,1] ε # For each... = # Print it. ₄ # Push 1000. D # Duplicate top (1000). ; # Divided by 2 (500). Ÿ # Range from b to a ([1000 .. 500]). Ω # Random pick. .W # Wait X ms. ``` --- Try it with debug enabled: [Try it online!](https://tio.run/##MzBNTDJM/f/f2Cfo3FbbR00tLtZHd5xbqRf@//9/3RQA "05AB1E – Try It Online") [Answer] # SmileBASIC, ~~64~~ 62 bytes ``` ?3M?2M?1DEF M M=MILLISEC WHILE MILLISEC<M+500+RND(501)WEND END ``` Unfortunately I can't use WAIT since that only supports intervals of 1/60 of a second (anything less isn't normally useful since input/output only update once per frame) This requires adjustment depending on the speed of the system it's running on, so it might not be valid (46 bytes): ``` ?3M?2M?1DEF M FOR I=-66E4-RND(66E4)TO.NEXT END ``` Invalid WAIT version (36 bytes): ``` ?3WAIT 30+RND(30)?2WAIT 30+RND(30)?1 ``` [Answer] # [R](https://www.r-project.org/), ~~46~~ 44 bytes for an actual countdown: ``` for(i in 3:1){cat(i) Sys.sleep(runif(1,.5))} ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdjKULM6ObFEI1OTK7iyWK84JzW1QKOoNC8zTcNQR89UU7P2/38A "R – Try It Online") printing interval as I initially misunderstood the challenge (46 bytes) Thanks [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for saving 2 chars. ``` for(i in 3:1)cat(i,format(runif(1,.5),,2)," ") ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdjKUDM5sUQjUwcolAtkFJXmZaZpGOromWrq6Bhp6igpKGn@/w8A "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` from time import* for a in'321':print a;sleep(1-time()%.5) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehJDM3VSEztyC/qESLKy2/SCFRITNP3djIUN2qoCgzr0Qh0bo4JzW1QMNQF6RUQ1NVz1Tz/38A "Python 2 – Try It Online") I created a very simple random number generator that takes the seed time (as many people do). --- Improvements * From 63 to 58 bytes by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) * [MagicOctopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn) suggested swapping sleep and count down. [Answer] # APL+WIN, 37 bytes ``` 3⋄r←⎕dl ↑n←.49+.01×2?51⋄2⋄r←⎕dl 1↓n⋄1 ``` [Answer] # Java 8, 86 bytes ``` v->{for(int i=0;++i<4;Thread.sleep((int)(Math.random()*500+500)))System.out.print(i);} ``` Prints without delimiter. If that is not allowed it's +2 bytes by changing `print` to `println` (new-line delimiter). [Try it online.](https://tio.run/##ZU@xbsIwEN37FTfajbAywOTSjREWEAtiuDqmMTh2ZF8CCOXb00vTrdI9nZ7u6d57V@xxca1uo/GYM2zRhdcbgAtk0wWNhd1EAfroKjDiOK1eUp3iPcPmYWxLLgbNmoHBkwnJGdhBgDWM/eLzdYlJ8D9w61IXhftY6kOdLFYqe2tbMd2k2CLVKmGoYiPk@6osC4aUcv/MZBsVO1JtYqVwUg@jnr3a7suz15/lb8SGC4g9sfT7dAb8l3RuE5QRofNezsGH8Qc) [Prove the intervals are in the correct range of `[500, 1000)` ms.](https://tio.run/##HYu9CoMwFEZ3n@LDKakoUnCS9g2cHEuHW@3PtSYRcxVK8dnT2OHjG845A62UD/07hG4k79EQ228CTMtt5A5eSOKtjnuYiFQrM9vn5QrSuwY83KzYCvh0rGpwnp/LGvqPgPbj5W4Kt0gxxU5Gq3ZZq4bkVcxke2eUPlRlmcXpLIXxqa5jvSVbCD8) **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type for(int i=0;++i<4; // Loop in range [1,4) Thread.sleep((int)(Math.random()*500+500))) // After every iteration: sleep for [500, 1000) ms randomly System.out.print(i);} // Print the current number ``` [Answer] # Python 3, 122 bytes ``` import random as r,time def w():time.sleep(abs(r.random()-.5)+.5) print(3,end="");w();print(", 2",end="");w();print(", 1") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoMS8lP1chsVihSKckMzeVKyU1TaFcQ9MKxNErzklNLdBITCrWKNKDqNTQ1NUz1dQGYq6Cosy8Eg1jndS8FFslJU1roC5riJiSjoKREnZxQyXN//8B) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 65 60 bytes * thanks to @Shaggy for reducing by 10 bytes * thanks to @Kevin Cruijssen for reducing by 5 bytes ``` f=(i=3)=>i&&setTimeout(f,Math.random()*500+500,i-1,alert(i)) ``` [Try it online!](https://tio.run/##HczBDYMwDADAbZBNA6KqeIYN@LGABU7rKsQocbt@QDzue1/6U1mzHNYl3bhS5Gx@1VQ0ch/1XYMH8S/0kzRNYVtkZ/0ZBDeTffpMadMdsB2H4XFx0j3dnYAg1gBYTw "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 39 bytes Gradually tweaked down to 39 bytes, thanks to @jonathan-allan + @xcali. ``` say-$_+select$a,$a,$a,1-rand.5for-3..-1 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJXJV67ODUnNblEJVEHggx1ixLzUvRM0/KLdI319HQN////l19QkpmfV/xf19dUz8DQAAA "Perl 5 – Try It Online") [Answer] # [Chip](https://github.com/Phlarx/chip) `-wingjj`, 33 bytes ``` 0123456e7f s ???????p*9S!ZZZtaABb ``` [Try it online!](https://tio.run/##S87ILPj/38DQyNjE1CzVPE2hmMseAgq0LIMVo6KiShIdnZL@//@vW56Zl56VBQA "Chip – Try It Online") In Chip, we cannot wait for exactly 1/100 of a second, but we can wait for 1/256 of a second, so we use that here. `p`, when asked, will pause execution for the stack head (one byte) \* 1/256 seconds. On each cycle, we always set the high bit of the stack (128/256) and set all other stack bits randomly (with the `?`'s). This gives an even distribution between 0.50 and 1.00 seconds. Some of the args, `-w` and `-gjj`, specify that the input, instead of using stdin, should be a countdown from `0xFF` to `0x00` (then wrapping). We use this to provide the low two bits for counting down. All other output bits remain constant (at the value corresponding to ASCII `0`). Finally, once we are done, we terminate the program with `t`, preventing a pause after the last number. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` V_S3N.d-1O.5 ``` [Try it online!](https://tio.run/##K6gsyfj/Pyw@2NhPL0XX0F/P9P9/AA "Pyth – Try It Online") --- Python 3 translation: ``` V_S3 | for N in range(1, 4)[::-1]: N | print(N) .d-1O.5 | time.sleep(1 - random.uniform(0, 0.5)) ``` [Answer] # [Nim](http://nim-lang.org/), 70 bytes ``` import os,random randomize() for i in[3,2,1]:echo i;sleep 500.rand+500 ``` [Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEIb9YpygxLyU/lwtCZValamhypeUXKWQqZOZFG@sY6RjGWqUmZ@QrZFoX56SmFiiYGhjogRRrAxn//wMA "Nim – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 18 bytes ``` 3RṚðṄṛ50r³÷³XœS@ð/ ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//M1LhuZrDsOG5hOG5mzUwcsKzw7fCs1jFk1NAw7Av//8 "Jelly – Try It Online") -3 bytes from xigoi. ## Explanation from caird coinheringaahing. ``` 3RṚðṄṛ50r³÷³XœS@ð/ - Main link. Takes no arguments on the left 3R - Generate the range [1, 2, 3] Ṛ - Reverse it ð ð - Define a dyadic chain f(a, b): Ṅ - Print a ṛ - Replace a with b 50r³ - Yield a range [50, 51, ..., 100] ÷³ - Divide each by 100; Yields [0.5, 0.51, ..., 1] X - Take a random element t œS@ - Sleep for t seconds then return b / - Reduce the range by the dyadic chain. Remember, f(a, b) = b (with some side effects), so this runs: f(f(3, 2), 1) = f(2, 1) = 1, printing a each time (3, 2, 1) ``` [Answer] # [GAWK], 57 bytes ``` BEGIN{while(a++<2){print 4-a;sleep(rand()/2+0.5)}print 1} ``` [Try it online!](https://tio.run/##SyzP/v/fydXd06@6PCMzJ1UjUVvbxkizuqAoM69EwUQ30bo4JzW1QKMoMS9FQ1PfSNtAz1SzFiJrWPv//7/8gpLM/Lzi/7q6OfmJKbYlmbmpAA "AWK – Try It Online") ]
[Question] [ Make a quine but with a twist. **Statement** The quine prints its code but puts its first character at the end. (You can do it in reverse but include that note in your answer) The output must then be a program which is also an solution. Example: Assume your code was `foobar`, running it will return `oobarf` which will be another valid program. ``` foobar -> oobarf oobarf -> obarfo obarfo -> barfoo barfoo -> arfoob arfoob -> rfooba rfooba -> foobar ``` **Rules** * Your code **must not** be an output of some generation of someone else's code that's quite obviously stealing * Your code must be more than 2 characters long (so short code is no fun) * Your code must contain at least two different characters (ex: `+++` is not valid) **Scoring** As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge the shortest code wins. [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 2600 bytes ``` ab*1'3:*2+*0pnd3*:::::::::::::::1'3:*3+*0p1'3:*5+*0p1'3:*d+*0p1'3:*f+*0p1'3:*fa++*0p1'3:*fd++*0p1'4'3*f-*0p1'4'3*7-*0p1'4'3*5-*0p6:*:*4-1p6:*:*4+1p6:*:*8+1p6:*:*a+1p6:*:*8+2p6:*:*f1++2p6:*:*f3++2pn75*1-:1'3:*4+*0p6:*:*f2++2pnaa*:::::::::::::::::1'3:*6+*0p1'3:*7+*0p1'3:*f1++*0p1'3:*f2++*0p1'3:*fe++*0p1'3:*ff++*0p1'4'3*e-*0p1'4'3*d-*0p1'4'3*4-*0p1'4'3*3-*0p6:*:*3-1p6:*:*2-1p6:*:*b+1p6:*:*c+1p6:*:*9+2p6:*:*a+2p6:*:*f4++2p6:*:*f5++2pn67*::::::::::1'3:*8+*0p1'3:*a+*0p1'3:*f4++*0p1'3:*f5++*0p1'4'3*f-5-*0p1'4'3*c-*0p1'4'3*2-*0p6:*:*1-1p6:*:*d+1p6:*:*b+2p6:*:*f6++2pna5*::1'3:*9+*0p1'3:*f3++*0p6:*:*1pn68*:::::1'3:*b+*0p1'3:*f8++*0p1'4'3*f-2-*0p1'4'3*9-*0p1'4'3*1+*0p6:*:*f7++2pne8*:::::::1'3:*c+*0p1'3:*f9++*0p1'4'3*f-1-*0p1'4'3*8-*0p1'4'3*2+*0p6:*:*f2++1p6:*:*f+2p6:*:*f8++2pnf4*:1'3:*e+*0p1'4'3*3+*2pn77*::::1'3:*f6++*0p1'4'3*f-4-*0p6:*:*f1++1p6:*:*c+2p6:*:*e+2pnb4*1-::1'3:*f7++*0p6:*:*f+1p6:*:*d+2pnf4*1-::1'3:*fb++*0p6:*:*7+2p1'3:*1+*2pnf4*2-1'3:*fc++*0pn95*:::1'4'3*f-3-*0p1'4'3*a-*0p1'4'3**0p6:*:*1+1pn87*1'4'3*b-*0pnac*2-:1'4'3*6-*0p1'4'3*3+*0pnf4*3-1'4'3*1-*0pn88*2-6:*:*5-1pnc9*1-6:*:*2+1pnb4*:6:*:*3+1p6:*:*6+1pn88*6:*:*9+1pnd4*1-6:*:*e+1pnc8*2-:1'3:**1p1'3:**2pnd7*2+6:*:*4+2pn75*6:*:*6+2pn>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ab*1'3:*2+*0pnd3*:::::::::::::::1'3:*3+*0p1'3:*5+*0p1'3:*d+*0p1'3:*f+*0p1'3:*fa++*0p1'3:*fd++*0p1'4'3*f-*0p1'4'3*7-*0p1'4'3*5-*0p6:*:*4-1p6:*:*4+1p6:*:*8+1p6:*:*a+1p6:*:*8+2p6:*:*f1++2p6:*:*f3++2pn75*1-:1'3:*4+*0p6:*:*f2++2pnaa*:::::::::::::::::1'3:*6+*0p1'3:*7+*0p1'3:*f1++*0p1'3:*f2++*0p1'3:*fe++*0p1'3:*ff++*0p1'4'3*e-*0p1'4'3*d-*0p1'4'3*4-*0p1'4'3*3-*0p6:*:*3-1p6:*:*2-1p6:*:*b+1p6:*:*c+1p6:*:*9+2p6:*:*a+2p6:*:*f4++2p6:*:*f5++2pn67*::::::::::1'3:*8+*0p1'3:*a+*0p1'3:*f4++*0p1'3:*f5++*0p1'4'3*f-5-*0p1'4'3*c-*0p1'4'3*2-*0p6:*:*1-1p6:*:*d+1p6:*:*b+2p6:*:*f6++2pna5*::1'3:*9+*0p1'3:*f3++*0p6:*:*1pn68*:::::1'3:*b+*0p1'3:*f8++*0p1'4'3*f-2-*0p1'4'3*9-*0p1'4'3*1+*0p6:*:*f7++2pne8*:::::::1'3:*c+*0p1'3:*f9++*0p1'4'3*f-1-*0p1'4'3*8-*0p1'4'3*2+*0p6:*:*f2++1p6:*:*f+2p6:*:*f8++2pnf4*:1'3:*e+*0p1'4'3*3+*2pn77*::::1'3:*f6++*0p1'4'3*f-4-*0p6:*:*f1++1p6:*:*c+2p6:*:*e+2pnb4*1-::1'3:*f7++*0p6:*:*f+1p6:*:*d+2pnf4*1-::1'3:*fb++*0p6:*:*7+2p1'3:*1+*2pnf4*2-1'3:*fc++*0pn95*:::1'4'3*f-3-*0p1'4'3*a-*0p1'4'3**0p6:*:*1+1pn87*1'4'3*b-*0pnac*2-:1'4'3*6-*0p1'4'3*3+*0pnf4*3-1'4'3*1-*0pn88*2-6:*:*5-1pnc9*1-6:*:*2+1pnb4*:6:*:*3+1p6:*:*6+1pn88*6:*:*9+1pnd4*1-6:*:*e+1pnc8*2-:1'3:**1p1'3:**2pnd7*2+6:*:*4+2pn75*6:*:*6+2pn>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ``` [Try it online!](https://tio.run/##7VQxksMgDHxOZmA8EwwY7OL@AjZc50lzxb0@JwRIOP11dpMFxGpXKIop/5zfaVr99PpF@H6HKNRDb2KW4vk6Dy2264eHuhwisoQOQplRkIyPhs1DizwRdAxtgcsmNmEm1YBswHcQeGeuICtJUBd4OivUVKUa2TnzjGchfFpqphaS6li0GgzMA04DzoOxxG4OhoahJo@6e5w7iN3a3sHajQVyaNisRUOLEx9OPGkLrNIMiu3lKSyr2xnOJFR1fYckoV3CUmtqRUu9chItqfQKVHrBAiNH@YuUmfOvDBW/ocN8yYvR785064VOMYcfnF1aolnKZMljimxEJU9MCG1fmqvWu@ZbLvkM1aw0Dj1mY06FN5rSmu224xJlSUWu2TkqcpSDQ9xUKAXCoHkwaMegcy0vsXU9mk0HhvQqkPL0TtTdWALOsANju79Mo/MnpoOmrU@C0d5DNHJZ6JFzX2G/tnShBqtb7fTubcGMXrTehsVh@pVUlruv6cERNE39BZ@HA8Y2D@rfu9HB4uv/v3sm3jPxnon3TLxnIn/v9x8 "Befunge-98 (PyFunge) – Try It Online") This making this was a hellfest. How this works: The program is a bunch of put statements that assembles a Program B around itself which then prints half of the source byte shifted twice. The program is actually 2 copies of a 1300 byte program, this is so it's ensured that the whole 1300 byte program always gets ran as a whole. Better explanation: Every Befunge-98 quine needs to contain symbols such a `@` or `q` and `,` **Problem**: None of those symbols are a good starting point especialy since `@` and `q` terminate the program instantly. **Solution**: Get rid of those characters in the source code **Problem**: How? **Solution**: Use `p` (put) commands to modify the source code to include the required characters which will print the contains of the source code shifted by one byte and **not** use the `g` command which is cheating. **Problem**: (sigh when will these end) A put command pops 3 values `n x y` which determine character, x-coord, y-coord however when the initialization of these values is split in half it can write bad characters in the beginning source code making it useless for quining. **Solution**: (last one I promise) Use 2 copies of the source code, the latter one being the "correct one" this accidentally fixes another problem which is that a put statement (p command + the constant initializers) which is split in half will not get executed, this is fixed by having 2 copies of each statement. Last thing this needs to work is how do we make the whole source code out of a half? **Answer**: [![An image's worth 1000 words they say. Then they made Piet.](https://i.stack.imgur.com/DpApM.png)](https://i.stack.imgur.com/DpApM.png) This is visual proof of why two copies of a string byte shifted == Two copies of a byte shifted string. That means we can take a half of the code, byte shift it, then print it twice (OR take half of the code, byte shift it, print, repeat [That's what actually happens]) **How this is implemented**: Assume 0123456789abcdef is the source Befunge Pseudocode: ``` 0123456789abcv;;"123456789abcdef" < go this way <-- >PS'0, repeat 2x ^ ``` PS means Print Stack (not a real instruction). We push half of the source code in reverse onto the stack using `""` then we print the stack and then we fetch (`'` command) the first character `0` which we move in front of the `'` and print it last which causes the byte shift, then we repeat the cycle once more to print the second copy. One technicality to deal with are the symbols inside the source, this can cause trouble if we write it while executing the source code, I circumvented this by adding more put statements which take care of it externally. This makes the code look something like this: [![Code](https://i.stack.imgur.com/qUMiS.png)](https://i.stack.imgur.com/qUMiS.png) **Explanation**: Green Highlight: Code that takes care of adding characters into the source Grey Letters (probs poor visibility sorry): Code that gets added by green code Red Highlight: Code that moves first character of the second half of source code into the Blue area. Blue Highlight: See Red Highlight Orange Highlight: Code that makes sure we terminate after we wrote 2 byte shifted copies by putting a `@` (terminate) command into the Yellow Area. Arrows should hopefully make it clearer how the code flow goes. Here comes the last tough part: **Where do ~~babies~~ source code come from?** Short answer: C# Magic Long answer: 100+ Befunge code snippets made by hand compiled by C# code. I manually wrote about 100 constant initializers (a piece of befunge code that pushes a certain number to stack) by hand and then used a custom C# program to compile it into the 1300 byte Befunge output, which I then copy pasted twice and made the final program. Are you still here? Great thank you for reading! (or at least scrolling to the end) I hope my bad jokes were fun and not annoying. Note: No put statement in this code creates a g command which would be cheating. EDIT: I have verified the code using the following Javascript code in TIO using developer tools ``` setInterval(()=>{document.getElementById("code").value = document.getElementById("output").value; document.getElementById("run").click();}, 2000); ``` ]
[Question] [ ### The Challenge I am thirsty and need a drink, but I don't know what to order. Your task is to provide me with either a drink or options for one. ### I/O Input will be either a *base* or a *drink name*. If given a *base*, your program should output *one random* drink from a list of drinks with that base. If given a *drink name*, your program should output the *base* that drink is made from. Below is a list of drink names, ordered by their bases: ``` Absinthe: Death in the Afternoon Earthquake Green Russians Green Vesper Moloko Plus Beer: Black and Tan Black Velvet Boilermaker Michelada Irish Car Bomb Brandy: B&B Brandy Alexander French Connection Horse's Neck Sidecar Cachaça: Caipirinha Leite de Onça Quentão Rabo-de-Galo Royce Gin: Bramble Casino Clover Club Cocktail Gin Fizz Martini Rum: Bacardi Cuba Libre Daiquiri El Presidente Piña Colada Tequila: El Toro Loco Margarita Matador Paloma Tequila Sunrise Vodka: Black Russian Bloody Mary Cosmopolitan Kamikaze Screwdriver Whiskey: Bourbon Lancer Irish Coffee Manhattan Rusty Nail Whiskey Sour ``` ### Rules: * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If given a *base*, the program's output should be *non-deterministic*, meaning that multiple runs should result in different outputs. * Accordingly, when given a *drink name*, the program's output should be *deterministic*, yielding the same result for drinks with the same base. * You may assume the input will always be one of the bases or drink names in the list compiled above. * You may choose to print characters such as `ç`, `ñ` and `ã` as `c`, `n` and `a`, respectively. * You may accept I/O in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest answer (in bytes) wins. ### Test Cases: ``` Input: Output (Any one of the following): Absinthe Death in the Afternoon Earthquake Green Russians Green Vesper Moloko Plus Beer Black and Tan Black Velvet Boilermaker Michelada Irish Car Bomb Brandy B&B Brandy Alexander French Connection Horse's Neck Sidecar Cachaça Caipirinha Leite de Onça Quentão Rabo-de-Galo Royce Gin Bramble Casino Clover Club Cocktail Gin Fizz Martini Rum Bacardi Cuba Libre Daiquiri El Presidente Piña Colada Tequila El Toro Loco Margarita Matador Paloma Tequila Sunrise Vodka Black Russian Bloody Mary Cosmopolitan Kamikaze Screwdriver Whiskey Bourbon Lancer Irish Coffee Manhattan Rusty Nail Whiskey Sour ``` Likewise, the input can be any of the drink names in the output column. If so, the output should be the corresponding base. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 356 bytes ``` “%³“¥;ġŀṭṢDṡỌµ“Ñçḥ“)ụ_ƥЬ“(OE⁼Ọ“"³Ḟ'×ɱA8“tẊ“ßDæj|t³G“z⁸ƈƲe“¦¿¶“ßṆÑẆṇ8“©ŒẓġṾɠד¢(°“⁶oI“¬ĿḤẈX“ṫ°^iɱ“ıịṣXṆẠL“3!ṁ“©VṢ“¦ƈœƘNd]¶mḄœ“Ðv4WṁḌạYÐġȯḣɼ“¢ḅuɼḶŒß“AṠḍ*ɦ)!Ḷ¿µʋ“¡pK“¡ȯL“¦uż“¬5;“¥I¢q9ḅḋĖ“µ>Ƥøŀ“ ØÐ“¤^(“¡Il“£Ḅ#ṫ$⁽ø“€Uy“"ƭ/4¢ṫ“ƬƒN⁼A6+EẈṆ“8ɠ¹“½oŒLụ}ɗ“µṡ⁴“½Çj“€g©“ÆḄ²zị'“¥¹j“þk¥ÆṢ“C⁼ṭ¬'“¿®ı“÷Ụ;“1ṂY“?]ʂ“¢ȥ4Ɗh⁺“Œ\ẒƘḳ“µċ$“¦ʋȷ[Ɱ“¡?ƓṚĠk» ¢i³ ¢_¢’¤%6¤¤¢+5X¤¤¢%6¤’¤?ị1£ ``` [Try it online!](https://tio.run/##JVL/S1NRFP@9vyJLceYPIU0xhMZIiZHZT9WkVIKkNldWzEAp2Bs1hzOYb5ArIvc9xE2da/Pet@ng3Pcee/svzvtH1rlXHtx7Pp9z7vnyOS@8GolsDgZu7PcINOiE8oyZt2LIa8gLs8jz2N6FJjnEnviLrEzWGLbLK3ZZpKFKyPN4ztU6FEX2DWgg@zMq9p26f5pwFI0d@fRgVlTCn6PQeEBoy9WYnbTPVmW1CnShpUKQJ8QeGgnk2/IpHFo6Ghkzj/zSyYl9SRU8cEq3q7XWAxJXzS6yEhrJICHkR3C6HHLqZJt1bKeQF4OUFI3cPFF3hpBrKu9TGkyVtpNWxs4uvFqC1ltkX62M7CP9yfuMIpHtopFfFGkz3ztBVnQ6qgFk3zacDrKWpYsDYvzIc8i@33IqY0PE0jDNfkpG5t8/VFfvZF7V2rBUgurkjNI4AIUPdykZspT5QzLNe3ZJMCtG9nWRFWnJlZY9KkcgIq8itXiThhx2tQvBpAzx6pNNKbpdu@2l1vgRAbtq6wu0D//U@BwJQ/MTOe3kgMscF@uWPk/b@@IoPZu0Xlf7pzxiO3yV8zUcSh0SVA7OtkjHUdUxcOkXl2tQJp9S8L7cO69BVUV04diU2otzbJfklBPI44t0@5b6cSVer@y1d964mkHI0l@godtZZOqna5qpYaVTP9U7f@7Wj9XgPjuD/JeZW4P2NSiEoEHnClDpn1AamYISfYXxyeCVIQnl8VHPE1AcDAaPXn6Mht6F/gM "Jelly – Try It Online") Formula stolen from Colera Su but I think I can get it shorter in Jelly using a Jelly-mindset approach. **¢\_¢** [Answer] # Python 3, ~~693~~ ~~690~~ ~~686~~ 687 bytes Yeah, naive approach. I tried some compression methods, and this one seems to be the shortest. *-2 bytes thanks to [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino).* EDIT: Bug fixed. ``` import random v="Absinthe$Death in the Afternoon$Earthquake$Green Russians$Green Vesper$Moloko Plus$Beer$Black and Tan$Black Velvet$Boilermaker$Michelada$Irish Car Bomb$Brandy$B&B$Brandy Alexander$French Connection$Horse's Neck$Sidecar$Cachaca$Caipirinha$Leite de Onca$Quentao$Rabo-de-Galo$Royce$Gin$Bramble$Casino$Clover Club Cocktail$Gin Fizz$Martini$Rum$Bacardi$Cuba Libre$Daiquiri$El Presidente$Pina Colada$Tequila$El Toro Loco$Margarita$Matador$Paloma$Tequila Sunrise$Vodka$Black Russian$Bloody Mary$Cosmopolitan$Kamikaze$Screwdriver$Whiskey$Bourbon Lancer$Irish Coffee$Manhattan$Rusty Nail$Whiskey Sour".split('$');a=v.index(input());print(v[a-a%6if a%6else random.randint(1,5)+a]) ``` [Try it online!](https://tio.run/##PVLBbtNAEL3zFaNqIIkgkRCCS9VDHNqCSEtoonBAHMbrCR55vePurkPTnw9jZLh4d9Zv3nv7ZrtTrjW8O5@l7TRmiBQqbV8cry6WZZKQa8aPTLkGCWAFLA@ZY1ANeE0x1489NYy3kTnAQ5@SUEhjuefUccQ79doobHyfsGA7KDy5BkwGdhTGas/@yBkLFc@xNUrrE1ezp4rwc5RUw4oiFNqWWAwWT1i8KsYtLD0/2caabiIHZ1gNgV0Wc/lJY@JJgnt2DW6lYkcRV@RqcmSrdBIl1IRrlsxQMXwN9uNbzyGT4gOVOq94fkveCj05u6uEQbctPVu/RaS48nrkCCvflybtmkziBxzcyPMz3llOEgQf@hYLU42V4KovCdZSRkuX5LE3E3jtYRM5mcWQGTcSyMj@BrBjQ3gaEDuNCmt1OtD@oiiZbJep0ogbM9n@R8O2DxYc416rhsacxxFZpWrBGccJV5pa7dQbVcAv1EpDz4xbF/l3FcUuht9rSQ1b5NrHUgOsKTg7HueihwOzmbAU80BhGvkE90MGYyNsrfFikTrTmE5wMrukq@NCbGJPUwldn6ez2WVnc8jT4w@a08sPcgD7sk88PsjFsAyAt2/ez17Tz9n5/O99/gE "Python 3 – Try It Online") [Answer] # PHP, ~~681 680 676 661~~ 646+1 bytes **gz version:** ``` <?=($x=explode)(_,$x(X,strstr($d=gzinflate(base64_decode("RZHBbtswDIZfhaft1IeI3TYblnRZEmS6CbTM1IRlMqXkbs7Tj9lS7CCQBH6Sn36uusJSBwqPhHUAFvACVudKJqoSn9Dq8DbjSHFtRAL7uRRGKffyROVCFreadVTY5bmEhsjCltNAGXuMTcY0AkoPR5R7daL8TjU2ypls8uEWvxqXAVo0aHTqQmPesYTmUxP/pbDK9NsTlz4bSXKtilCq7JRf1Ap9LvBCaYwH7imhhRbTgAk98oWNZcC4Ia4EPcF3SRh/zCQVNe6x04eeHtaYvdAlUViz3B488/Uat+4BC99Api5TbNE909hmfSeDNs+ds6SxIuewn6fQ+FbrObZzh7Dhzig+Ir/NDhF3LOjqv848ZdgZFceVSuFIrsj4EeEwi1tCN9VRTWGjSW8or2hc0bOKvVrcOfSE4aT9iKHJqm6Vq5a70/dzxVbLpBfN3irxkIx+9caOH7/hxCNeKfwcuIy0fEQ46Gx+odk6FdigpP9H0vOZyAnc0nqb50vqAi/+/z8")),$argn.X))[1])[rand()%5]?:array_slice($x(X,strstr($d,$argn,1)),-2)[0]; ``` **strtr version, ~~676~~ 661+1 bytes** ``` <?=($x=explode)(_,$x(X,strstr($d=strtr("Abs4theXDeath 4 the Aft2noon_E5thquake_Green Russi0s_Green Vesp2_Moloko PlusXBe2XMiche7da1 0d T01 Velvet_Boil2mak2_I8sh C5 BombXBr0dyXB&B_Br0dy Alex0d2_French Connection_Horse's Neck_Sidec5XCachacaXCaipi8nha_Leite de Onca_Quentao_Rabo-de-Galo_RoyceXG4XG4 Fizz9rt4i_Bramble_Cas4o_Clov2 Club CocktailXRumXBac5di_Cuba Libre_Daiqui8_P4a Co7da_El Presidente66 Sun8se_El Toro Loco9rg5ita9tador_PalomaXVodkaXBloody M5y1 Russi0_Cosmopolit0_Screwd8v2_Kamikaze33 Sour_Bourbon L0c2_I8sh Coffee9nhatt0_Rusty Nail",[an,_Black,er,XWhiskey,in,ar,XTequila,la,ri,_Ma]),$argn.X))[1])[rand()%5]?:array_slice($x(X,strstr($d,$argn,1)),-2)[0]; ``` Run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/85a3b97b842844311829fd2f890aeb23c32b6476). Requires PHP 7. [Answer] # [Python 2](https://docs.python.org/2/), 640 bytes ``` import random as r def f(s):d="eJw9Ucty2zAM/BWc2lPwD5by6tRJXNvjniEKjjCiAAek0tpfXyij6UlYanexXG66IloHxnumOoAoBIDNubKrmeIDeR0+ZhoZn5xZYT+XIqRlhScuF3Z8sWyjwS7PBRuOgyZTGoG0hyPpik6cP7liY5LZp7AMnaSBM/WEP1zKAC05NDZ12Hhor9h8a9YRNpn/xhCiR2dNwTVVTlUi5bN54e8FXjmNeJCeEzm2lAZKFF+5iIsOhFuWytAzvGn8+DWzVjLcU2d3Pd89UQ5g1xR3FV32Tl3m0EdFhm22T3Zo89zF6jRWkrzw4FFuN3yJnkQF9/OETWz1XrCdO4KtdB7tknzMEQIfMuycS0TUyrgTpTD7KuDIwci0MI7mBltLtti+k0ulmCr15riLkNN/NhxmjeIYT9aPtPa8PlEgsyguPK7YWpnsYjmsFH/SJCPdGA/J+U/vEhfD34OUkaNym70zhS1piuP1Xex8Zo4Q0WJdLGJHvcLr0sEqhEMI/wHq6dVM".decode('base64').decode('zip').split('.');i=d.index(s);print d[[i+r.randint(1,5),i/6*6][i%6>0]] ``` [Try it online!](https://tio.run/##PZJLb6JQAIX3/RXGpFFrIy95OE0nQQEFBRFBlKYL5F7l8i5cFPjzjjOLWX7n5JzVV7Q4zDP68UBpkZe4V/oZyNOeX/XKFwAvvcuwGv0Cn32o3WdOgFu6E3Vi7gZ0Yt4l9txy2NKOxi3KkLyOogUSRRiTuLgcWxRxTnLyM9gclxynJvmqyep0m4v5XJWM@rwuU6hK0CLHXph7Gdt4J3t8VH@sJNwHtcJ4QuW20X3Pm3Or3l5bz17mSzJszQLFXGDyCTqxG6/gRT3z93OdcGWT6tbigmQNyaPoVZiXs1DwZyfLKDKiCRfIooFxtw8HO3EQezbYKRSUY5QaUFtAuUvpRPTWijJmkVptQ6V2Wyx2t2UmjCW3O0SbwKEBYwJh5uzYK9VYjHJgaDthUlIGSpjStM14uTDrFC6y3Ljs7lNFqQ2m1bJ4p8yIrWy7HXUsF2A7XWMw53Gcdbq8Uy963QZ70nba8moXtsSva0m9B4jUVT6dJ3iDMRrHZJ2ki5JiS7SJDYMwwiaNoHqyZ76JTV8wE/latdfaXPMnt8iqU5RWyorYawsTLEVCGzvETQ4vEjPdOrFvtClPduGeKlBtUkfYCF4@3ZGuBjZLbXULNiVZyT@hrKvEffXDgYPenwAY5AAOB2e/gtx0MPofdKh4UlUkCA8Hk8HoA32CCcoAbJ7ufBQlynAPfH2hcTn5a9cTh9Q7O3pHBPfGfX@hV@43@f39uAwHVl3htmf4KBmMXv4NX2ADg/6zmkNYPq/7bxT5@AM "Python 2 – Try It Online") [Answer] ## PHP, 628 bytes Stealing the best ideas from others... thanks for the inflate trick ``` <?$d=explode("|",gzinflate(base64_decode("PVHLctswDPwVnHrLR1hqHp06iWt73DNEwRVGFOCAVBp78Lc99Nw/KNTR9CQstbtYLjddYakD+WfCOgALBIDNuZKJqvg9Wh3eZhzJH41IYD+XwihlhScqFzJ/1qyjwi7PxRuKgyZjGgGlhyPKik6U36l6o5zJprAMHaeBMvboX4zLAC0aNDp13lhor958atYRNpk+YgjRg5Gk4KoIpcqR8kmtEBR4oTT6gXtKaN5iGvA3xpcvbCwD+pa4EvQErxI/vs0k9Zf6Hju96+nuEXMAvaa4K8uyd+oyhT4qUm+zvpNBm+cuVqexIueFBw98u/lz9MTCvp8nbzDW9+zt3CFsubNoF/ltjhB+n2FnVCKiVPId/8Ew+1fAkYKRcWEc1RS2mnSx/YHGFWOq2Kv5LkJO/9lwmCWKIz9pP+La8/pEgVSjuPC4eqtl0ovmsBL/ihOPeCM/JKOfvXFczL8PXEaKynW2TgW2KCmO13fR85koQkSLdbGIHfUKL0sHqxAOIfwL")));$i=array_search($argv[1],$d);echo($i%6)?$d[$i-$i%6]:$d[$i+rand(1,5)]; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 381 375 bytes ``` ≔⪪”}⊞J'%↓B+K…↙ZQαyε↘¶⎚\`⟲≧↑lⅉ&⬤↖ΦüY⁹←‖⧴p×OC∧⊗F]±⊗✳N″ⅈ✳c∕lü,Π438↖⍘✳⍘⁷N⪪ςz↨D″≦«p¶↧⟦¬²◨▶↗⪫/_"b8n↨À⊙ρ≡1#▶UD⸿no,7φ²↘↑r‴m⪪pW⭆mC↥#pP″νr↧″h[κznβd6qυ:*…KC⪫⌈⸿&DΣεXMω⊙⟧↔L↓;?ü↶σ⁵%F⊙⪫:QD*)⊞↥$X4.⎆V\`″Nb5βς|…5¤⁴↘⊗|%À⭆)⬤,⁻f»Dh…{“ [WF⸿⊗$ς«8RbγZ5gv⮌⟲Π\`XcρO≦3;2{§³Qψt‹SY⪫ς⦃D⪫⎚TO⁼N⊗E⁺ζt≕·´H|›gPOWkK⁶³⧴\`⁶A⊟ⅈ✂&)ξ↧εβ%ιSΦY\`»XWV⁸|∧A▷RE⍘Zα#÷Þ~↙{﹪ÞqSK[μO\`It›▷≕ρ≔⊘Jc◨;Zm�~8″⟲P↶S⎆2×”#δ≔⌕δθπ§δ⁻π∨﹪π⁶±⊕‽⁵ ``` [Try it online!](https://tio.run/##PVLBktowDL33Kzxopg2z4dheeiLpst0psBQY9qzYgmjiWMFx6LI/T8VOZnOJJOs9ye/Z1hitoL/d5n3Pp5DtOs8pm8yrnkOqCX4RptpwMJqY@TFRDCIBHjGm@jxgQ/AUiYLZDorH0I/pgfqOIqzESyNm44ceCtJC4dE2BoMzewxjdiB/oQSFsKfYKqXi2Nbk0SE8R@5rU2I0hbQVFFGxVyi@FmNo5p7eNFDQIlKw2ishkE2sW/6W2NO33qzJNrBjRxYjlGhrtKh/7jhyqBGWxImMI/MS9ODvQCGhwBYrmTmaPaHXRK5W78rhPretPCleJRIovVwomtIPlY62TUL29z6z4Pd3WKlOHBi2QwuFTo2OoRwqNEuuoqqLfB50CXj0ZhOp1xVDIthwQCX7EGBP2uHx3rGXKGYpVu60J4ycUKOETiJsdMn2s9vshqDCERzENTjqPFqkmYgKpxxXKKVvpRP1XA/@YMsNvhPsbKR/LrJeDF5r7htSyWWIlQSzxGC1PPoixyORLqEqpjuFzkhXs75rMALNToGT3ExgMs2Nm/78Mr60BQeXufw8zTstbtSJlM3Ts1r5puVZ1uUvMVuJG7xo/GOar@mEibKHh2yrhkubfZ9@fLfb53O5zS7@Pw "Charcoal – Try It Online") A port to Charcoal of Colera Su's answer. Link is to the verbose version of the code. I could not test some of the cases because Charcoal considers `French Connection` as two different inputs... * 6 bytes saved thanks to Neil! ]
[Question] [ Sandbox post [here](http://meta.codegolf.stackexchange.com/a/10889/62574). Create a function or program that "Springifies" a string. * Input will be a String in Stdin, or closest alternative * Input will only contain printable ASCII and/or spaces * Output will be to Stdout, or closest alternative * A trailing newlines and spaces are acceptable ### How to springify a String 1. Format the String into as many ASCII spring coils as needed 2. Pad the coils with spaces, up to the nearest coil 3. Read off the characters, following the spring around the coils This is an ASCII spring coil: ``` # # #### # # # #### # ``` Where the `#`s are the characters of the String Here is an example: `abcdefghijklmnopqrstuvwxyz` becomes ``` a b cdef g h i jklm n o p qrst u v w xyz. . ``` Where the `.`s replace spaces for visibility. Then, the string is read back, following the ASCII spring downwards, around the loops, hitting the `g` and `u` twice: ``` 1| a <-3 V b cdef g h 4| i jklm V n 2-> ... ``` ...giving: `abgjklmhfedcginopuxyz vtsrquw` (with a trailing space) ### Test Cases (quotations added to highlight trailing spaces - please ignore in terms of IO) ``` I: "abcdefghijklmnopqrstuvwxyz" O: "abgjklmhfedcginopuxyz vtsrquw " I: "!@#" O: "!@ # " I: "" O: "" I: "12345 67890" O: "12690 7 54368 " I: " " O: " " ``` Note that the output length is always a multiple of 15, the length of a spring coil This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Python 2, ~~104~~ ~~102~~ 98 Bytes ``` f=lambda t:''.join((t+' '*13)[ord(x)-97+y*14]for y in range(len(t)/14+1)for x in'abgjklmhfedcgin') ``` Thanks for the comment help! <https://tio.run/#2VDVy> Original: ``` t=raw_input()+' '*13 print''.join(t[ord(x)-97+y*14]for y in range(len(t)/14)for x in'abgjklmhfedcgin') ``` [Answer] ## JavaScript (ES6), 79 bytes ``` f= s=>s.replace(/.{1,14}/g,s=>'0169abc7543268d'.replace(/./g,c=>s['0x'+c-0]||' ')) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Hexadecimal string shamelessly stolen from @ETHproductions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “4ṘƝ;þ¦Ɱ’b®¤ị ;⁶x14©¤s®ṖÇ€ ``` **[TryItOnline!](https://tio.run/nexus/jelly#AVEArv//4oCcNOG5mMadO8O@wqbisa7igJliwq7CpOG7iwo74oG2eDE0wqnCpHPCruG5lsOH4oKs////YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo)** ### How? ``` “4ṘƝ;þ¦Ɱ’b®¤ị - Link 1, output for a single coil: char array ¤ - nilad followed by link(s) as a nilad “4ṘƝ;þ¦Ɱ’ - base 250 number, 13140239220751650 ® - retrieve from register (14 from main link) b - convert to base, [1,2,7,10,11,12,13,8,6,5,4,3,7,9,0] ị - index into the char array ;⁶x14©¤s®ṖÇ€ - Main link: theString ¤ - nilad followed by link(s) as a nilad ⁶ - a space character x - repeated 14© - place 14 into the register and yield 14 ; - concatenate theString with the 14 spaces s - split into chunks of length ® - retrieve from register (14) Ṗ - pop last entry from the result (removes the space only last entry of 14 chars or less) Ç€ - call the last link (1) as a monad for €ach - implicit print ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 71 bytes ``` $ 13$* M!`.{14}|$ (.)(.)(.)(.)(.)(.)(.)(....)(.)¶ $5$8$6$4$3$2$1$5$7$9 ``` [Try it online!](https://tio.run/nexus/retina#@6/CZWisoqXA5auYoFdtaFJbo8KloaeJDQEBiHFoG5eKqYqFipmKiYqxipGKIZBnrmL5/39iUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlFQA "Retina – TIO Nexus") Permuting strings isn't exactly concise in Retina... [Answer] # JavaScript (ES7), ~~144~~ ~~143~~ ~~141~~ ~~114~~ ~~104~~ 103 bytes *Thanks to ETHProductions for a 10B save!* ``` a=>[...b=a+' '.repeat(15-a.length%15)].map((_,c)=>b['0x'+'0169abc7543268d'[c%15]-0+(c/15|0)*14]).join`` ``` ## Example ``` f=a=>[...b=a+' '.repeat(15-a.length%15)].map((_,c)=>b['0x'+'0169abc7543268d'[c%15]-0+(c/15|0)*14]).join`` f('abcdefghijklmnopqrstuvwxyz') ``` ## Output ``` abgjklmhfedcginopuxyz vtsrquw ``` [Answer] # [Perl 6](http://perl6.org), 61 bytes ``` {S:g/(.)**1..14/{[~] $0["abgjklmhfedcgin".ords X-97]X//" "}/} ``` ### How it works The basic structure is this: ``` { } # A lambda. S:g/(.)**1..14/{ }/ # Regex-replace segments of 1-14 characters, with: $0 # The single-char submatches captured by the parens. [ ] # Index them using certain indices (see below). X//" "} # Replace each undefined element with a space. [~] # Concatenate the characters. ``` The expression used to index into each 14-characters segment is `"abgjklmhfedcgin".ords X- 97`, which works as follows: 1. Take the hard-coded string `abgjklmhfedcgin`. 2. Get its codepoints: `97 98 103 106 107 108 109 104 102 101 100 99 103 105 110`. 3. Subtract 97 from each number: `0 1 6 9 10 11 12 7 5 4 3 2 6 8 13`. --- # [Perl 6](http://perl6.org), 64 bytes ``` {[~] .comb(14)».comb»[0,1,6,9..12,7,5...2,6,8,13].flat X//" "} ``` [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V8dXReroJecn5ukYWiieWg3mHlod7RSYlJ6VnZObkZaakpyemaekl5@UUqxQoSupXmsXlpOYolChL6@koJS7f/ixEqFNA2g@uSU1LT0jEyQrrz8gsKi4pLSsvKKyiolTb2C1KIcay6oSkUHZSVNBewAVSVOZRgqDY2MTUwVzMwtLA0wNKGqVMBjKETlfwA "Perl 6 – TIO Nexus") ### How it works The basic structure is this: ``` { } # A lambda. .comb(14) # Split the argument into substrings of <= 14 chars. ».comb # Split each substring into a list of characters. »[ ] # Index each list using the same indices (see below). .flat # Flatten the resulting nested list. X//" " # Replace each undefined element with a space. [~] # Concatenate the list to get a string again. ``` Same indices as above, but since we're calling `.flat` anyway, we can use a nested (but 1 byte shorter) expression for them: `0,1,6,9..12,7,5...2,6,8,13`. (Looks trivial, but actually relies on a parsing peculiarity of Rakudo Perl 6 that is [probably a bug](https://rt.perl.org/Ticket/Display.html?id=130604). To write it without exploiting that bug, one would have to add parens around the `5...2`.) [Answer] # Befunge-93, 97 bytes ``` <>0>v%2g3\p89:-1+*"!"!:+1<_@#`0:~ ,^\,_\:98g\9p1+:76+`#v_:~^ ^,,g96g98g9+67,,,,,$$_ == = ==== ``` [Try it online!](http://befunge.tryitonline.net/#code=PD4wPnYlMmczXHA4OTotMSsqIiEiITorMTxfQCNgMDp+CixeXCxfXDo5OGdcOXAxKzo3NitgI3ZfOn5eCl4sLGc5Nmc5OGc5KzY3LCwsLCwkJF8KPT0gICAgPSAgPT09PQ&input=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo) This is a breakdown of the source code with the various component parts highlighted. ![Source code with execution paths highlighted](https://i.stack.imgur.com/Cp1R5.png) ![*](https://i.stack.imgur.com/jmV4j.png) The main loop starts off executing right to left, wrapping around to the right hand side of the playfield. This is where we read the first character from stdin, and terminate if it's an EOF. ![*](https://i.stack.imgur.com/z4eIY.png) The next section makes sure any EOF characters are converted to spaces using the formula `c = c + 31*!(c+1)`. Although this won't apply on the first iteration, it can occur on subsequent passes. ![*](https://i.stack.imgur.com/aZli8.png) A copy of the character is saved to temporary memory, and then a lookup of the current index is performed on the table on line four (![*](https://i.stack.imgur.com/SetfX.png)) to determine whether the character should be output or not. ![*](https://i.stack.imgur.com/RFUim.png) If the character needs to be output, we take the left branch. A swap is performed here to cancel out the swap that's going to occur next, and then a zero is pushed to force the branch right. ![*](https://i.stack.imgur.com/BX1CZ.png) If the character wasn't output, we swap it down the stack beneath the index counter (this is the swap that gets cancelled in the left branch). And in both cases we save the character to memory at the current index offset, increment the index, and check if it's greater than 13. ![*](https://i.stack.imgur.com/xap31.png) If not, we read the next character from stdin and repeat the inner loop. ![*](https://i.stack.imgur.com/F81v5.png) If it is, we'll have finished a set of 14 characters, 7 having been output (`abgjklm`), and 7 remaining on the stack (`cdefhin`). We drop the last two, output the remaining 5 (`hfedc`), and then retrieve and output the special cases `g`, `i` and `n` from memory. ![*](https://i.stack.imgur.com/jmV4j.png) And that brings us back to the start of the main loop, where we repeat the process again for the next 14 characters. [Answer] # Mathematica, ~~77~~ 72 bytes *Thanks to JungHwan Min for saving 5 bytes!* ``` Join@@Partition[#,14,14,{1,1}," "][[;;,LetterNumber@"abgjklmhfedcgin"]]& ``` Unnamed function taking a list of characters as input and returning a list of characters. `Partition[#,14,14,{1,1}," "]` splits the input into sublists of length 14, padding with spaces if necessary. `LetterNumber@"abgjklmhfedcgin"` evaluates to `{1,2,7,10,11,12,13,8,6,5,4,3,7,9,14}`, which indicates the order to take each length-14 sublist in (repeating the 7th element appropriately). Then `[[;;,...]]` takes the elements of all the length-14 sublists in that order, and `Join@@` joins the answers together. Previous submission: ``` Join@@Partition[#,14,14,{1,1}," "][[All,83224017339955102~IntegerDigits~16]]& ``` [Answer] # [Python 3](https://docs.python.org/3/), 86 bytes ``` lambda s:''.join(t[i%14]for t in zip(*[iter(s+' '*13)]*14)for i in b'Tq>]zQ|1/X;:L$o') ``` [Try it online!](https://tio.run/nexus/python3#FcoxDsIgFADQq/xBA9REQ@xUoydwMXEwqQxgi/7aAkWqSLw7pm9@GvZwzb0cVCMhVoSsO4uGhhqXvBTaegiABhI6WtQYWk/jigAp@JaJgpdsHjgPRc7jQaTTj28uu@q4sIRl59EEqikaNwXKGMtS3ZpW3x/YPfvBWDf6V5jen/hNfw "Python 3 – TIO Nexus") As a bonus, the string `Tq>]zQ|1/X;:L$o` is a valid CJam program that prints the unique characters on standard input, sorted. [Try it online! (+ explanation)](https://tio.run/nexus/cjam#jZFPa8JAEMXv/RSP1EMLJZqrglDwUpBa/0CFksNitmap3V0zk5osfne7Ta1VE2ofzLKHx/zezOxm637sxtuoPe91hy2zk9fwmqGup5xSdK6@DVjXDRMpEkxng4fHH1OjAufKIjhY@jXDdKUWsockMxYdrHxXpZdYpCIj3KhQhtBGy9tfSOzOOjxnwoJYLN4gdALOhCZrSHb/DPYSuABVlb6KID52j7enGSVvFEmMJtgoTiHfLZdYKWKMQwxkkls/hWBJ4T@YDTwgah/zfDuG0hWCYF79XvTSg6M7kMFGIhUfl@b7gsUeWVavB8bn/nnv9NxRtT/rD6G43rs73H/uidRSg1NFYINhU4zWfhCT8aWUxVFK15CykqneUc42553zKsviEw "CJam – TIO Nexus") [Answer] # PHP, 94 bytes ``` foreach(str_split($argv[1],14)as$s)for($i=0;$c=abgjklmhfedcgin[$i++];)echo$s[ord($c)-97]??" "; ``` splits command line argument to 14-byte chunks and loops through the translation string as index for the sub-string. Run with `php -nr '<code>' <string>`. I was glad to find out that `??` also accepts the empty string (for an "invalid" index) as null. [Answer] ## Ruby, 83 bytes ``` ->s{v="";(s+" "*13).scan(/.{14}/){|y|"0169:;<7543268=".chars{|o|v+=y[o.ord-48]}};v} ``` First idea was using hex numbers, but ord-48 saves another byte (stolen from throx's answer). ]
[Question] [ [Adam7](https://en.wikipedia.org/wiki/Adam7_algorithm) is an interlacing algorithm for raster images, such as PNG. It is called the "Adam7" algorithm because it was invented by Adam M. Costello, and it is generated by following a certain pattern 7 times. One of the cool things about the Adam7 algorithm that makes it really fun for code golf, is that the pattern can be repeated an arbitrary number of times, as long as it's odd. Back when 1996 when the `PNG` standard was developed, using only 7 iterations was seen as sufficient, since the 9 iterations was too complex, and 5 iterations is not as efficient. Here is the first iteration of the tile: ``` a ``` Pretty simple. This is an "Adam1" tile. Here's how we get to the next iteration, the "Adam3" tile. Since our last tile was `1x1`, we double the height and width, and the next one will be `2x2`. First, we start with an 'a' in the upper left corner. ``` a- -- ``` Step 2, copy this pattern to the right, and increase the letter we're on by one. ``` ab -- ``` Step 3, same as step 2, but copy down instead of right. ``` ab cc ``` Boom. The "Adam3" tile. Let's do the "Adam5" also, so you can actually see how the algorithm works. This tile will, again, be twice as large, so `4x4`. Again, we start with a `a` in the upper left corner: ``` a--- ---- ---- ---- ``` Double this pattern, increase the letter, and move it to the right: ``` a-b- ---- ---- ---- ``` Again, this time down. ``` a-b- ---- c-c- ---- ``` Again, this time to the right. ``` adbd ---- cdcd ---- ``` Again, this time down. ``` adbd eeee cdcd eeee ``` This is the "Adam5" tile. Here is the ASCII representation of the Adam7 tile: ``` afdfbfdf gggggggg efefefef gggggggg cfdfcfdf gggggggg efefefef gggggggg ``` And while we're at it, here is a fun animation of each step of the Adam7 tile (although it does several tiles side by side): [![enter image description here](https://i.stack.imgur.com/8UhiP.gif)](https://i.stack.imgur.com/8UhiP.gif) # The challenge Given a positive odd number *N*, output the "Adam*N*" tile. You can use any [default method of IO](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Since we're using the alphabet in lieu of numbers, you only need to handle inputs up to 25. You can choose to output lower-case or upper-case characters as long as you specify and it's consistent. # Sample IO 1: ``` a ``` 3: ``` ab cc ``` 5: ``` adbd eeee cdcd eeee ``` 7: ``` afdfbfdf gggggggg efefefef gggggggg cfdfcfdf gggggggg efefefef gggggggg ``` 9: ``` ahfhdhfhbhfhdhfh iiiiiiiiiiiiiiii ghghghghghghghgh iiiiiiiiiiiiiiii ehfhehfhehfhehfh iiiiiiiiiiiiiiii ghghghghghghghgh iiiiiiiiiiiiiiii chfhdhfhchfhdhfh iiiiiiiiiiiiiiii ghghghghghghghgh iiiiiiiiiiiiiiii ehfhehfhehfhehfh iiiiiiiiiiiiiiii ghghghghghghghgh iiiiiiiiiiiiiiii ``` As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins! [Answer] ## CJam, 20 bytes ``` Laq~{'a+_@f*\f+z}/N* ``` [Try it online](http://cjam.aditsu.net/#code=Laq~%7B'a%2B_%40f*%5Cf%2Bz%7D%2FN*&input=5). ``` La Push [[]] q~ Push input n { }/ For i in 0..n-1 ... 'a+ Add to char 'a to give current char _@f* Join each row by char \f+ Add char to the end of each row as well z Zip to transpose N* Join result by newlines ``` 20/21-byte alternatives: ``` Laaq~{'a+aff+:sz}/N* Laaq~{'a+\Laf+f*z}/N* Laq~{'a+f{_@*\+}z}/N* ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 23 bytes ``` 97tiq:+"TFX*tXa~@wZ(!]c ``` [**Try it online!**](http://matl.tryitonline.net/#code=OTd0aXE6KyJURlgqdFhhfkB3WighXWM&input=Nw) This uses repeated Kronecker tensor product for extending the array, followed by transposition. At each iteration, new columns containing zeros are interleaved with the old; those zeros are then replaced by the appropriate new value (which increases at each iteration); and the matrix is transposed. (One byte wasted because Octave's Kronecker product doesn't allow char input. This will be fixed for next release). ### EXplanation ``` 97 % Push 97 (ASCII for 'a') t % Duplicate iq: % Take input n. Range [1 2 ... n-1] + % Add. Gives [98 99 ... 97+n-1] (letters to be filled) " % For each TFX* % Kronecker product with [1 0]. This interleaves new columns with zeros tXa~ % Duplicate. Logical index for the new columns @wZ( % Assign letter to those columns ! % Transpose (zip) ] % End if c % Convert to chat. Implicitly display ``` [Answer] # Perl, ~~110~~ ~~104~~ ~~100~~ ~~99~~ ~~91~~ ~~89~~ 87 + 1 (`-p` flag) = 88 bytes ``` #!perl -p $==$_/2;$_=a.$/;$"=b;s/\w/$&.$"/ge,$"++,s/\n/$&.$"x2**$%.$&/ge,$"++until$=<++$%;$\=$_}{ ``` Using: ``` > echo 5 | perl -pe '$==$_/2;$_=a.$/;$"=b;s/\w/$&.$"/ge,$"++,s/\n/$&.$"x2**$%.$&/ge,$"++until$=<++$%;$\=$_}{' ``` Ungolfed: ``` while (<>) { # code above added by -p # $_ has input value # $/ = "\n" by default # $% = 0 by default my $n = $_ / 2; # input my $s = "a" . $/; # "a\n" my $c = "b"; # "b" my $i = $%; # 0 while (++$i <= $n) { $s =~ s/(\w)/$1 . $c/ge; $c++; $s =~ s/(\n)/$1 . ($с x 2**$i) . $1/ge; $c++; } $\ = $s; } { # code below added by -p print; # prints $_ (undef here) and $\ } ``` [Ideone](http://ideone.com/u41qSt). [Answer] ## JavaScript (ES6), 114 bytes ``` f=n=>n<2?`a `:f(n-2).replace(/./g,`$&`+(n+8).toString(36)).replace(/\n/g,` ${(n+9).toString(36).repeat(1<<n/2)} `) ``` [Answer] ## Pyth, 38 bytes ``` u:+r:jK@;tyHGb++b*^2H@;yHb6b+bKbh/Q2"a ``` [Try it here!](http://pyth.herokuapp.com/?code=u%3A%2Br%3AjK%40%3BtyHGb%2B%2Bb*%5E2H%40%3ByHb6b%2BbKbh%2FQ2%22a&input=5&debug=0) I would expect this to be easily golfable. ]
[Question] [ Given an input of two strings with sequences of underscores representing corresponding words, output the sentences with the "blanks" filled in. The best way to describe this challenge is by example. Here is an example input: ``` programming _____________ and code golf programming puzzles ______ code ____ ``` And here is the corresponding output: ``` programming ___puzzles___ and code golf programming puzzles _and__ code golf ``` For the purposes of this challenge, a "word" is defined as a sequence of one or more lowercase letters, and a "blank" is defined as one or more underscores (the input will always contain only lowercase letters, spaces, and underscores). *Words* and *blanks* in the input strings are separated by single spaces, and the sum of the number of *words* and *blanks* in the sentences will always be equal. The objective of the challenge is to fill all of the *blanks* with the correct *words*, which are the words that occupy the same index in the other string when split by spaces. * The word must be centered in the blank, as shown with the word "puzzles" in the example above—an equal number of underscores remain on either side. * If the word cannot be exactly centered, the extra underscore may go either on the left or the right (ex. the word "and" in the example above). * There will always be enough underscores for the word to fit, but there may be exactly as many as the length of the word (ex. the word "golf" in the example above). * There will never be a blank in the same position in both strings. Input/output may be any of the following (input/output do not necessarily have to be via the same method): * single string separated by any character that is not alphabetic, a space, or an underscore (ex. newline or comma separated string) * an array/list/etc. of two strings * two function/command line arguments (input only) Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. The example above can be used as a test case. Here is a larger test case (second string in output may vary slightly due to different centering behavior): ``` lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum lorem ipsum dolor _sit_ amet __consectetur__ adipiscing elit mauris dapibus tincidunt ____________metus____________ accumsan fringilla proin vulputate viverra lorem fermentum dictum lorem ipsum dolor_ sit _amet__ consectetur __adipiscing___ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem _________fermentum__________ dictum ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~102~~ ~~100~~ ~~93~~ 88 bytes Byte count assumes ISO 8859-1 encoding. ``` $ !¶$` m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+)) $2 (([a-z])+)(?<-2>_)*(_*)\3|!\D+ $3$1$3 ``` The strings will are separated by a linefeed. If there is an odd number of underscores left, the extraneous one will be after the word. [Try it online!](http://retina.tryitonline.net/#code=JAohwrYkYAptYCg_PD1eKFx3KyApKikoPz1fLirCtig_PC0xPlx3KyApKihcdyspKQokMgooKFthLXpdKSspKD88LTI-XykqKF8qKVwzfCFcRCsKJDMkMSQz&input=bG9yZW0gX19fX18gZG9sb3IgX19fX18gYW1ldCBfX19fX19fX19fX19fX18gYWRpcGlzY2luZyBlbGl0IG1hdXJpcyBkYXBpYnVzIHRpbmNpZHVudCBfX19fX19fX19fX19fX19fX19fX19fX19fX19fXyBhY2N1bXNhbiBmcmluZ2lsbGEgcHJvaW4gdnVscHV0YXRlIHZpdmVycmEgbG9yZW0gZmVybWVudHVtIGRpY3R1bQpsb3JlbSBpcHN1bSBfX19fX18gc2l0IF9fX19fX18gY29uc2VjdGV0dXIgX19fX19fX19fX19fX19fIGVsaXQgbWF1cmlzIGRhcGlidXMgdGluY2lkdW50IG1ldHVzIGFjY3Vtc2FuIGZyaW5naWxsYSBwcm9pbiB2dWxwdXRhdGUgdml2ZXJyYSBsb3JlbSBfX19fX19fX19fX19fX19fX19fX19fX19fX19fIGRpY3R1bQ) ### Explanation I guess this is the "duplicate-append-lookback-match-add-centre approach", or something close... ``` $ !¶$` ``` We start by duplicating the input (separated with a `!` and a linefeed). The purpose of this is that we can then process both lines by fetching words from the *next* line (instead of having to treat the second line separately). ``` m`(?<=^(\w+ )*)(?=_.*¶(?<-1>\w+ )*(\w+)) $2 ``` This prepends the correct word to each gap. We start by counting the current word position with the lookbehind `(?<=^(\w+ )*)` (the position is stored as the depth of group `1`). Then the lookahead a) ensures that we're at the beginning of a gap by matching `_`, then skips to the next line with `.*¶`, matches the correct number of words with `(?<-1>\w+ )*` to get to the right position, and then matches the word found there with `(\w+)` into group `2`. ``` (([a-z])+)(?<-2>_)*(_*)\3|!\D+ $3$1$3 ``` This stage does three things: * It removes the underscores corresponding to each word length. This is done by counting the word length into group `2` with `([a-z])+` and then matching that many underscores (which are never written back). * It shifts the word to the centre of the gap by capturing half of the remaining underscores with `(_*)\3` and writing `$3$1$3` back. * It removes the duplicated input by matching `!\D+` and replacing it with nothing. [Answer] # Pyth, 30 ``` jL;Cmm|*}J\_k.[lkhx#JdJkdCcR;Q ``` Takes input and outputs as a list of two strings. Uses a pretty basic split–zip–double map–centre–zip–join approach. [Try it here](http://pyth.herokuapp.com/?code=jL%3BCmm%7C%2A%7DJ%5C_k.%5Blkhx%23JdJkdCcR%3BQ&input=%22programming%20_____________%20and%20code%20golf%22%2C%20%22programming%20puzzles%20______%20code%20____%22&debug=0) ### Expanded: ``` jL;Cmm|*}J\_k.[lkhx#JdJkdCcR;Q ## cR;Q ## split C ## zip mm ## double map |*}J\_k.[lkhx#JdJkd ## centre C ## zip jL; ## join ``` I'll explain more once I'm really satisfied that I can't golf this any more, although it should be pretty clear, given the ubiquity of the split–zip–double map–centre–zip–join approach and all. [Answer] ## Python 2, 109 ``` def f(a,b):exec"print' '.join([x,y][x<'`'].center(len(x),'_')for x,y in zip(a.split(),b.split()));a,b=b,a;"*2 ``` The function takes two strings as arguments and prints the output as in the examples. It uses a boring approach, with `str.center(width, fillchar)` doing most of the work. [Try it online](http://ideone.com/vhDDzn). [Answer] # Ruby, ~~111~~ 109 characters ``` ->l{l.map(&:split).transpose.map{|c|c[m=c[0]<c[1]?0:1]=c[1-m].center c[m].size,?_ c}.transpose.map{|s|s*' '}} ``` Input: array of 2 strings; output: array of 2 strings. Sample run: ``` 2.1.5 :001 > puts ->l{l.map(&:split).transpose.map{|c|c[m=c[0]<c[1]?0:1]=c[1-m].center c[m].size,?_;c}.transpose.map{|s|s*' '}}[[ 2.1.5 :002 > 'programming _____________ and code golf', 2.1.5 :003 > 'programming puzzles ______ code ____', 2.1.5 :004 > ]] programming ___puzzles___ and code golf programming puzzles _and__ code golf ``` [Answer] # JavaScript, ~~194~~ 185 bytes ``` f=(m,n)=>(m=m.split` `,n=n.split` `,G=(x,i,a)=>x[0]!='_'?x:(b=(a?n:m)[i],s=x.length-b.length,(k='_'.repeat(s/2))+b+k+(s%2?'_':'')),H=(e,y)=>e.map((x,i)=>G(x,i,y)).join` `,[H(m,1),H(n)]) ``` Takes two strings as parameters and outputs two strings as array/list ``` f=(m,n)=>( m=m.split` `, n=n.split` `, G=(x,i,a)=> x[0]!='_'?x: ( b=(a?n:m)[i], s=x.length-b.length, (k='_'.repeat(s/2))+b+k+(s%2?'_':'') ), H=(e,y)=>e.map((x,i)=>G(x,i,y)).join` `, [H(m,1),H(n)] ) document.body.innerHTML = '<pre>' + "f('lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum', 'lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum')<br>" + f('lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum', 'lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum') + "<br><br>" + "f('programming _____________ and code golf', 'programming puzzles ______ code ____')<br>" + f('programming _____________ and code golf', 'programming puzzles ______ code ____') '</pre>' ``` [Answer] # Mathematica 223 There must be a shorter way to do this. ``` k=StringLength;m=StringSplit; g=Partition[Riffle[m@#,m@#2],2]/.{{a_,a_}:> a<>" ",{a_,b_/; StringTake[b,1]=="_"}:> a<>" ", {a_,b_}:>Table["_",Ceiling[z=(k@a-k@b)/2]]<>b<>""<>Table["_",Floor@z]<>" "}&; s_~h~t_:={""<>g[s,t],""<>g[t,s]} ``` --- **Sample run** ``` h["programming _____________ and code golf", "programming puzzles ______ code ____"] ``` [![enter image description here](https://i.stack.imgur.com/bfYjh.png)](https://i.stack.imgur.com/bfYjh.png) [Answer] # Gema, ~~208~~ 203 characters ``` \B=@set{i;0} <I>=@push{${v;f};$0}@incr{i} \n=@set{v;s}@set{i;0} = \E=@repeat{$i;@cmps{$f;$s;@set{f;@fill-center{$f;$s}};;@set{s;@fill-center{$s;$f}}}@set{F;$f ${F;}}@set{S;$s ${S;}}@pop{f}@pop{s}}$F\n$S ``` Just because Gema has the perfect function for this task: [`@fill-center{*background*;*value*}`](http://gema.sourceforge.net/new/function.shtml#4.2.1Outputfrmtpddn,flln,ndwrpp). Input: 2 newline separated lines (no final newline); output: 2 newline separated lines (with trailing spaces – not seem to be forbidden). Sample run: ``` bash-4.3$ echo -ne 'programming _____________ and code golf\nprogramming puzzles ______ code ____' | > gema '\B=@set{i;0};<I>=@push{${v;f};$0}@incr{i};\n=@set{v;s}@set{i;0}; =;\E=@repeat{$i;@cmps{$f;$s;@set{f;@fill-center{$f;$s}};;@set{s;@fill-center{$s;$f}}}@set{F;$f ${F;}}@set{S;$s ${S;}}@pop{f}@pop{s}}$F\n$S' programming ___puzzles___ and code golf programming puzzles _and__ code golf ``` [Answer] # C, 197 bytes ``` #define c(w,y)l=strspn(w,"_"),r=strcspn(y," "),memcpy(w+(l-r)/2,y,r),w+=l,y+=r; main(l,v,w,y,r)char**v,*w,*y;{for(w=v[1],y=v[2];*w;w++,y++)if(*w^*y)if(*w^95)c(y,w)else c(w,y)puts(v[1]);puts(v[2]);} ``` ## Output ``` $ ./a.out "lorem _____ dolor _____ amet _______________ adipiscing elit mauris dapibus tincidunt _____________________________ accumsan fringilla proin vulputate viverra lorem fermentum dictum" "lorem ipsum ______ sit _______ consectetur _______________ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem ____________________________ dictum" lorem ipsum dolor _sit_ amet __consectetur__ adipiscing elit mauris dapibus tincidunt ____________metus____________ accumsan fringilla proin vulputate viverra lorem fermentum dictum lorem ipsum dolor_ sit _amet__ consectetur __adipiscing___ elit mauris dapibus tincidunt metus accumsan fringilla proin vulputate viverra lorem _________fermentum__________ dictum ``` [Answer] ## ES6, 122 bytes ``` a=>a.map(s=>s.split` `).map((s,n,a)=>s.map((w,i)=>w<'a'?(l=w.length,t=w+a[n^1][i]+w,t.substr(t.length-l>>1,l)):w).join` `) ``` Takes an array of two strings as a single parameter and returns another array of two strings. ]
[Question] [ *EDIT:* As some of you suspected, there was a bug in the official interpreter: the order of composition in `.` was reversed. I had two versions of the interpreter, and used the wrong one here. The examples were also written for this incorrect version. I have fixed the interpreter in the repository, and the examples below. The description of `>` was also a bit ambiguous, so I've fixed that. Also, apologies for this taking so long, I was caught up in some real life stuff. *EDIT2:* My interpreter had a bug in the implementation of `.` which was reflected in the examples (they relied on undefined behavior). The issue is now fixed. # Introduction [Shift](https://github.com/iatorm/shift) is an esoteric functional programming language I made a couple of years ago, but published today. It is stack-based, but also has automatic currying like Haskell. # Specification There are two datatypes in Shift: * Functions, which have an arbitrary positive *arity* (number of inputs), and which return a list of outputs. For example, a function that duplicates its only input has arity 1, and a function that swaps its two inputs has arity 2. * Blanks, which are all identical and have no other purpose than not being functions. A Shift program consists of zero or more *commands*, each of which is a single ASCII character. There are 8 commands in total: * `!` (*apply*) pops a function `f` and a value `x` from the stack, and applies `f` to `x`. If `f` has arity 1, the list `f(x)` is added to the front of the stack. If it has arity `n > 1`, a new `(n-1)`-ary function `g` is pushed to the stack. It takes inputs `x1,x2,...,xn-1` and returns `f(x,x1,x2,...,xn-1)`. * `?` (*blank*) pushes a blank to the stack. * `+` (*clone*) pushes to the stack a unary function that duplicates its input: any value `x` is mapped to `[x,x]`. * `>` (*shift*) pushes to the stack a unary function that takes in an `n`-ary function `f`, and returns an `(n+1)`-ary function `g` that ignores its first argument `x`, calls `f` on the remaining ones, and tacks `x` in front of the result. For example, `shift(clone)` is a binary function that takes inputs `a,b` and returns `[a,b,b]`. * `/` (*fork*) pushes to the stack a ternary function that takes three inputs `a,b,c`, and returns `[b]` if `a` is a blank, and `[c]` otherwise. * `$` (*call*) pushes to the stack a binary function that pops a function `f` and a value `x`, and applies `f` to `x` exactly as `!` does. * `.` (*chain*) pushes to the stack a binary function that pops two functions `f` and `g`, and returns their composition: a function `h` that has the same arity as `f`, and which takes its inputs normally, applies `f` to them, and then *fully* applies `g` to the result (calls it as many times as its arity dictates), with unused items from the output of `f` remaining in the result of `h`. For example, suppose that `f` is a binary function that clones its second argument, and `g` is *call*. If the stack contains `[f,g,a,b,c]` and we do `.!!`, then it contains `[chain(f,g),a,b,c]`; if we do `!!` next, then `f` is first applied to `a,b`, producing `[a,b,b]`, then `g` is applied to the first two elements of that since its arity is 2, producing `[a(b),b]`, and the stack will finally be `[a(b),b,c]`. * `@` (*say*) pushes a unary function that simply returns its input, and prints `0` if it was a blank, and `1` if it was a function. Note that all commands except `!` simply push a value to the stack, there is no way to perform input, and the only way to output anything is to use `@`. A program is interpreted by evaluating the commands one by one, printing `0`s or `1`s whenever "say" is called, and exiting. Any behavior not described here (applying a blank, applying a stack of length 0 or 1, calling "chain" on a blank etc.) is undefined: the interpreter may crash, silently fail, ask for input, or whatever. # The Task Your task is to write an interpreter for Shift. It should take from STDIN, command line, or function argument a Shift program to be interpreted, and print to STDOUT or return the resulting (possibly infinite) output of `0`s and `1`s. If you write a function, you *must* be able to access the infinite-length outputs in some way (generator in Python, lazy list in Haskell, etc). Alternatively, you can take another input, a number `n`, and return at least `n` characters of the output if it is longer than `n`. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases This Shift program prints `01`: ``` ?@!@@! ``` Starting from the left: push a blank, push *say*, then apply the *say* to the blank. This outputs `0`. Then, push *say* twice, and apply the second *say* to the first. This outputs `1`. This program loops forever, producing no output: ``` $+.!!+!! ``` Push *call* and *clone*, then apply *chain* to them (we need two `!`s since *chain* is a binary function). Now the stack contains a function that takes one argument, duplicates it, and calls the first copy on the second. With `+!!`, we duplicate this function and call it on itself. This program prints `0010`: ``` ?@$.++>!.!!.!!.!!!!+?/!!!@!@>!!! ``` Push a blank and *say*. Then, compose a binary function that copies its second argument `b`, then copies the first `a` and composes it with itself, then applies the composition to the copy of `b`, returning `[a(a(b)),b]`. Apply it to *say* and blank, then apply *say* to the two elements remaining on the stack. This program prints `0`. For each `!!!` that you append to it, it prints an additional `0`. ``` ?@+$>!>!+>!///!!>!>!.!!.!!.!!+!!!! ``` Push a blank and *say*. Then, compose a ternary function that takes `f,g,x` as inputs and returns `[f,f,g,g(x)]`. Clone that function, and apply it to itself, *say*, and the blank. This application does not change the stack, so we can apply the function again as many times as we want. This program prints the infinite sequence `001011011101111...`, where the number of `1`s always increases by one: ``` @?/!@>!??/!!>!+.!!.!!.!!.+>!.!!$$$$+$>!>!$>!>!+>!$>!>!>!+>!>!///!!>!>!>!.!!.!!.!!.!!.!!.!!.!!.!!.!!.!!+!!!!! ``` The repository contains an annotated version. [Answer] # Python 2, ~~752~~ ~~667~~ ~~534~~ ~~506~~ ~~445~~ ~~436~~ ~~427~~ ~~404~~ ~~398~~ 393 bytes This is by no means short... but I did my best. Any golfing suggestions would be very much appreciated... ***EDIT6: This is now a script instead of a function. Save it to a file (shift.py, forex), then run it with `$ python shift.py '<my_input>'`. Make sure to put the input in single quotes, or bash will go crazy with the input characters.*** *EDIT7: Aaaaaaand... it's not readable anymore. But I got rid of 23 more bytes, so that's good, I guess? I'll post an ungolfed version too.* *EDIT8: One more golf, thanks to @Zgarb.* ``` k,d=[],[] u=k.append def z(f,a=1):f.a=a;return f exec "i=!x:x(*map(k.pop,[-1]*x.a)));e=dict(zip('?+>/$.@',[0,!x:u(x)<u(x)),!x:u(!a,*_:x(*_)<u(a),x.a+1))),!x,y,z:u((z,y)[x<1]),3),!x,y:u(!*_:x(y,*_),x.a-1))if x.a>1 else x(y),2),!x,y:u(!*_:x(*_)<i(y),x.a)),2),!x:d.append(`+(x>0)`)<u(x))]))".replace('!',"z(lambda ") for _ in raw_input(): try:[i,u][_ in e](e.get(_,e['$'])) except:break print d ``` *EDIT: thanks to @DLosc for the golfing help! Managed to reduce it by 85 bytes.* *EDIT2: cut out a ton of unnecessary wrappers, and dropped it by another 133 bytes!* *EDIT3: ...and 28 more thanks to @Sp3000 and @orlp in chat!* *EDIT4: with help from @orlp & @Sp3000, removed all the decorators and now it's 61 bytes shorter.* *EDIT5: help meeeeee, I can't stop golfing this.... 9 more bytes gone. Getting rid of the final print statement would save another 7, but then if you run m() in a loop, all the output is on the same line... is that ok?* Here's an ungolfed version: ``` stack = [] push = stack.append def arity(func,a=1): #give each of our functions an arity func.arity = a return func def do(func): ##pop the args off the stack, then call the function args = map(stack.pop,[-1]*func.arity) func(*args) def call(func,arg): #apply is just do(call) if func.arity == 1: func(arg) else: def curried(*a): #a quick little currier func(arg, *a) curried = arity(curried, func.arity - 1) push(curried) def clone(arg): push(arg) push(arg) def shift(func): def shifted(a, *arg): func(*arg) push(a) shifted = arity(shifted, func.arity + 1) push(shifted) def fork(a, b, c): if a == 0: push(b) else: push(c) def chain(func, gunc): def composition(*args): func(*args) do(gunc) composition = arity(composition, func.arity) push(composition) def say(arg): print '10'[arg == 0], push(arg) commands = {'?': 0, '+': arity(clone), '>': arity(shift), '/': arity(fork, 3), '$': arity(call, 2), '.': arity(chain, 2), '@': arity(say)} def interpret(input_string): for command in input_string: try: if command == '!': do(call) else: push(commands[command]) except RuntimeError: #this handles max recursion depth errors break # for infinite programs print if __name__ == "__main__": interpret(raw_input()) ``` Basic idea is that the python list works very nicely as a stack, and by storing `u=k.append`, not only do I save characters, ~~but I can also use `@u` as a decorator for pushing functions~~ (not anymore!). Since the couple of functions which act on functions of n-arity need to be able to accept an arbitrary number of arguments, I had to use `*args`, which meant that my original plan of tracking f.func\_code.co\_argcount had to be replaced by an arity ~~decorator~~ attribute. In terms of handling infinite programs, the interpreter runs until it hits max recursive depth; the RuntimeError handler at the bottom has it exit quietly at that point, and it prints out the current output string then. Test cases: ``` >>> tests ['?@!@@!', '$+.!!+!!', '?@$..!!+.!!+>!.!!!!+?/!!!@!@>!!!', '?@+$>!>!.!!+>!.!!///!!>!>!.!!+!!!!', '?@+$>!>!.!!+>!.!!///!!>!>!.!!+!!!!!!!', '?@+$>!>!.!!+>!.!!///!!>!>!.!!+!!!!!!!!!!', '?@+$>!>!.!!+>!.!!///!!>!>!.!!+!!!!!!!!!!!!!', '@?/!@>!.!!??/!!>!.!!+.!!.+>!.!!$$.!!$.!!$.!!+.!!$>!>!.!!$>!>!.!!+>!.!!$>!>!>!.!!+>!>!.!!///!!>!>!>!.!!+!!!!!'] >>> for t in tests: m(t) 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` [Answer] # Ghostscript Not golfed yet, since I still need to work out the parsing function. This implementation uses `_` and `:` instead of `>` and `/`, and it requires all the program characters to be separated with spaces. This is because `>` and `/` are not valid names in Postscript, and the operators are not self-delimiting, but this will be fixed when I write the parser. The first part of the code should be fairly transparent, as it is merely repeating the definitions of the operator functions. The magic happens in the definition of `!`. ``` /switch { /y exch def /x exch def {x} {y} ifelse } bind def /unwrap { dup type (arraytype) eq {aload pop} if } bind def /! { % IN: <x> <f> OUT: <g>|<f(x)> [ 3 1 roll unwrap] cvx %prefix argument into function dup /fun exch def %bind [ count 1 roll ] { %run the function sandboxed so it can't take any additional args 2 dict begin /=only {} def % suppress output { fun } stopped /err exch def clear err end } .runandhide exch { $error /errorname get (stackunderflow) ne { handleerror } if $error /newerror false put unwrap } { unwrap exec } ifelse } def /? 0 def /+ {{dup}} def /_ {{/f exch def pop f}} def % using _ instead of > /: {{? ne 3 1 roll switch}} def % using : instead of / /$ {{!}} def /. {{/g exch def exec g}} def /@ {{dup ? eq {0}{1} ifelse =only}} def ``` The way `!` works is simple: First, it adds argument `x` to `f` by prefixing `x` to the contents of `f`, pushing it back on the stack, and naming a copy of the result `fun`. It then wraps the entire stack up as an array. `.runandhide` is a [Ghostscript extension](http://www.ghostscript.com/doc/9.00/Language.htm#Miscellaneous) for running sandboxed code, hiding the contents of the preceding array from the procedure it is invoked on. The `dict` command pushes a new dictionary on the dict stack, narrowing the scope of names defined within until `end` pops it back off. It also replaces `=only` (the output operator I use in `@`) with a dummy one, suppressing the output during the trial run. `stopped` is the PostScript equivalent of the `try` statement found in other languages, and it returns true if its procedure threw an error, and false if it ran to completion. Once the trial run of `fun` completes, the program restores the original stack from the hidden array, and if `fun` completed without error, it then runs it for real, keeping the output. [Answer] # Python3, ~~685~~ ~~670~~ ~~634~~ 633 bytes I'm pretty sure this is the longest thing I've ever golfed. It used to be somewhat readable, but following @sirpercival's advice has eliminated *that* drawback! ``` from re import* E,*k="E" P="e(k.pop(),k.pop())" def H(a,b):global k;k+=list(a)+[N(b)];exec("k+=%s;"%P*Z(N(b)));return[] def e(a,b):a=sub("(?<!\d)0",repr(N(b,1)).replace("\\",r"\\"),a,1);return Z(a)and[a]or list(eval(a)) D=list(zip("ilhydsSNZ",[3,2,2]+[1]*6,sub("A","N(a)",',b,c:[N([b,c][a>E])]|,b:e(A,N(b))|,b:["H(%s,%s)"%(A,repr(b))]|:print(0+(a>E),end="")or[A]|:[A]*2|:["S(0,%s)"%A]|,b:b+[A]|,b=-1:sub("\d+",lambda m:str(int(m.group())+b),a)|:len(split("\D0",a))-1').split("|"))) for n,r,f in D:exec(n+"=lambda a"+f) F=dict(zip("/$.@+>?!",D)) for z in input():n,r,f=F[z];k+=z!="!"and[[n+"(%s)"%",".join("0"*r),E][z=="?"]]or eval(P) ``` `k` is the stack, which contains functions represented as strings like `"h(0,0)"` (which is *c**h**ain*). When a function is passed as an argument to another function, it gets `repr`'d and all the numbers incremented: `"h('h(1,1)',0)"`. Once all the `0`s are replaced in a function, the whole thing is passed to `eval`, thereby calling the appropriate Python function--most of which are lambda functions generated from the big string in line 6 by `exec` in line 7. Getting multiple levels of nested functions incremented, quoted, and escaped properly was the biggest headache. I could save a bit more on regex operations if I could assume that function nesting won't proceed any deeper than 9 levels, but as pointed out in comments that's probably not a safe assumption. Ungolfed earlier version of code: ``` from re import * E="E" stack=[] clone=lambda a:[unnest(a)]*2 shift=lambda a:["shifted(0,%s)"%unnest(a)] fork=lambda a,b,c:[unnest(c if a!=E else b)] call=lambda a,b:apply(unnest(a),unnest(b)) chain=lambda a,b:["chained(%s,%s)"%(unnest(a),repr(b))] def say(a): print(1 if a!=E else 0,end="") return [unnest(a)] shifted=lambda a,b:b+[unnest(a)] def chained(a,b): global stack stack+=list(a)+[unnest(b)] exec("stack+=apply(stack.pop(),stack.pop());"*zeros(unnest(b))) return [] nest=lambda a,direction:sub("\d+",lambda m:str(int(m.group())+direction),a) unnest=lambda a:nest(a,-1) zeros=lambda a:len(split("\D0",a))-1 def apply(a,b): a=sub("(?<!\d)0",repr(nest(b,1)).replace("\\",r"\\"),a,1) return [a] if zeros(a) else list(eval(a)) functions=dict(zip("+>/$.@",zip(["clone","shift","fork","call","chain","say"],[1,1,3,2,2,1]))) for cmd in input(): if"!"==cmd: stack+=apply(stack.pop(),stack.pop()) elif"?"==cmd: stack+=[E] else: name,arity=functions[cmd] stack+=[name+"(%s)"%",".join("0"*arity)] ``` The one potential flaw of this implementation is that it uses recursion, so programs that ought to be infinite hit the max recursion depth pretty quickly. (You probably want to redirect stderr when you run an infinite program--otherwise the stack trace will swamp the actual output.) Other than that, everything seems to be working. [Answer] # Ceylon, ~~1167~~ ~~1057~~ 1031 I don't get it that short as the mono-typed python versions ... `import ceylon.language.meta.model{N=Function}import ceylon.collection{H=HashMap}interface D of F|b{}object b satisfies D{}class F(shared Integer a,[D+](D+)f,[D*]c=[])satisfies D{shared[D+]o(D i){[D+]s=[i].prepend(c);return a==1then f(*s)else[F(a-1,f,s)];}shared[D+]y([D+]i){return f(*i.prepend(c));}}F m<A>(N<[D+],A>f)given A satisfies[D+]=>F(f.parameterTypes.size,(D+i)=>f.apply(*i));[D,D]e(D x)=>[x,x];[F]t(F f){[D+]g(D+i){assert(is[D+]r=i.rest);return[i[0],*f.y(r)];}return[F(f.a+1,g)];}[D]k(D a,D d,D c)=>a==b then[d]else[c];[D+]l(F a,D x)=>a.o(x);[F]n(F f,F g){[D+]h(D+i){[D+]r=f.y(i);assert(is[D+]d=r[0:g.a]);return g.y(d).append(r[g.a...]);}return[F(f.a,h)];}[D]y(D x){process.write(x==b then"0"else"1");return[x];}class I(){variable D[]s=[];value c=H{'?'->b,'+'->m(`e`),'>'->m(`t`),'/'->m(`k`),'$'->m(`l`),'.'->m(`n`),'@'->m(`y`)};shared void r(Character i){if(i=='!'){assert(is F f=s[0],is D x=s[1]);s=f.o(x).append(s[2...]);}else{assert(is D d=c[i]);s=[d].append(s);}}}shared void z(){process.readLine()?.collect(I().r);}` Here is a formatted (and commented) version of the same code (with spaces/newlines/comments it becomes 4867 bytes): ``` import ceylon.language.meta.model { N=Function } import ceylon.collection { H=HashMap } //↑ Import of stuff we need – with a shorter alias. // (The comment is down here due to a bug in my comment and space // remover – it doesn't remove a comment if it is the first token // at all.) // Our data items are either functions or blanks. interface D of F | b {} // There is no point in having many blanks – so here a singleton. object b satisfies D {} // The function class. Our functions take a number of data items, // and return a number of data items. // We know the arity a, and have also an actual function f, and a number // or already collected arguments. class F(shared Integer a, [D+](D+) f, [D*] c = []) satisfies D { // apply once (= collect one parameter). Returns either the result, // or a function with arity one less. shared [D+] o(D i) { [D+] s = [i].prepend(c); return a == 1 then f(*s) else [F(a - 1, f, s)]; } // apply fully (= with all needed parameters). // The input size should equal the arity. shared [D+] y([D+] i) { // merge collected and input arguments. return f(*i.prepend(c)); } } // creates a shift function from a ceylon function, // deriving the arity using reflection. F m<A>(N<[D+],A> f) given A satisfies [D+] => F(f.parameterTypes.size, (D+ i) => f.apply(*i)); // // clone: a unary function that duplicates its input: any value x is mapped to [x,x]. // [D, D] e(D x) => [x, x]; // // shift: a unary function that takes in an n-ary function f, and returns an // (n+1)-ary function g that ignores its first argument x, calls f on the // remaining ones, and tacks x in front of the result. For example, // shift(clone) is a binary function that takes inputs a,b and returns [a,b,b]. // [F] t(F f) { [D+] g(D+ i) { assert (is [D+] r = i.rest); return [i[0], *f.y(r)]; } return [F(f.a + 1, g)]; } // // fork: a ternary function that takes three inputs a,d,c, and returns [d] if a is a blank, // and [c] otherwise. // [D] k(D a, D d, D c) => a == b then [d] else [c]; // // call: a binary function that pops a function f and a value x, // and applies f to x exactly as ! does. // [D+] l(F a, D x) => a.o(x); // // chain: a binary function that pops two functions f and g, and returns their composition: // a function h that has the same arity as f, and which takes its inputs normally, applies // f to them, and then fully applies g to the result (calls it as many times as its arity // dictates), with unused items from the output of f remaining in the result of h. For // example, suppose that f is a binary function that clones its second argument, and // g is call. If the stack contains [f,g,a,b,c] and we do .!!, then it contains // [chain(f,g),a,b,c]; if we do !! next, then f is first applied to a,b, producing // [a,b,b], then g is applied to the first two elements of that since its arity is 2, // producing [a(b),b], and the stack will finally be [a(b),b,c]. // [F] n(F f, F g) { [D+] h(D+ i) { // call f, remember the results. [D+] r = f.y(i); // first some results from f are the arguments to g: assert (is [D+] d = r[0:g.a]); // remaining results from f are passed back directly, with the results from g. return g.y(d).append(r[g.a...]); } return [F(f.a, h)]; } // // say: a unary function that simply returns its input, and prints 0 if it was a blank, // and 1 if it was a function. // [D] y(D x) { process.write(x == b then "0" else "1"); return [x]; } // // Interpreter class, which manages the stack and interprets the commands. // Just call the r method with the individual command characters. // class I() { // The stack. The only variable in the whole program. variable D[] s = []; // a hash map of items to be pushed by commands, most build using the m function. // The apply command is not here, this is handled separately by the interpreter. value c = H { '?'->b, '+'->m(`e`), '>'->m(`t`), '/'->m(`k`), '$'->m(`l`), '.'->m(`n`), '@'->m(`y`) }; // Interprets one command, indicated by a character. // Will throw an AssertionError for unknown commands. shared void r(Character i) { if (i == '!') { assert ( is F f = s[0], is D x = s[1]); // apply f on x, push the result onto a shortened version of the stack. s = f.o(x).append(s[2...]); } else { assert (is D d = c[i]); // push d on top of the stack. s = [d].append(s); } } } shared void z() { process.readLine()?.collect(I().r); } ``` The functions clone `e`, shift `t`, fork `k`, call `l`, say `y` and chain `n` use the last letter of the names for the abbreviated version, because that gave less collisions. (Trivia: fork was originally defined this way: `[Data] fork(Data a, Data b, Data c) => a == blank then [b] else [c];` – when I renamed `blank` to `b`, this broke, because it now compared the parameters `a` and `b` instead `a` with the blank. Took me some time to debug.) The `z` function is shared because my IDE runs those functions – the command line tool can also run non-shared ones. ]
[Question] [ Terminals are so *boring* these days. They used to look like this: [![Terminal 1](https://i.stack.imgur.com/89f5kt.jpg)](https://i.stack.imgur.com/89f5k.jpg) [![Terminal 2](https://i.stack.imgur.com/yNfEbt.jpg)](https://i.stack.imgur.com/yNfEb.jpg) Now they're just bland and dull and black-and-white. I want you to write me a program that will make my terminal all colorful again! ## Description Take this example Ruby code: ![Example code](https://i.stack.imgur.com/pK1Fi.png) Most Linux terminals support these **escape sequences** (`\e` stands for the escape character), and Windows can support them with [ANSICON](https://github.com/adoxa/ansicon). Here is the syntax of the specific escape sequence that can change the text or background color of a string: ``` \e[{{COLOR}}m ``` where `\e` stands for the escape character (`0x1B` in ASCII) and `{{COLOR}}` is replaced by the number of the color that you want to use (more details on that later). Text that comes after this escape sequence will be formatted as directed, and a value of `0` will reset all formatting. Your challenge is to take a string specifying some text that may contain color, and output a colorful version of it. ## Input / Output Normal text works just like normal, and is printed literally. For example, the input `waffles` yields the same output, with no special color. The syntax for specifying a color is similar to [Wikipedia's syntax](http://en.wikipedia.org/wiki/Help:Using_colours#Overriding_font_colour). For example, to color the words "the color red" in red in the sentence `This is the color red!`, the input would be: ``` This is {{red|the color red}}! ``` Background colors work too. If you wanted black letters on a white background, you would use this: ``` {{black|white|This text is black on white}} ``` To get only a background color, omit the foreground: ``` {{|red|This text has a red background}} ``` ## Specification Two open curly brackets always specify the beginning of a **color directive**. Two closing curly brackets specify the end. Brackets will always match; there will never be a `{{` without a corresponding `}}`, and a `}}` will never come before its corresponding `{{`. These *color directives* will not be nested, and a `{{` will never appear within a color directive. Within a color directive, there will always be either one or two `|` symbols. If there is one, the text before it is the foreground color and the text after is the string to show in that color. If there are two, the text before the first one is the foreground color, the text after the first but before the second is the background color, and the text after the second is the string to display. These vertical bars may exist outside of a color directive, and should be printed literally. The foreground color or background color (but not both) may be empty, in which case you should leave them as the default. The final string (the one to output) will never be empty. Here are the directions to output text of a certain color: * A **color sequence** is defined in the "Description" section. For example, a color sequence of 42 would be `"\e[42m"`. * To set a color, print the color sequence of the number determined below: ``` Color name | Color sequence number (foreground / background) --------------+---------- black | 30 / 40 red | 31 / 41 green | 32 / 42 yellow | 33 / 43 blue | 34 / 44 magenta | 35 / 45 cyan | 36 / 46 lightgray | 37 / 47 darkgray | 90 / 100 lightred | 91 / 101 lightgreen | 92 / 102 lightyellow | 93 / 103 lightblue | 94 / 104 lightmagenta | 95 / 105 lightcyan | 96 / 106 white | 97 / 107 ``` * Color names are case sensitive, and an invalid color name will never be provided. You don't have to handle stuff like `RED` or `lightgrey` (spelled with an `e`). * After you print a color sequence, it will apply for all text following it. To end a color sequence (reset to the default color), output a color sequence of `0` (`"\e[0m"`). ## Test case ``` {{|yellow| }} {{|yellow| }} {{|yellow| }} {{|yellow| }} {{red|'}} {{red|'}} {{|yellow| }} {{|yellow| }} \_/ {{|yellow| }} {{|yellow| }} {{|yellow| }} {{|yellow| }} ``` This should output a smiley face... with evil red eyes. ## Rules * You may not use any libraries or functions of your programming language to automatically parse a color. This means that *you* must be the one to determine what `"red"` means; you can't have a library automatically do that for you. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! [Answer] ## Ruby, ~~205~~ ~~189~~ ~~188~~ ~~186~~ ~~185~~ ~~182~~ ~~174~~ ~~170~~ ~~165~~ ~~161~~ ~~159~~ 154 bytes Putting long strings of color names in your code doesn't look nerdy enough. Down to 170 partly thanks to `rubik`. Now the scrolling bars are gone! One obvious and one not so obvious improvement, thanks to the flex answer, without the improvement to it, I wouldn't have revisited this! Not anymore, I saved 4 bytes with #sum. ~~I didn't intend it, but I just noticed this solution is case-insensitive as well. It happily processes `{{RED|Red text}}`.~~ Hex dump: ``` 0000000: 7a3d 2d3e 6a7b 693d 2240 3054 2d44 1547 z=->j{i="@0T-D.G 0000010: 5155 0034 3256 2f46 1749 0b22 2e69 6e64 QU.42V/F.I.".ind 0000020: 6578 2028 415b 6a5d 2e74 6f5f 732e 7375 ex (A[j].to_s.su 0000030: 6d25 3839 292e 6368 723b 692b 3d69 3e39 m%89).chr;i+=i>9 0000040: 3f38 303a 3330 7d0a 243e 3c3c 243c 2e72 ?80:30}.$><<$<.r 0000050: 6561 642e 6773 7562 282f 7b7b 282e 2a3f ead.gsub(/{{(.*? 0000060: 297d 7d2f 297b 413d 2431 2e73 706c 6974 )}}/){A=$1.split 0000070: 277c 273b 221b 5b25 693b 2569 6d23 7b41 '|';".[%i;%im#{A 0000080: 2e70 6f70 7d1b 5b30 6d22 255b 7a5b 305d .pop}.[0m"%[z[0] 0000090: 2c31 302b 7a5b 315d 5d7d ,10+z[1]]} ``` You can convert it with `xxd -r hex.dump`. The program with all non-printable characters escaped for reference purposes: ``` z=->j{i="@0T-D\x15GQU\x0042V/F\x17I\v".index (A[j].to_s.sum%89).chr;i+=i>9?80:30} $><<$<.read.gsub(/{{(.*?)}}/){A=$1.split'|';"\x1b[%i;%im#{A.pop}\x1b[0m"%[z[0],10+z[1]]} ``` That is one line. Use it like this ``` ruby colors.rb -W0 < input.txt ``` The `-W0` flag suppresses warnings that would be sent to `stderr` otherwise. However, the program works fine without any flags. Output: ![output](https://i.stack.imgur.com/NZk45.png) [Answer] # Ruby, 329 bytes. ``` h={};(y=0..15).each{|i|h[%w(black red green yellow blue magenta cyan lightgray darkgray lightred lightgreen lightyellow lightblue lightmagenta lightcyan white)[i]]=y.map{|j|[30,40].map{|k|k+i%8+i/8*60}}[i]} loop{puts gets.gsub(/{{.+?}}/){|x|"\e[#{h[(g=x.scan(/[^{}|]+/))[0]][0]}m#{(g[2]? "\e[#{h[g[1]][1]}m":'')}#{g.last}\e[0m"}} ``` [Answer] ## Flex (lexer) - ~~226~~ ~~197~~ ~~192~~ ~~182~~ 168 (or 166) To get it down to 166, change the `\33` to an actual escape character. ``` int z;p(i){printf("\33[%dm",i);} %% "{{" z=2; [a-z]*\| if(!z)REJECT;~-yyleng&&p("062q00t03058ns7uo0p90r4"[*(int*)&yytext[yyleng>7?4:0]%131%27]-10*z);z--; "}}" p(z=0); ``` Compile and run: ``` $ flex -o colour.c colour.l $ gcc -o colour colour.c -lfl $ ./colour < input ``` [Answer] ## Python - 351 ``` import re,sys R=range E=lambda n,d=0:'\033[%dm'%(T[n]+d)if n else'' def P(m):f,b,t=m.groups();return'%s%s%s\033[0m'%(E(f),E(b,10),t) x='!red!green!yellow!blue!magenta!cyan'.replace T=dict(zip(('black'+x('!',' ')+' lightgray darkgray'+x('!',' light')+' white').split(),R(30,38)+R(90,98))) print re.sub(r'{{(\w+)?\|?(\w+)?\|?(.+?)}}',P,sys.stdin.read()) ``` [Answer] # Cobra - 496 It could *almost* be a single print statement. ``` use System.Text.RegularExpressions class P def main print Regex.replace(Console.readLine,r'\{\{('+(l=List<of String>(((m=' black red green yellow blue magenta cyan'.split).join(' ')+' lightgray darkgray'+m.join(' light')+' white').split))[1:].join('|')+r')?\|?('+l[1:].join('|')+r')?\|(.*?)\}\}',do(a as Match)) return if(x=l.indexOf('[a.groups[1]]'),r'\e['+'[if(x>8,x+81,x+29)]m','')+if(y=l.indexOf('[a.groups[2]]'),r'\e['+'[if(y>8,y+91,y+39)]m','')+'[a.groups[3]]'+if(x+y,r'\e[0m','') ``` [Answer] ## Python, 561 Reads the text to format from stdin. ``` import re,sys def p(f,b,t): p='' m='\033[%dm' if f!=0:p+=m%f if b!=0:p+=m%b return p+t+m%0 def c(n,b=0): s='black:30#red:31#green:32#yellow:33#blue:34#magenta:35#cyan:36#lightgray:37#darkgray:90#lightred:91#lightgreen:92#lightyellow:93#lightblue:94#lightmagenta:95#lightcyan:96#white:97' r=0 for i in s.split('#'): (t,c)=i.split(':') if t==n: r=int(c) if b==1:r+=10 return r def r(m): i=m.groups() f=b=0 if i[0]!='':f=c(i[0]) if i[1]!=None:b=c(i[1],1) return p(f,b,i[2]) print re.sub('{{(\w*)\|(?:(\w*)\|)?([^}]+)}}',r,sys.stdin.read()) ``` ]
[Question] [ Given that the Chinese New Year is coming, here is a challenge to calculate the Chinese Zodiac, element and Taijitu for a given date. The input should be a date: ``` 1/31/2014 ``` The date used here is the US style `mm/dd/yyyy`, but may alternatively be ISO-8601 style: `yyyy-mm-dd` so the style of date input is not strict. The output should be the animal sign in the [Chinese Zodiac](http://en.wikipedia.org/wiki/Chinese_zodiac) including the element that corresponds to the date, and its [Taijitu](http://en.wikipedia.org/wiki/Taijitu) counterpart: ``` Horse - Wood - Yang ``` A table showing the Zodiac - element - Taijitu relationship can be seen here: [Chinese Zodiac - Years](http://en.wikipedia.org/wiki/Taijitu) The output format is not strict but should contain animal, element and Taijitu component, and should be delimited in some fashion. Examples of valid output for the above date might include: ``` (horse, wood, yang) ["Horse", "Wood", "Yang"] ``` Your program should return valid output for a range of at least 100 years, including today's date. This means that it will need to account for at least two 60 year ([Sexagenary](http://en.wikipedia.org/wiki/Sexagenary_cycle)) cycles. [Answer] ## Mathematica 63 Okay, this may be getting old, but it works (date input is ambiguous in many cases): ``` z=WolframAlpha[#<>" Chinese zodiac",{{"Result",1},"Plaintext"}] & ``` Example: ``` z@"1/31/2014" ``` > > "Horse (Yang Wood)" > > > [Answer] ## C# – ~~357~~ ~~337~~ 339 bytes ``` string Z(System.DateTime d){var c=new System.Globalization.ChineseLunisolarCalendar();var y=c.GetSexagenaryYear(d);var s=c.GetCelestialStem(y)-1;return",Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[c.GetTerrestrialBranch(y)]+" - "+"Wood,Fire,Earth,Metal,Water".Split(',')[s/2]+" - Y"+(s%2>0?"in":"ang");} ``` Formatted: ``` string Z(System.DateTime d) { var c = new System.Globalization.ChineseLunisolarCalendar(); var y = c.GetSexagenaryYear(d); var s = c.GetCelestialStem(y) - 1; return ",Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[c.GetTerrestrialBranch(y)] + " - " + "Wood,Fire,Earth,Metal,Water".Split(',')[s / 2] + " - Y" + (s % 2 > 0 ? "in" : "ang"); } ``` [Answer] # Python 2: 360\* ~~387~~ ~~586~~ ~~594~~ - Characters Reduced further ``` m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2] ``` The above code works for the following interval: 5 Feb 1924 – 31 Dec 2043 Example: after pasting the above code in the python interpreter cursor ``` >>> m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2] ``` and then press `Enter`, input a date like this ``` 6/13/2018 ``` and then press `Enter` again, output will be ``` Dog Earth Yang ``` --- \* reduced further 27 bytes [with Brian's help](http://www.reddit.com/r/Python/comments/2oqobw/code_golf_calculate_chinese_zodiac_sign/) see comments. [Answer] ## Ruby, 340 ``` m,d,y=gets.split(?/).map(&:to_i);y+=1if 31*m+d-51>"d88jac8mlbuppp21ygmkjsnfsd4n3xsrhha4abnq9zgo6g2jupc39zav84434f75op4ftfhdcsa3xhc8nsw1ssw8p9qns1tf14mncy8j18msr9rsb7j7".to_i(36)>>5*y-9625&31 $><<[%w(Goat Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse)[y%12],%w(Metal Water Wood Fire Earth)[(y-1)/2%5],%w(Yin Yang)[y%2]]*' - ' ``` This will work for dates between Feb 5, 1924 and Jan 29, 2044. [Answer] ## GolfScript (212 chars) This uses non-printable characters, so here's the output from xxd: ``` 0000000: 272d 272f 6e2a 7e5c 2833 312a 2b5c 3a5e '-'/n*~\(31*+\:^ 0000010: 3139 2a22 d4e3 275a 747f 878c 70cb 996d 19*"..'Zt...p..m 0000020: a4f9 19e9 699e d818 bb61 c4e3 2232 3536 ....i....a.."256 0000030: 6261 7365 2033 6261 7365 5e31 3932 322d base 3base^1922- 0000040: 3c7b 282d 7d2f 3330 2532 312b 3e5e 352d <{(-}/30%21+>^5- 0000050: 2b3a 5e31 3225 2752 6174 0a4f 780a 5469 +:^12%'Rat.Ox.Ti 0000060: 6765 720a 5261 6262 6974 0a44 7261 676f ger.Rabbit.Drago 0000070: 6e0a 536e 616b 650a 486f 7273 650a 476f n.Snake.Horse.Go 0000080: 6174 0a4d 6f6e 6b65 790a 526f 6f73 7465 at.Monkey.Rooste 0000090: 720a 446f 670a 5069 6727 6e2f 3d6e 5e32 r.Dog.Pig'n/=n^2 00000a0: 2f35 2527 576f 6f64 0a46 6972 650a 4561 /5%'Wood.Fire.Ea 00000b0: 7274 680a 4d65 7461 6c0a 5761 7465 7227 rth.Metal.Water' 00000c0: 6e2f 3d6e 5e31 2627 5961 6e67 0a59 696e n/=n^1&'Yang.Yin 00000d0: 276e 2f3d 'n/= ``` An equivalent program which uses string escapes and is hence a bit longer is: ``` '-'/n*~\(31*+\:^19*"\xD4\xE3'Zt\x87\x8Cp\xCB\x99m\xA4\xF9\x19\xE9i\x9E\xD8\x18\xBBa\xC4\xE3"256base 3base^1922-<{(-}/30%21+>^5-+:^12%'Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig'n/=n^2/5%'Wood Fire Earth Metal Water'n/=n^1&'Yang Yin'n/= ``` The interesting part is computing, given the date, whether it is before or after the Chinese New Year which falls in that Gregorian year. Taking inspiration from the [Easter calculation algorithm](https://codegolf.stackexchange.com/a/11212/194) which I've used on a previous question, I looked for a reasonably simple calculation of the New Year date. In the end I've gone with a simple formula which gets me most of the way there, plus a lookup table for the error term. The simple calculation is `day_of_year = 21 + (19 * year % 30)`. The error term ranges from `0` to `8` over the range of interest (1924 to 2044), and never changes from year to year by more than one, so the lookup table is encoded in balanced ternary and the error is computed by summing the error terms of a prefix of the table. [Answer] ## C#, 630 611 604 572 570 bytes, 120 years ### (add ~2⅔ bytes per additional year if you know the offset) This is good for people born 31-Jan-1900 through 24-Jan-2020 and will likely crash outside of that range. Are there bonus points for the number of years covered? ``` string Z(DateTime date) { int[] days = new int[] { 3, 22, 11, 1, 19, 7, -3, 16, 5, -6, 13, 2, 21, 9, -2, 17, 6, -5, 14, 4, 23, 11, 0, 19, 8, -3, 16, 5, -5, 13, 2, 20, 9, -2, 17, 7, -4, 14, 3, 22, 11, -1, 18, 8, -3, 16, 5, -6, 13, 1, 20, 9, -1, 17, 6, -4, 15, 3, 21, 11, 0, 18, 8, -3, 16, 5, -7, 12, 2, 20, 9, -1, 18, 6, -5, 14, 3, 21, 10, 0, 19, 8, -3, 16, 5, 23, 12, 1, 20, 9, -1, 18, 7, -5, 13, 3, 22, 10, 0, 19, 8, -4, 15, 4, -6, 12, 1, 21, 10, -2, 17, 6, -5, 13, 3, 22, 11, 0, 19, 8 }; string[] signs = "Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(','); string[] elements = "Metal,Water,Wood,Fire,Earth".Split(','); string[] polarities = new string[] { "Yang", "Yin" }; int year = date.Year - 1900; int x = year - (date.DayOfYear < days[year] + 28 ? 1 : 0); return signs[x % 12] + " - " + elements[x / 2 % 5] + " - " + polarities[x % 2]; } ``` Or condensed (with added line breaks): ``` string Z(DateTime d){ int y=d.Year-1900, x=y-(d.DayOfYear<new[]{3,22,11,1,19,7,-3,16,5,-6,13,2,21,9,-2,17,6,-5,14,4,23,11,0,19,8,-3,16,5,-5,13,2,20,9,-2,17,7,-4,14,3,22,11,-1,18,8,-3,16,5,-6,13,1,20,9,-1,17,6,-4,15,3,21,11,0,18,8,-3,16,5,-7,12,2,20,9,-1,18,6,-5,14,3,21,10,0,19,8,-3,16,5,23,12,1,20,9,-1,18,7,-5,13,3,22,10,0,19,8,-4,15,4,-6,12,1,21,10,-2,17,6,-5,13,3,22,11,0,19,8}[y]+28?1:0); return "Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig".Split(',')[x%12]+" - "+"Metal,Water,Wood,Fire,Earth".Split(',')[x/2%5]+" - "+new[]{"Yang","Yin"}[x%2]; } ``` One of the tricks was to have the offset table's origin at 28-Jan. This proved to have the lowest character count. If by chance it is insisted the input is a string, add 22 characters to change the method signature to: ``` string Z(string i){ ``` and add the line: ``` var d=DateTime.Parse(i); ``` **EDITS:** * Put all strings in one array and added offsets to the output selectors. * Changed the day offset to 28-Jan. * `string.Split()` Inspiration taken from [Eduard Florinescu's answer](https://codegolf.stackexchange.com/a/19047/4934). * Inlined all arrays. It only saved me 2 characters. :-/ ]
[Question] [ Find the shortest regex that matches all radioactive elements and nothing else in the Periodic Table of Elements. Radioactive Elements ``` 'Technetium','Promethium','Polonium','Astatine','Radon','Francium','Radium','Actinium','Thorium','Protactinium','Uranium','Neptunium','Plutonium','Americium','Curium','Berkelium','Californium','Einsteinium','Fermium','Mendelevium','Nobelium','Lawrencium','Rutherfordium','Dubnium','Seaborgium','Bohrium','Hassium','Meitnerium','Darmstadtium','Roentgenium','Copernicium','Ununtrium','Flerovium','Ununpentium','Livermorium','Ununseptium','Ununoctium' ``` Non-radioactive Elements ``` 'Hydrogen','Helium','Lithium','Beryllium','Boron','Carbon','Nitrogen','Oxygen','Fluorine','Neon','Sodium','Magnesium','Aluminium','Silicon','Phosphorus','Sulphur','Chlorine','Argon','Potassium','Calcium','Scandium','Titanium','Vanadium','Chromium','Manganese','Iron','Cobalt','Nickel','Copper','Zinc','Gallium','Germanium','Arsenic','Selenium','Bromine','Krypton','Rubidium','Strontium','Yttrium','Zirconium','Niobium','Molybdenum','Ruthenium','Rhodium','Palladium','Silver','Cadmium','Indium','Tin','Antimony','Tellurium','Iodine','Xenon','Caesium','Barium','Lanthanum','Cerium','Praseodymium','Neodymium','Samarium','Europium','Gadolinium','Terbium','Dysprosium','Holmium','Erbium','Thulium','Ytterbium','Lutetium','Hafnium','Tantalum','Tungsten','Rhenium','Osmium','Iridium','Platinum','Gold','Mercury','Thallium','Lead','Bismuth' ``` * Scored by character count in the regex. * Use standard Perl regex (just no specialized functions). * Assume all lower case. * You only need to count the characters of the regex itself. Note if you used a program to get you started and maybe post how well it did. I'll post my best attempt as an answer to get started/show an example. [Answer] **Char Count 61** ``` lon|ct|oh|^ra|...t.+i|^c?u|or.+u|r.+c.|e..+e|f.?e|^h?as|be*.i ``` ~~One~~ 3 characters better than accepted answer! 63-character solution found with [Peter Norvig's Regex golf solver.](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313-part2.ipynb?create=1) 61-character improvement found by a personal rewrite of that program in Go. [Answer] **Char count 64** ``` ^(c?u|ra|no)|e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|f.r|ac|sta|bn|has ``` Should note, used parts of qw3n solution to reduce down my solution. Also used Peter Taylor's suggestion to trim two characters. [Answer] ### Char count 59 ``` e.+[hktv]|oh?r.+m|p...?o|r.*ci|be?.i|^c?u|rad|sta|has|ct|fe ``` Found via a mix of manually selecting good parts and running [Peter Norvig's golfer](http://nbviewer.jupyter.org/url/norvig.com/ipython/xkcd1313-part2.ipynb) on the remaining items. [Regex101 link](https://regex101.com/r/lG2qR9/1) [Answer] **Char count 69** ``` ^u|e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|^cu|f[oe]|a[cds]t|has|nob|rad|du ``` Curium/Cerium are a pain to deal with ]
[Question] [ [Shamir's secret sharing scheme](http://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing) is a simple way of protecting a secret by splitting it into several parts needed to reconstruct it. Your task is to implement Shamir's Secret Sharing reconstruction over the [Finite Field](http://en.wikipedia.org/wiki/Finite_field) defined by the prime `1928049029`. If you have any doubts about what this means, just ask or see Finite Field & [Finite Field Arithmetic](http://en.wikipedia.org/wiki/Finite_field_arithmetic) in wikipedia (more resources below). ## Input Input is done using stdin. First comes an integer `k`, then k lines follow. Each of these lines contains a pair of integers `x y` that represent a secret. In other words `f(x) = y` in the original polynomial that was used to construct the secrets. The number of secrets given is always enough to construct the corresponding secret. ## Output Output to stdout the reconstructed secret. ## Examples **Input:** ``` 5 1 564797566 2 804114535 4 1354242660 6 1818201132 7 503769263 ``` **Output:** ``` 1234 ``` **Input:** ``` 7 1 819016192 2 1888749673 3 1737609270 4 365594983 5 1628804870 6 1671140873 7 492602992 ``` **Output:** ``` 456457856 ``` ## Resources [Wikipedia article](http://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing) [Paper](http://szabo.best.vwh.net/secret.html) [Finite field](http://en.wikipedia.org/wiki/Finite_field) Source: Wikipedia [Finite field arithmetic](http://en.wikipedia.org/wiki/Finite_field_arithmetic) Source: Wikipedia [Lagrange polynomial](http://en.wikipedia.org/wiki/Lagrange_polynomial) Source: Wikipedia [Chapter on Finite field arithmetic](http://docs.google.com/viewer?a=v&q=cache%3aCmQSTh2WDeIJ%3awww.springer.com/%3FSGWID%3D2-102-45-110359-4+finite+field+arithmethics&hl=en&pid=bl&srcid=ADGEESikdA6tzTfrWAdoudGolj3rW6eFLQGVnUSdnS3Yl_viLtytnZQUs868ulwqWbdYUCecDNUMQSVou0ItLhhJstUITdUsBbokZuArnDGoB5MzcuAPdz-iODPRYdX0OPRB0kxa2ttL&sig=AHIEtbTNiW7G-8mbUMBt1YEcLTiRDy7eXw) [Answer] ### bash, 271 chars ``` r(){ [ ${1/0/} ]&&{ r $(($2%$1)) $1;((t=u,u=v-$2/$1*u,v=t));} } read ((N=1928049029,n=0)) while read x[$n] y[$n] do((n++)) done for((i=n;z=(z+l)%N,i--;))do for((j=n,l=y[i];j--;))do ((u=0,v=1,d=x[j]-x[i],M=N+d)) r M N [ ${d/0/} ]&&((l=l*x[j]%N*(u+N)%N)) done done echo $z ``` The newlines could be replaced in most cases with semicolons, but I don't think there's any unnecessary whitespace. (I hadn't realised before today that bash's integers are 64-bit - very helpful). For bash the recursive GCD (exploiting global state) seems to be more compactible than the iterative one. This is mostly straightforward; the interesting trick is `[ ${d/0/} ]&&foo` which is effectively `if [ $d -ne 0 ];then foo;fi` [Answer] 199 characters in Octave: ``` m=@(x)mod(x,1928049029);[d,l]=scanf('%d');c=d(1);e=repmat(int64(d(2:2:l)),1,c);[_,b]=gcd(e-e',1928049029*ones(c));b=eye(c)+m(e.*b);x=b(1,:);for i=2:c;x=m(x.*b(i,:));end;disp(m(sum(m(x'.*d(3:2:l))))) ``` [Answer] ### Golfscript, 114 112 111 110 109 65 (86) chars If you don't care about getting results this week, 65 chars suffice: ``` ~](;2/0\:X{~\.X{0=}%^\{\.@- 1928049029:P.,\@{@*\%(!}++?**}+/+P%}/ ``` But if you're looking for efficiency, it's slightly longer at 86 chars: ``` ~](;2/0\:X{~\.X{0=}%^\{\[.0](@-[1928049029:P%P]{.~/{\.(;@@~@*-+\}+2*.1=}do;0=*}+/+P%}/ ``` This is dissected in far more detail than I want to repeat here [on my blog](http://www.cheddarmonk.org/golfscriptblog/2011/10/code-dissection-secret-sharing.html). --- Mainly not my work, but cribbing heavily from Nabb gives 47 chars: ``` n%(!\:A{~A{~;.3$- 1928049029:N((?1or**}/\/+N%}/ ``` Note: I've only reasoned about this code: trying to run it would be pointless given the length of time and amount of memory it would use. [Answer] ## Golfscript - ~~52~~ 46 (67) A brute force approach for modular inverses in 46 characters. Repeatedly computes a^(N-2) with arbitrary precision integers. ``` n%(!\:A{~A{~;.3$-.!+1928049029:N((?**}/\/+N%}/ ``` Implementing the extended Euclidean algorithm only costs us an additional 15 characters. ``` n%(!\:A{~A{~;.3$-:|!1\1928049029:N{@2$|3$/*-\|\:|%.}do;;**}/\/+N%}/ ``` This code is fully detailed on my [blog post](http://golfscript.blogspot.com/2011/10/code-golf-shamirs-secret-sharing.html), including some alternatives for computing the modular multiplicative inverse. [Answer] **Lua 444 Chars** Works for the example on the wiki page ``` 3 2 1942 4 3402 5 4414 ``` But somehow does not work for the examples here on this page. If anyone can find the error? Non-golfed version: ``` -- Reconstruct shamir secret -- convention, poly = {[0]=a0,a1,...,an} i=io.read f=math.fmod w=1928049029 k=i():match"%d+" x={} -- Will contain X values y={} -- Will contain Y values p={} -- will contain lagrange polynomials -- Read data for j=0,k-1 do x[j],y[j]=i():match("(%d+) (%d+)") print(j,x[j],y[j]) end -- Multiplication and scaling function function mul(p,q,s) -- multiply polies r={} -- poly to be returned for k=0,#p do for l=0,#q do r[l+k]=r[l+k] or 0 -- if the coeff for degree l+k of x doesn't exist, put 0 p[k]=p[k] or 0 -- if p hasn't got a coeff for x^k q[l]=q[l] or 0 -- idem for q r[l+k]=(r[l+k]+s*p[k]*q[l]%w -- calculate increment for coeff for x^(l+k) end end -- Debugging io.write"Multiplied " printPoly(p) io.write"With " printPoly(q) io.write("And scaling factor ",tostring(s),"\n") io.write"Yielding " printPoly(r) return r end function printPoly(p) -- "Pretty" printing of the polynomial for k=#p,1,-1 do io.write(tostring(p[k] or 0),"x^",tostring(k),"+") end io.write(p[0]) io.write"\n" end function egcd(a,b) if a == 0 then return b, 0, 1 else local g, y, x = egcd(b % a, a) return g, x - math.floor(b / a) * y, y end end function inv(a,m) a=a>=0 and a or a+m local g,x,y = egcd(a,m) if g== 1 then return x%m else print(a,"has no inverse mod",m) end end -- generate lagrange polynomials for j=0,#x do print("j=",j,"*********") for m=0,k-1 do if m~=j then -- if m==j, continue p[j]=p[j]or{[0]=1} -- if this poly doesn't exist, take 1 p[j]=mul( p[j], {[0]=-x[m],1},inv(x[j]-x[m],w))-- multiply with (x-x_m)/(x_j-x_m) io.write"---------------------------------\n" end end end r=0 -- Result for x^0 for k=0,#p do print("l_"..k) printPoly(p[k]) -- print l_k r=r+f(y[k]*p[k][0],w) -- add coeff for x^0 to result end print("Secret was",f(r,w)) -- display result ``` Golfed (not using finite field), 444 chars: ``` i=io.read f=math.fmod w=1928049029 k=i():match"%d+"x={}y={}p={}for j=0,k-1 do x[j],y[j]=i():match("(%d+) (%d+)")end function mul(p,q,s)r={}for k=0,#p do for l=0,#q do r[l+k]=r[l+k]or 0 p[k]=p[k]or 0 q[l]=q[l]or 0 r[l+k]=f(r[l+k]+s*p[k]*q[l],w)end end return r end for j=0,#x do for m=0,k-1 do if m~=j then p[j]=p[j]or{[0]=1}p[j]=mul(p[j],{[0]=-x[m],1},1/(x[j]-x[m]))end end end r=0 for k=0,#p do r=r+f(y[k]*p[k][0],w)end print(f(r,w)) ``` [Answer] ### Java, 435 407 chars ``` import java.util.*;public class G{public static void main(String[]args){Scanner s=new Scanner(System.in);int i,k,n=s.nextInt();long N=1928049029L,x[]=new long[n],y[]=new long[n],z=0,l,c;for(i=n;i-->0;){x[i]=s.nextInt();y[i]=s.nextInt();}for(i=n;i-->0;){l=y[i];for(long j:x)if(x[i]!=j){c=1;for(long a=N+j-x[i],b=N,d=0,t;b>0;){t=d;d=c-a/b*d;c=t;t=b;b=a%b;a=t;}l=l*j%N*(c+N)%N;}z+=l;}System.out.println(z%N);}} ``` Ungolfed: ``` import java.util.*; public class G { public static void main(String[] args) { Scanner s=new Scanner(System.in); int i,k,n=s.nextInt(); long N=1928049029L,x[]=new long[n],y[]=new long[n],z=0,l,c; for (i=n; i-->0;) { x[i]=s.nextInt(); y[i]=s.nextInt(); } for (i=n; i-->0;) { l=y[i]; for (long j:x) if (x[i]!=j) { // Extended Euclid algorithm - iterative version - // to find the reciprocal of j-x[i] (mod N) c=1; for (long a=N+j-x[i], b=N, d=0, t; b>0;) { t=d; d=c-a/b*d; c=t; t=b; b=a%b; a=t; } l = l*j%N; l = l*(c+N)%N; } z+=l; } System.out.println(z%N); } } ``` [Answer] # Haskell, 183 ``` p=1928049029 a#0=(1,0) a#b=let(s,t)=b#mod a b in(t,s-div a b*t) s d=sum[y*product[z*fst((z-x)#p)|[z,_]<-d,z/=x]|[x,y]<-d] main=interact$show.(`mod`p).s.map(map read.words).tail.lines ``` ]
[Question] [ [Knight](https://github.com/knight-lang/knight-lang) is the [Language of the Month for August 2022](https://codegolf.meta.stackexchange.com/questions/25002/language-of-the-month-for-august-2022-knight), and I noticed that it didn't have a [tips](/questions/tagged/tips "show questions tagged 'tips'") page, so here it is! 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 Knight (e.g. "remove comments" is not an answer). Please post only one tip per answer. [Answer] Variables in Knight consist of a lowercase letter followed by additional lowercase letters or numbers, but not uppercase letters. This means that you don't need a space between a variable and a function call -- e.g. ``` Oa Ob OaOb ``` But you can't do ``` O+a1 ``` because the `1` will be parsed as part of the variable name. To get around this, swap the argument order: ``` O+1a ``` [Answer] # Use coercion For example, in the case that `+` receives a string as the first and a number as the second arg, it will coerce the second one to a string and concatenate them. However, if you do it vice versa, with a number as the first and a string as the second, it will convert the second to a number and add the two. This means that you can use `+0` to convert a string to a number, and `+""` to convert a number to a string. However, sometimes, `+0` can be one byte shorter! `E`, the evaluate function, will evaluate its argument as Knight code. So given a number-string, it will convert to a number. Often, however, this will cost 1 or 2 bytes due to whitespace being needed. With `*`, if the first argument is a string and the second a number, it will repeat the string n times instead of multiplying. In the case of num+str, it will coerce the string to a number. And with str+str, it will coerce the second to a number and repeat the first string that many times. However, with `-`, `/`, `^`, and `%`, if the first is a number, the second will be converted to a number. But if the first is a string, it's undefined behavior. Some other operators like `<` and `>` will also coerce - [see the spec](https://github.com/knight-lang/knight-lang/blob/master/specs.md). [Answer] # Using `&` and `|` instead of `IF` Unless you need both the if true and if false clauses of `IF`, you can simply use `&` or `|`. Instead of `Ifoo bar <whatever>`, you can do `&foo bar`. Likewise, instead of `Ifoo <whatever> bar` (or `I!foo bar <whatever>`), you can do `|foo bar`. [Answer] The `ASCII` function in Knight, if given a string, returns the ASCII value of just the first character of a string; if given a number, it returns the ASCII character with that code point. This means that `ASCII (ASCII s)` will return the first character of string `s`. You can use this along with `GET` to iterate through a string: ``` ;=pP;=i~1W<=i+1iLpO Gp i 1 ;=pP Wp;O A Ap=pGp 1Lp ``` Here's the code snippets written out in easier to understand format, with basically equivalent Python code on the side: ``` ;= p PROMPT # p = input() ;= i ~1 # i = -1 WHILE (< (= i (+1 i)) (LENGTH p) # while (i = i+1) < len(p): OUTPUT (GET p i 1) # print(p[i:i+1]) ;= p PROMPT # p = input() WHILE p # while p != "": ;OUTPUT (ASCII (ASCII p)) # print(p[0]) = p (GET p 1 (LENGTH p)) # p = p[1:len(p)+1] ``` Technically, the call to `Gp 1Lp` is undefined since `+ 1 LENGTH p` is outside of the bounds of the string `p`. In order to make it fully spec-compliant, it would have to be ``` ;=pP Wp;O A Ap=pGp 1-Lp 1 ``` However, the first version works within the C TIO. *Edit:* [Using @Sampersand's suggestions](https://codegolf.stackexchange.com/a/251090/113573), you could alternatively do ``` ;=pP Wp;O GpF1=pSpF1"" ``` Which is the same number of characters but spec-compliant. In this case, we can additionally use the fact that `OUTPUT` returns a falsy value to shorten it to ``` ;=pP Wp=pSpO GpF1T"" ``` Which saves two bytes. [Answer] Since the assignment operator in Knight returns the assigned value, you can chain together definitions if, for example, you want to create multiple variables with the same value: ``` ;=a 0;=b 0=c 0 =a=b=c 0 ``` [Answer] At the risk of stating the obvious, all functions can be abbreviated to a single uppercase character. For example: ``` OUTPUT 1 O 1 ``` You also can remove the space between the function and the parameter: ``` O1 ``` But if you want to nest function calls, you need to put a space between them: ``` OP # Parsed as a single function "OP", which is equivalent to "OUTPUT" O P # Parsed as "OUTPUT PROMPT" ``` [Answer] # Use `T` or `F` instead of `1` or `0` to save a character Examples: ### Save a byte when initializing to 0 Instead of `;=n 0` you can do `;=nF`, but this will require you to ensure that you're coercing `a` later on. But, if you're using `n` as a counter, you can simply do `W>100=n+1n`, which'll coerce the initial `F` to `0`. ### Getting the first character of a string Instead of `Gs 0 1`, you can do `GsF1`—since all arguments to `G` are coerced to the appropriate types, this'll always work. ### Getting the rest of a string Instead of `Ss 0 1 ""` (set the range `0..0+1` to an empty string), you can do `SsF1""`. This works in a similar fashion to `G` ]
[Question] [ Given a list of activities and their start time/date, output an ASCII-art calendar showing the activities on the appropriate days. All activities are guaranteed to be in the same month, no two activities will be on the same day, and all activities are guaranteed to fit within the calendar box. The calendar has the date in the upper-left corner of each box, the boxes are 9 spaces wide by 5 spaces tall, surrounded by `-` and `|`. The two-letter abbreviation for the day of the week is centered above the first row, and the weeks start with Sunday. For example, given the following activities: ``` 10/5/2018 - 9:00am - Sandbox calendar challenge 10/9/2018 - 9:00am - Post challenge to main 10/10/2018 - 10:00am - Profit 10/31/2018 - 7:30pm - Halloween party ``` Output this corresponding calendar: ``` Su Mo Tu We Th Fr Sa ----------------------------------------------------------------------- | |1 |2 |3 |4 |5 |6 | | | | | | |9:00am | | | | | | | |Sandbox | | | | | | | |calendar | | | | | | | |challenge| | ----------------------------------------------------------------------- |7 |8 |9 |10 |11 |12 |13 | | | |9:00am |10:00am | | | | | | |Post |Profit | | | | | | |challenge| | | | | | | |to main | | | | | ----------------------------------------------------------------------- |14 |15 |16 |17 |18 |19 |20 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ----------------------------------------------------------------------- |21 |22 |23 |24 |25 |26 |27 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ----------------------------------------------------------------------- |28 |29 |30 |31 | | | | | | | |7:30pm | | | | | | | |Halloween| | | | | | | |party | | | | | | | | | | | | ----------------------------------------------------------------------- ``` ## Clarifications * The schedule words (matching [A-Za-z]+) will delimited by a single space between them (as in the example). * Splitting the text on word boundaries is sufficient. No need for hyphenating words. * If February starts on a Sunday in a non-leap-year, you only will have four calendar rows. * If a 31-day month (e.g., August) starts late in the week, you may have to output six calendar rows. ## I/O and Rules * Your code must handle dates at least between `0001-01-01` and `9999-12-31` in the Gregorian calendar, including leap years as appropriate. For example, if given input `2016-02-13 9:00am Test`, the output calendar should have February 29. * Input date format can be in any desired format. ISO 8601, a `datetime` object, a particularly-formatted string, etc. Input parsing is not the interesting part of this challenge. * Input and output can be [by any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * Output can be to the console, returned as a list of strings, returned as a single string, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # JavaScript (ES8), ~~380~~…~~321~~ 320 bytes Takes input as `(y,m,e)` where: * `y` is the year * `m` is the month, 0-indexed * `e` is an object whose keys are the days and whose values are the events in `[hour, task]` format ``` (y,m,e)=>`SuMoTuWeThFrSa `.split(/(..)/).join` `+(p='-'.repeat(d=71)+` `)+(g=i=>++d<1|(x=G`getMonth`==m)|i%7?`|${[h,t]=e[d]||E,o=[x*d,h],q=E,t&&t.split` `.map(s=>q=(u=q?q+' '+s:s)[9]?o.push(q)&&s:u),[...o,q][r%5]||E}`.padEnd(10)+(++i%7?E:`| `+(++r%5?(d-=7,E):p))+g(i):E)(E=r='',d=-(G=s=>new Date(y,m,d)[s]())`getDay`) ``` [Try it online!](https://tio.run/##VZBRb9sgEMff/Sl4WAMMTO1VVRZrJC/1updKk1JpD5YlWCC2Kxtsg9dEdT97hhdN03g4cfr/7v539yJ/SXcYm97Hxip9OfILOtOOasy3Yj892efph36uv457GQnm@rbx6BYxhm8xe7GNESA8QVDPYQzZqHstPVJ8nWIiIoEJqnjDt4SoL@mMTvxRVNo/WeNrwXmH5@ZmvRPzh7eipr7kulDlPOfU8uL0UdG6pAPPqV@t/NVZAME62SPHtwNHEx92A4EAEpc5XGzKnWX95Go04NXKZROmBWPM0qEsxpv7pfG7YL1UuVEoTcJohCz2eSbmSCxZoHZIxXxNc5z1GJMKNTjLMcr5yCGkisfokQdzo1/Bg/T6z6UULlyJMF42e5BngS8Ha5xtNWtthY7oU5J@piBN4pSCtwiAe5AVcJMliewghXtp1E97AgfZaqPkCA61bMO30rCkgd78R3@3zv8jgLegk425kmkSyBD@oqM9Nv4q3aVBWmd3Sb8o30K5fdXagF6O/gzL6B3jy28 "JavaScript (Node.js) – Try It Online") ## How? Below are some important parts in the code. ### Header The header line is generated with: ``` 'SuMoTuWeThFrSa\n'.split(/(..)/).join` ` ``` When `split()` is used with a regular expression containing a capturing group, this group is included in the output array. In this case, it gives: ``` [ '', 'Su', '', 'Mo', '', 'Tu', '', 'We', '', 'Th', '', 'Fr', '', 'Sa', '\n' ] ``` We join this array with 4 spaces, leading to: ``` ' Su Mo Tu We Th Fr Sa \n' ``` which is exactly what we want. ### Month structure The helper function \$G\$ builds a date from the input year \$y\$ and input month \$m\$ (which are constant) and the day \$d\$ (which is dynamic). Its parameter is a method name, which allows to extract either the day of the week or the month. ``` G = s => new Date(y, m, d)[s]() ``` It is first used to identify the day of the week of the first day of the month, so that we can move back to the last Sunday from there. It is then used to detect when we enter back the correct month and when we leave it (this information is stored in the Boolean \$x\$). ### Event formatting The following code is used to format an event. ``` [h, t] = e[d] || E, // split the content of the event into h and t o = [x * d, h], // set the first 2 entries of o[]: day and hour q = E, // we start with q = empty string t && // skip this .map() loop entirely if t is not defined t.split` ` // split the string on spaces .map(s => // for each word s: q = // update q: (u = q ? q + ' ' + s : s) // u is the concatenation of the previous string with // the new word, separated by a space if needed [9] ? // if u is more than 9 character long: o.push(q) // push the previous string in o[] && s // and reset q to s : // else: u // update q to u ), // end of map() [...o, q][r % 5] // append the last pending part to o[] and extract the || E // relevant row; or use an empty string by default ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~326~~ ~~324~~ ~~315~~ ~~312~~ 307 bytes ``` import calendar as c,textwrap as t c.setfirstweekday(6) y,m,e=input() print' Su Mo Tu We Th Fr Sa\n'.replace(' ',' '*8)[4:]+'-'*71 for w in c.monthcalendar(y,m): for l in zip(*[[d or'',a]+(t.wrap(b,9)+['']*3)[:3]for d in w for a,b in[e.get(d,' ')]]):print'|'+'|'.join('%-9s'%v for v in l)+'|' print'-'*71 ``` [Try it online!](https://tio.run/##TVHJbsMgEL37K@YSDSTEspO2iS31WvVSqVIi9eD6QGyS0NqAMNm6fLsLiaL0MIh5y/AAc3JbrSZ9L1ujrYOKN0LV3ALvoGJOHN3BchM6F1VxJ9xa2s4dhPis@Yk80OjEWiYepTI7R2hkrFQOYbGDFw3LHbwJWG7hycKCvyuMrTANrwRBQOZrOKfFXV6OcIzDWRqttYUDSAVV3GrlttcsxJ9B8wgC3wT@SxoyLIoatEVkvBwRF4eYZMUyOioQy@GUFvm0DI46OA5nM2cr3xQi3ghHap8AkJYlzS@pf3DkK/7QUhEcjLMOB/uzbR8mNDSwEVy058B9P0nSOYM0YfB9nxPM8iThrb/agqt6pY@316y2vPHbjUDKsv/KV925GwtOQ8ul8qo08TK/XHVWr6Xz@DT1@CyfJibAz96o/W8oMNy6E9LfPw "Python 2 – Try It Online") Same input as [Arnauld's JS answer](https://codegolf.stackexchange.com/a/173807/38592): Takes input as `(y,m,e)` where: * `y` is the year * `m` is the month, 1-indexed * `e` is an object whose keys are the days and whose values are the events in `(hour, task)` format [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~215~~ 206 bytes ``` Sθ≔I⪪§⪪θ ⁰/η≔⁻⁺×¹²⊟η⊟η²η≔EE²⁻ηι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷η≔±⊟ηζ≔⁺²⁸﹪⁺⊟ηζ⁷ε⭆⪪SuMoTuWeThFrSa²◨◧ι⁶χ↓←⁷¹W‹ζε«↘F⁷«P↓⁵→≦⊕ζF⁼Iζ§⪪θ/⁰«≔⪪θ - θ≔⟦ω◨§θ¹¦⁹⟧δF⪪⊟θ ⊞δ⎇‹⁺L§δ±¹Lμ⁹⁺⁺⊟δ μμP⪫δ¶Sθ»◨×››ζ⁰›ζεIζ⁹»↓⁵←⁷¹ ``` [Try it online!](https://tio.run/##bVNNb6MwED3Dr7A4GYkqQNrNR0/Vdj@ySlZoibSHbg/e4IAlsAmYpE3V354d28RJkz0YbM@b5@c341VBmpUg5eEw43UnU9kwnuONf@8@tC3LOf5MWonTumQSP8gZz@hLv9oEyEOeH6AQhjfwfPgVp7wF412LkxI@S1bRFkdxgBJR40IB7SS@yCK1HoA1BEWAmMItRNaVAqddhZ9mXD6yLcsoZgG6HYdKwE@aE0nxh1AUQwhiF/jLnSj@sNOrHYJIJf7Wnm2givDOf4bv6OLGvQR7tf0ppJnisaXSawNUuJ6LQkIC/oPfugzKCOO1l3YLsex@02XxtUmJZ3xLSPaL5YXEMJnTtVQKP8F@BLcGqoXYUjx9FDtueacKBqdFsLMrWEkRntO2xXt1uI/eXOeUpKkB56xFg/BIR51FV0pWGy4FUl7cq32dZlMckN5ffcZXDa0olzQzljiG8MumI2Vr2ks5cN1cA9NcRpfj9HxnzXej22@jOY/hp92ZL0dOQEeAnPjPAcoMXGswXKoOG990s4@Sri0wSF3ShpPm1fij6zWnPJeFJc1s00WqeH208vVBffPYOmf@8bVUehgRZ27@EIwrSu8P9/ro5YN0nHcYppD2iqZbvzUUhDT2vzev8mxJla7ebK1QEQJfclXL6055PxzuBlE4iMNoDKZPpmFIKpikhGd/xQtakZLyjDRoVZASpjl1J//DJ6KVJwySAlWEcReQJ3AUWnQj1ky6w@gsOpoOw1oFvwOJ2FHKUU0a@eoebrblPw "Charcoal – Try It Online") Link is to verbose version of code. Takes dates in d/m/yyyy format. Explanation: ``` Sθ ``` Input the first event. ``` ≔I⪪§⪪θ ⁰/η ``` Extract the date and split on `/`s. ``` ≔⁻⁺×¹²⊟η⊟η²η ``` Convert to months since March, 1 BC. I want to calculate the day of week of the first of both next month and the current month, and working in months is easier than keeping the months and years separate and carrying at the end of the year, plus it also allows me to start counting months beginning at March instead of January, which is required by Zeller's congruence. ``` ≔EE²⁻ηι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷η ``` Use a modified Zeller's congruence to extract the day of the week of the first day of next month and this month. The basic part relies on the fact that the number of days from October 30th of the previous year to the 1st of a given month where `m = 4` for March and `m = 14` for January of the following year is given by the formula `m * 153 / 5`, however we can subtract 140 because we only care about the day of the week. It then remains to make adjustments due to the year; each year adds a day, each 4th year adds an extra day, each 100th year subtracts a day, and each 400th year adds a day again. (As I'm working in months these values are all multiplied by 12.) Rather conveniently this directly gives me the answer in terms of a Sunday-indexed week (normally you would add the day of month and start counting on Saturday). ``` ≔±⊟ηζ ``` Negate the day of the week and save it as the current day of the month. ``` ≔⁺²⁸﹪⁺⊟ηζ⁷ε ``` Calculate the number of days in the month from the day of the week of the two months. ``` ⭆⪪SuMoTuWeThFrSa²◨◧ι⁶χ ``` Output the day headers. ``` ↓←⁷¹ ``` Print the top row of `-`s. ``` W‹ζε« ``` Loop until the last day of the month has been output. ``` ↘ ``` Move the cursor to the start of the next row. ``` F⁷« ``` Process 7 days at a time. ``` P↓⁵→ ``` Print the column of `|`s to the left. ``` ≦⊕ζ ``` Increment the current day of the month. ``` F⁼Iζ§⪪θ/⁰« ``` If the current day of the month is the day of the current event, ... ``` ≔⪪θ - θ ``` ... extract the other parts of the event, ... ``` ≔⟦ω◨§θ¹¦⁹⟧δ ``` ... pad the time to 9 spaces and save it and an empty string as a list, ... ``` F⪪⊟θ ``` ... split the description on spaces and loop over them, ... ``` ⊞δ⎇‹⁺L§δ±¹Lμ⁹⁺⁺⊟δ μμ ``` ... adding each word to the previous word if it will fit; ... ``` P⪫δ¶ ``` ... output the time and description (`Pδ` doesn't work, might be a Charcoal bug?), ... ``` Sθ» ``` ... and input the next event. ``` ◨×››ζ⁰›ζεIζ⁹» ``` If the current day of the month is between 1 and the last day of the month then output it, otherwise just output enough spaces to move to the next day. ``` ↓⁵←⁷¹ ``` At the end of the week, print the right column of `|`s and the bottom row of `-`s. [Answer] # [Java (JDK)](http://jdk.java.net/), 538 439 428 425 bytes Quite possibly the longest Code Golf solution I've ever posted. Still trying to golf it down from here but it's a struggle. Managed to knock off 99 bytes by changing the input format and using some regex parsing, and another 11 from miscellaneous bits. *3 extra bytes off thanks to Kevin!* Taking inspiration from other answers, it takes input as the year, month and a Map of days to a String representing the time and event in the format `<time>-<event>`. ``` (y,m,M)->{var C=java.util.Calendar.getInstance();C.set(y,m-1,1);String r=",Su,,Mo,,Tu,,We,,Th,,Fr,,Sa\n".replace(","," "),e;for(int x=C.getActualMaximum(5),l=0,b=0,j,c,i=0;i<7;r+="\n",l+=b<=x&++i>6?7*(i=1):0)for(j=0;j<71;b=l+j/10+2-C.get(7),e=(e=M.get(b))!=null?e.replaceAll("([^-]{1,9})(-| |$)","$1-")+" - ":null,r+=e=i%6<1?"-":c<1?"|":c*i<2&b>0&b<=x?b+"":c<2&e!=null?e.split("-")[i-2]:" ",j+=e.length())c=j%10;return r;} ``` [Try it online!](https://tio.run/##dVNRb9owEH4uv@JmtchunDShalkJBlVo0/pAN4lJe@g6yQQXnDlO5DgURPntzKZ0bTXNUXSy7/vuvvOdc77kYT77vZNFVRoLudtHjZUqOk3h7OyrVmtoajGDh9JAZcqlnEk9B27mTSG0rVtVM1Uyg0zxuoYxl3rTOmqBW7Xl1jmktsI88EzA7WZ/7teBNLHGB9PYgWAtuKEeDkWp7YK6YFX/xrHnwp0/QwdQ8IqAXZjysYZPq0xUVpY63Qfett7mvQUNDFo7vKYFHZNwsFlyAyP2WuCIK6Fn3ERzYW@0o@lMYJKOolpYzwoTmpD0oNEwRCcNpeOS0u/O/hDOLij9bCid8J8aRUZUypWJEXWfF4IIFam7tn11Kzbyea4z23A15itZNAW@IFSxmE7dn9OMShanst9NTcCQi0hVwKZ9tmoHgRxcDrunWLKE9GLiY@YOm/e7STplKsjPkjjohPsMuOvSMizYeL@bEvKB6UapoXhReK0URvjuV3i/SejVluDwCZ6OiVN9nISIBAhCQD3PoU6JYPLksp8MUYh6mbdPzp7Kfqc9HcRtr284DZD3ddrib6q6UtJixyF3Muzc9xAgmrtgkbvyuV1gQjKWnyRxaoRtjAaTbnfpc/8Os3Fo47KUM9d0qfFzI@7u/ezV/84AuLn738S4QdDiEb7weuEhA9fl1pE7j6rG4gsK6KoXx7wIJ1zPpuUKssNkQLbgyisW6C3j6pXxraztKwpsudf6Dp3EDp7EB7wpH6R95z9PnL/bO4@rIrx2GpUqH4XQUHFj13vkZF1bUURlY6PK1WSVxjrSuBMnHyn48P5RkJdHsN39AQ "Java (JDK) – Try It Online") --- **Ungolfed** ``` (y,m,M)->{ // Lambda taking input as a year, month and map var C=java.util.Calendar.getInstance(); // Creates a new Calendar instance C.set(y,m-1,1); // Sets the calendar to the first of the month in the given year String r=",Su,,Mo,,Tu,,We,,Th,,Fr,,Sa\n" // Creates the header row by replacing .replace(","," "),e; // commas with 4 sets of spaces for( // Creates 7 rows for a calendar row int x=C.getActualMaximum(5) // Stores last day of the month ,l=0,b=0,j,c,i=0;i<7; // Initialises other integers r+="\n", // Add new line each row l+=b<=x&++i>6 // If end of a calendar row is reached, and current day is less than max ?7*(i=1) // Set i to 1 and add 7 to line count to create another calendar row :0) // Otherwise do nothing for(j=0;j<71; // Loop 71 times, appending characters to create a row b=l+j/10+2-C.get(7), // Determine the day of the box we're in e=(e=M.get(b))!=null? // Get the event for this day from the map and if not null e.replaceAll("([^-]{1,9})(-| |$)","$1-") // Do some regex to separate the line entries by hyphens +" - " // Append extra hyphen to prevent array out of bounds :null, // Otherwise do nothing r+=e=i%6<1?"-": // If it's the first line of a calendar row, append - c<1?"|": // If it's the first column of a box, append | c*i<2&b>0&b<=x?b+"": // If it's the second column of a box, the second row, // and less than the max day, append the day c<2&e!=null?e.split("-")[i-2]: // If it's any other row and there is an event then split and append correct line " ", // Else just append a space j+=e.length()) // Increase the row character count by the length to append c=j%10; // Set the column of box (this is the only thing in the loop so happens first) return r; // return the calendar string! } ``` [Answer] # [Red](http://www.red-lang.org), 674 651 bytes ``` func[a][z: func[a b c][to-tuple reduce[a b c]]c: a/1 c/4: 1 d: c + 31 d/4: 1 d: d - 1 e: 1 + c/weekday % 7 if e = 0[e: 7]foreach t[:Su:Mo:Tu:We:Th:Fr:Sa][prin pad pad/left t 6 10]h: pad/with"-"71 #"-"print["^/"h]m: copy[]foreach[i b]a[put m z r:(t: e - 1)+ i/4 / 7 + 1 n: i/4 % 7 + t 2 b/1 t: split b/2" "l: 0 until[if t/2[if 10 >((length? t/1)+ length? t/2)[t/1: rejoin reduce[t/1" "take next t]]]put m z r n 2 + l: l + 1 take t tail? t]i: 0]n: k: 0 repeat v(g: e - 1 + d/4)/ 7 + sign? g % 7[repeat r 5[repeat i 7[t: copy"|"if i = e[k: 1]if all[k = 1 r = 1 n < d/4][append t n: n + 1]if s: select m z v i r[append t s]prin pad t 10]print"|"]print h]] ``` [Try it online!](https://tio.run/##bVLRitswEHz3VwwuBwkh2Erump5oe2@lL4XSHPRBqKDYcqzGkY0j312O/ntulKQJhRpi7W5mRzO77m15@GFLpZNKHqrBF8po9SpxCrFCoVVop2HoGovelkNhz2VdSJhMoMhuJQRKiQITzEVSXgolpgxszCbEPVu7Kc0eN1jAVbD4hFzx34Wu2t6aok6CkstBfmvl4yB/WvlYyy@9XFJR1zuPzpTxlzW2Cgh4D5HrWiax9OxCnU7ThcA7HhEdVPorS2u9pa6226u/dyiHlTaqGwK2eEUvR0FSCoWOJ4nLbpFR3YSKvURMb45pwAwrmiV21zUuMJmlSBuJPBl8cI2ioZDN4iFyfB6NGuvXoX5gkcS4ZrOxYkkmvf3d0tN5pCyRLpiNhbcvdKe1vkiE5@3kkGiOyo6wkATjGjJqRxGaajc8yddZE/A0Wp9dsYMLGZ9c7dzaP2AdTakTMulxdw7hWA2ncaV/Ujpx3JBV5BWamWkatWFFUFF8e3yM1FqZrrO@pCKK8FFhRO84KdvY4uThiVz9BYidviw0xC0eF8Y7TwFqrQ8VFO6mIp/OcvGBMdJ7medmyzEtjS9X7QsKw7GWpkdRUxsnbFNoJOBz///O7@0uXNEILbbGeXbFJnZcm1KRX5r6tnLhDJqLf5gXcp53EfSVnC0/8GiqD/soRB/eAA "Red – Try It Online") ## More readable: ``` func [ a ] [ c: d: a/1 c/4: d/4: 1 d: d + 31 d/4: 1 d: d - 1 e: 1 + c/weekday % 7 if e = 0[e: 7] g: e - 1 + d/4 w: g / 7 + sign? g % 7 foreach t [ :Su :Mo :Tu :We :Th :Fr :Sa ] [ prin pad pad/left t 6 10 ] h: pad/with "-" 71 #"-" print[ "^/" h ] m: copy #() foreach[ i b ] a [ n: i/4 % 7 + t: e - 1 r: t + i/4 / 7 + 1 put m to-tuple reduce[ r n 2 ] b/1 t: split b/2" " i: 0 until [ if t/2 [ if 9 >= ((length? t/1) + (length? t/2)) [ t/1: rejoin reduce[t/1" "take next t] ] ] put m to-tuple reduce [ r n 2 + i: i + 1 ] take t tail? t ] ] n: 0 g: off repeat v w [ repeat r 5 [ repeat i 7 [ t: copy "|" if i = e[ g: on ] if all [ g r = 1 n < d/4 ] [ append t n: n + 1 ] if s: select m to-tuple reduce [ v i r ] [ append t s ] prin pad t 10 ] print "|" ] print h ] ] ``` ]
[Question] [ It is the year MDLXVII in a world in which the Roman Empire never fell, and the collapse into the dark ages never occurred. Due to the extended period of Pax Romana, the empire's economic stability enabled technology to progress at a rapid rate. The Romans have begun to dabble with circuitry, and have invented an ingenious calculator that doesn't require the use of an "equals" button. They call it "Roman Polish Notation" To make a calculation, they enter their operands first, then the operation. For example, 100 + 11 \* 20 would be `C XI XX * +`. **Additionally** The Romans have found that they often need to make multiple calculations at the same time, and would prefer for the method to return every value "on the stack" in some sort of array/list/tuple-like structure. (e.g. `X I + X I - CC II +` would return [11, 9, 202]) --- The challenge is to develop a calculator program capable of making these computations. **Clarification**: Subtractive Notation is required. I hadn't realized it wasn't recognized feature in the Ancient Roman empire. The task was therefore ambiguous, and I apologize. **Minimum Guidelines** * Your output will be in Arabic Numerals. * You only need to convert from Roman Numerals up to 5000. * You will need to support +, -, /, \* operations (addition, subtraction, division, and multiplication). * Whether division is floating point based or integer based is implementation specific. Either works for this challenge. * Your output will need to support numbers up to 4 Billion. * Shortest answer overall, AND in each language wins. This is a Code Golf Challenge but I love the variety. In the event of a tie, ~~factors like support for roman numerals above 5000 or additional operations will be considered~~ the earliest submission will win. [Answer] # [Python 2](https://docs.python.org/2/) + [roman](https://pypi.python.org/pypi/roman), 118 bytes ``` from roman import* s=[] for i in input().split():s+=[eval(s.pop(-2)+i+s.pop())if i in"+-/*"else`fromRoman(i)`] print s ``` ### Demo It cannot be tested online because of the module it makes use of, but you can see how to run this [here](https://tio.run/##JUw9C8MgEN39FYeTRpJCxkKmTFkzFUIgGZQeGD08W@ivt9oO7xPeo09@xjCW4lK8oOIMgBfFlDvB07YLFxMgYG0DvbLSA5PHqnc202bfp1c8UCTVj9qg@Xut0f1G0vS3TlrP9mj/a7tXqI9dUMKQgUuRD1jAQOMe5hmWmuQX "Python 2 – Try It Online") (a full program accepting input from STDIN – an expression with quotes – and printing the output to STDOUT – in the form of a list, the stack). Uses a slightly older version, because I won't bother to create a new GIF for only a few bytes: [![Demo GIF](https://i.stack.imgur.com/0W52D.gif)](https://i.stack.imgur.com/0W52D.gif) To install the package, you can run the following in the Terminal / Command Line: ``` pip install roman ``` [Answer] # [Haskell](https://www.haskell.org/), 217 bytes *-13 bytes thanks to Bruce Forte. -73 bytes thanks to Ørjan Johansen.* ``` foldl(!)[].words s@ ~(x:y:z)!n=last$(a n:s):[y`f`x:z|(f,c)<-zip[(+),(-),(*),(/)]"+-*/",n==[c]] a s=last$0:[n+a(drop(length x)s)|(n,x)<-zip l$words"I IV V IX X XL L XC C CD D CM M",x<=s,x++"Y">s] l=[1,4,5,9]++map(10*)l ``` [Try it online!](https://tio.run/##JY5Ba8IwGEDv/RWfoYekSafCdlgwY1AvBb1KRxYwtEbLYhqawmKR/fR1ZfJ418e76PB1snYy4nMynW0sXhCpnr67vglJeIcfHPmNj2ThhNVhSLEGxwPh8nY0x8jHOzasJpt8bL3ElDCcz2azS6IQzbMlYk4IWSuVaAiPxopLRzVu@s5je3Ln4QKRBHLHjsVHCmz6f4BKKA9wgLKCmR3soCpgZgtbKPawRyxuRGCRUvSB3oJKrJBr9sxe2Kui9Ko9Xq8yYqerbh0I8H3rBkjBACqgKqGqIAOKpt/aWH0OU157/wc "Haskell – Try It Online") Manual implementation, yay! [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 57 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` θ{:u=?F!!}F:u=‽0AøF{1"IVXLCDM”GWH∫2%3*⁽*}aa⁵<⌡±;A}a¹∑ι}}⁰ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0I4JTdCJTNBdSUzRCUzRkYlMjElMjElN0RGJTNBdSUzRCV1MjAzRDBBJUY4RiU3QjElMjJJVlhMQ0RNJXUyMDFER1dIJXUyMjJCMiUyNTMqJXUyMDdEKiU3RGFhJXUyMDc1JTNDJXUyMzIxJUIxJTNCQSU3RGElQjkldTIyMTEldTAzQjklN0QlN0QldTIwNzA_,inputs=QyUyMFhJJTIwWFglMjAqJTIwKw__,v=0.12) [Answer] # JavaScript (Node) + [romans](https://www.npmjs.com/package/romans) + [stk-lang](https://www.npmjs.com/package/stk-lang), 74 bytes ``` s=>(R=require)("stk-lang")(s.replace(/\w+/g,R("romans").deromanize)).stack ``` Returns a list of bigintegers. ## Execution Run the following: ``` npm install romans npm install stk-lang node ``` Then paste the function. Example: ``` C:\Users\conorob\Programming\golf-new\roman λ npm install romans npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json' npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json' npm WARN Programming No description npm WARN Programming No repository field. npm WARN Programming No README data npm WARN Programming No license field. + [[email protected]](/cdn-cgi/l/email-protection) added 1 package in 0.801s C:\Users\conorob\Programming\golf-new\roman λ npm install stk-lang npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json' npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json' npm WARN Programming No description npm WARN Programming No repository field. npm WARN Programming No README data npm WARN Programming No license field. + [[email protected]](/cdn-cgi/l/email-protection) added 1 package in 0.847s C:\Users\conorob\Programming\golf-new\roman λ node > s=>(R=require)("stk-lang")(s.replace(/\w+/g,R("romans").deromanize)).stack [Function] > f=_ [Function] > f("X I + X I - CC II +").map(e => e.toString()) [ '11', '9', '202' ] > f("C XI XX * +").map(e => e.toString()) [ '320' ] > f("MMMM M I - +").map(e => e.toString()) [ '4999' ] ``` [Answer] # [Dyalog APL](https://www.dyalog.com/), 93 bytes ``` ⎕CY'dfns' a←⍬⋄{0::{a,←⍵}roman⍵⋄f←⍎'+-÷×'⌷⍨'+-/*'⍳⍵⋄r←f/¯2↑a⋄a↓⍨←¯2⋄a,←r}¨{1↓¨⍵⊂⍨⍵∊' '}' ',⍞⋄a ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI/6pjpHqqek5RWrcyU@apvwqHfNo@6WagMrq@pEHTB/a21Rfm5iHpABlEgDC/Wpa@se3n54uvqjnu2PelcAefpa6o96N0PUFAHVpOkfWm/0qG1iIpAPNHYyUBVQFCQG5IPMLao9tKLaEChzaAVIV1cTSAWQ0dGlrqBeC8Q6j3rngRRzRSh4KmgrgEhdBWdnBU8QT0vB2VNBHwA "APL (Dyalog Unicode) – Try It Online") [116 bytes](https://tio.run/##LY6xCsJAEER/ZbvTxONiwEbsYhPQVmwPJDaCYichjUiQ6Ilikc5CGwvBQkWwNH@yPxLn1GKXneExO3oykoOZHo2HZRlxutUYNhdeLWKv2dQ1SFf5sWRzqrB5tdg8qpwdcSbKq7E5x0Wu6pzufWqwucMQYa/fCdpdweYGOnmfsZEXfZM3wpXFs8gFr58WdqVy/iSYKZhIva8@pzsNjTZ7UHCtB237TBEZ25e/5GxuCRzLTJBIMKh1sHBZ9ikkl@yWFAQUWuVQEJL6AA) without the roman built-in [Answer] # [Python 3](https://docs.python.org/3/), ~~280~~ 206 bytes ``` N=dict(I=1,V=5,X=10,L=50,C=100,D=500,M=1000) def d(s): n=0 for v in map(N.get,s):n+=v-n%v*2 return n def c(w): s=[] for t in w.split():s+=[str(d(t)if t[0]in N else eval(s.pop(-2)+t+s.pop()))] return s ``` [Try it online!](https://tio.run/##PY1Ba4QwEIXP@ivmUpyYKNld9rKQU3oRWo9LwHpYNLYBG4OZuvTXW@2WXobv8d7HhG/6mPxpXWvVu46wUgdxVWdh1EGKF3WWQm8kxfOGUrzuLFna2wF6jOySJl7JNBmmGRZwHj5vAevy3ZLYSs/VUvinJT@myWzpa/bgf9UO77saVdM@XNrdexnD6AjZJXLVRJqxR2JuAGpku/U12DFasMttxFiGKWBxZJz4gxlj7f@buIbZecK8w0yDqcAYyIGDgervFqA1VHvSZl9cgWdMQLRBZW8@Y@sP "Python 3 – Try It Online") This time with subtractive notation support. Method `c` is the main entry point; the other is support. Edit log: * 74 down thanks to [Ørjan](https://tio.run/##PY1Ba4QwEIXP@ivmUpyYKNld9rKQU3oRWo9LwHpYNLYBG4OZuvTXW@2WXobv8d7HhG/6mPxpXWvVu46wUgdxVWdh1EGKF3WWQm8kxfOGUrzuLFna2wF6jOySJl7JNBmmGRZwHj5vAevy3ZLYSs/VUvinJT@myWzpa/bgf9UO77saVdM@XNrdexnD6AjZJXLVRJqxR2JuAGpku/U12DFasMttxFiGKWBxZJz4gxlj7f@buIbZecK8w0yDqcAYyIGDgervFqA1VHvSZl9cgWdMQLRBZW8@Y@sP) [Answer] # JavaScipt (ES6), ~~152~~ 151 bytes *Saved 1 byte thanks to user202729* ``` p=>p.split` `.map(c=>s.push(eval("+-/*".indexOf(c)+1?(T=s.pop(),s.pop())+c+T:c.replace(/./g,c=>"+"+{I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[c]))),s=[])&&s ``` ## Test cases ``` f=p=>p.split` `.map(c=>s.push(eval("+-/*".indexOf(c)+1?(T=s.pop(),s.pop())+c+T:c.replace(/./g,c=>"+"+{I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[c]))),s=[])&&s console.log(f("C XI XX * +")) console.log(f("X I + X I - CC II +")) ``` ## Explanation (less golfed) ``` V={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3} // Values of the roman numerals p=>( s=[], // Initialize the stack p.split` `.map(c=> // For every part in the input: "+-/*".indexOf(c)+1? // If the input is an operator: s.push(eval((T=s.pop(),s.pop())+c+T)) // Evaluate the operator on the top of the stack : // Else (if it is a roman numeral): s.push(eval(c.replace(/./g,c=>"+"+V[c])))// Push the sum of the characters' values ),s) // return the stack ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 82 bytes ``` ị“+-×÷”;”/v®ṫ-¤®ṖṖ¤;© 4Ḷ⁵*p1,5P€ “IVXLCDM”iЀị¢µIN‘Ṡæ.µ®;© Ḳµ“+-*/”W€i⁸Ñ⁸Ǥ¹?µ€ṛ®Ḋ ``` [Try it online!](https://tio.run/##y0rNyan8///h7u5HDXO0dQ9PP7z9UcNcayDWLzu07uHO1bqHloDoaUB0aIn1oZVcJg93bHvUuFWrwFDHNOBR0xouoEbPsAgfZxdfoK7MwxOAYkDjDi06tNXT71HDjIc7Fxxepndo66F1IN0Pd2w6tBVslZY@UHk4UHHmo8YdhyeCiHagXTvtgfJAE3bOBlq7o@v///@eYQphngoRLgrOLgqengpaAA "Jelly – Try It Online") [Originally posted in chat](https://chat.stackexchange.com/transcript/240?m=42020350#42020350). --- Explanation: Because Jelly doesn't have a stack, I put the stack in the register. When the program starts, the register value `®` is `0`, which is treated as `[0]` for the purposes of this program. ``` ị“+-×÷”;”/v®ṫ-¤®ṖṖ¤;© Link 1: Given an operator index (an integer in range 1..4), apply it. ị“+-×÷” Index to the string "+-×÷" ;”/ Concatenate with the character "/", which is Jelly splat operator. v ¤ Evaluate with parameter... ® the register's ṫ tail - from -1. (2 last items) ® ¤; Concatenate with the register value, ṖṖ pop twice. © Store the result to register. 4Ḷ⁵*p1,5P€ Link 2: Niladic, generate [1,5,10,50,...] 4Ḷ Lowered range of 4, gives [0,1,2,3]. ⁵* Raise to power of 10. Value = 1,10,100,1000. p1,5 Calculate Cartesian product with [1,5]. Value = [1,1],[1,5],[10,1],[10,5],... P€ Calculate product of each item. Alternatively, ×þ1,5F would also work instead of p1,5P€. “IVXLCDM”iЀị¢µIN‘Ṡæ.µ®;© Link 3: Given roman number, push it to the stack (register). i Find index of ... Ѐ each character ... “IVXLCDM” in "IVXLCDM". ị¢ Index to last link. (link 2) µ With that value, (consider LIX -> [50,1,10] for example) I Ḳµ“+-*/”W€i⁸Ñ⁸Ǥ¹?µ€ṛ®Ḋ [TODO complete explanation] ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~216~~ 187 bytes ``` from operator import* N=dict(I=1,V=5,X=10,L=50,C=100,D=500,M=1000) def f(w): s=[] for t in w.split():s+=[str(sum(map(N.get,t)))if t[0]in N else str(eval(s.pop(-2)+t+s.pop()))] return s ``` [Try it online!](https://tio.run/##LYyxasMwFEXn@Cve5vdsxSgtWQKa3MXQeiwCN4NppFRgS0J6aejXuwrtcjkXDif@8Ffwz9tmU1ghRJNmDgncGkPiphrVxX0yDuog3tVRaHWQ4lUdpegLSfFSUIq3B0uqLsaCxTudql1W07na2VJicB7uXY6LY6RTbtWUOWG@rbjOEcfualgwETkLPMlzsUcwSzbw0Mz3vGDuYoi4f6KW2z8uesknw7fkIW8xOc/YWKx70ANoDQ20oGH43z30PQzl1SQgm6jqD1/T9gs) Because it came up in the comments of both the question and this answer and likely led to down-votes: **this submission doesn't support subtractive notation.** Rationale: Subtractive notation was rarely used in the Roman Empire and only popularised later (see [Subtractive Notation](https://en.wikipedia.org/w/index.php?title=Subtractive_notation&oldid=788980081), paragraph 3, last sentence). The task presumes a Roman Empire that developed programmable integrated circuits, not one that underwent the same cultural changes as 13th century Europe. The description doesn't mention subtractive notation and none of the examples uses it. ]
[Question] [ Spring has recently arrived, and it is almost the time when flowers start to sprout. So I want you to help them grow. **Your task:** Given two numbers, `m`, and `n`, output `m` flowers randomly placed on an `n*n` grid. A single flower looks like this: ``` & | ``` A flower's position is defined by where its `&` is. When randomly placing two flowers, no two can be in the same place. If one flower's `&` overlaps another flower's `|`, display the `&`. The bottom row of flowers may not contain any `&`. Input can be as a number or a string, through any of the standard methods. Output can be a list of strings, each string representing one row of the grid, or a delimited string following the same guideline as the list. Standard methods of output. Trailing whatevers are allowed, and you can use tabs to separate your flowers. Note that every grid must be completely filled, with spaces or something. Note that the input will always be valid, you will always be able to legally fit the `m` flowers into the `n` by `n` grid. **Test cases:** Since only very tight test cases can be guaranteed, due to the whole "random placement" bit, that will be the only kind of test case with an answer provided. But I will try all submissions online to make sure that they are valid using some test cases too. Input for the test cases is given in the form `m, n`. ``` Input: 2, 2 Output: && || -------------- Input: 6, 3 Output: &&& &&& ||| ``` Note that the newline after the word `Output:` in the test cases is optional. Other test cases: 1. 1, 10 2. 0, 100 3. 5, 8 4. 6, 3 Code golf so shortest code wins! Thank you to ComradeSparklePony for making this challenge and posting it in the Secret Santa's gift box!. [Sandbox post](https://codegolf.meta.stackexchange.com/posts/11914) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ²‘;⁹R¤ṬṖs⁸×’¤Ẋ€ṙ2B¤F€ZḄị“&|& ”s⁸Y ``` **[Try it online!](https://tio.run/nexus/jelly#@39o06OGGdaPGncGHVrycOeahzunFT9q3HF4@qOGmUCBXV2PmoBiM42cDi1xAzKjHu5oebi7@1HDHLUaNYVHDXNBiiP///9v@t/Q8mtevm5yYnJGKgA "Jelly – TIO Nexus")** ### How? ``` ²‘;⁹R¤ṬṖs⁸×’¤Ẋ€ṙ2B¤F€ZḄị“&|& ”s⁸Y - Main link: n, m e.g. 3, 2 ² - square n 9 ‘ - increment 10 ¤ - nilad followed by link(s) as a nilad: ⁹ - link's right argument 2 R - range [1,2] ; - concatenate [10,1,2] Ṭ - untruth (1s at indexes) [1,1,0,0,0,0,0,0,0,1] Ṗ - pop [1,1,0,0,0,0,0,0,0] ¤ - nilad followed by link(s) as a nilad: ⁸ - link's left argument 3 ’ - decrement 2 × - multiply 6 s - split into chunks [[1,1,0,0,0,0],[0,0,0]] Ẋ€ - shuffle €ach (maybe:) [[0,1,0,0,1,0],[0,0,0]] ¤ - nilad followed by link(s) as a nilad: 2B - 2 in binary [1,0] ṙ - rotate (vectorises) [[[0,0,0],[0,1,0,0,1,0]],[[0,1,0,0,1,0],[0,0,0]]] F€ - flatten €ach [[0,0,0,0,1,0,0,1,0],[0,1,0,0,1,0,0,0,0]] Z - transpose [[0,0],[0,1],[0,0],[0,0],[1,1],[0,0],[0,0],[1,0],[0,0]] Ḅ - from binary (vectorises) [0,1,0,0,3,0,0,2,0] “&|& ” - literal ['&','|','&',' '] ị - index into [' ','&',' ',' ','&',' ',' ','|',' '] ⁸ - link's left argument 3 s - split into chunks [[' ','&',' '],[' ','&',' '],[' ','|',' ']] Y - join with newlines [' ','&',' ','\n',' ','&',' ','\n',' ','|',' '] - implicit print ``` [Answer] # PHP (>=7.1), ~~135 131 128 116 110~~ 109 bytes ``` for([,$m,$n]=$argv,$z=$q=$n*$n;$q;)echo" |&"[$m&&rand(0,--$z-$n)<$m?$s[$q]=2+!$m--:$s[$q+$n]/2]," "[--$q%$n]; ``` takes input from command line arguments; run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/f7791049f65a8b0ee8b032f0550672dae2f9ace8). **breakdown** ``` for([,$m,$n]=$argv, # import arguments $z=$q=$n*$n; # $q = number of total fields, $z-$n = available for flowers $q; # loop $q down to 0 ) echo" |&"[ # print: $m&&rand(0,--$z-$n)<$m # if (probability $m/($z-$n)), decrement $z ?$s[$q]=2+!$m-- # then index 2 (flower), set $s[$q], decrement $m :$s[$q+$n]/2 # else if flower above, then 1 (stalk), else 0 (space) ], "\n"[--$q%$n] # print newline every $n characters ; ``` [Answer] # [Python 2](https://docs.python.org/2/), 150 bytes ``` from random import* n,m=input() b=[1]*m+[0]*(n*~-n-m) shuffle(b) for r in range(n):print''.join(' &|'[f^-s]for s,f in zip([0]*n+b,b+[0]*n)[r*n:r*n+n]) ``` **[Try it online!](https://tio.run/nexus/python2#Hcy7DsIgAIXhnadgkkvBaHRq0ichmJRaFCMHQtvFGN/auRaHk7P8@VZfUqSlx3W7EHMqsyRQsQvIy8wFcZ05Whkbc7CSQ340dBRkui/eP0fuBPGp0EIDKnIbOUSbS8DM2P6RAjijuzcz/qInW8tJ@dq@QuZVROOU@9sQpki02xpYsa4ndf4i6aEf7uMP "Python 2 – TIO Nexus")** ### How? Takes `input()` from STDIN and unpacks the tuple provided (a comma separated string of decimal integers like `3,6`) into `n` and `m`. Creates an ordered, one dimensional `n*(n-1)` long "flowerbed", `b`, by concatenating: - a list containing a "flower" `[1]` repeated `m` times; and - a list containing a "space" `[0]` repeated `n*~-n-m` times\*. \* The tadpole operator `~` (`~x=-1-x`) saves 2 bytes with `n*~-n-m` in place of the more normal looking `n*(n-1)-m`. Shuffles (using `random`'s `shuffle` function) this flowerbed to place the flowers and spaces randomly amongst the `n*(n-1)` positions. Steps through the 0-indexed rows, `r`, and `prints` each in turn to create a two dimensional flowerbed from the one dimensional one... The final two dimensional (`n*n`) flowerbed has stalks, `s`, one row below flower heads, `f`, if and only if there is no flower head to show. This is achieved by XORing (`^`) `f` with `-s` where `f` and `s` are the `1`s and `0`s from before and using the result to index into the length 3 string `' &|'`: ``` f s f^-s ' &|'[f^-s] 0 0 0 ' ' 0 1 -1 '|' < negative indexing used here 1 0 1 '&' 1 1 -2 '&' < ...and here. ``` To get `f` and `s` the `zip` function is used with two copies of the one dimensional flowerbed, one with `n` trailing spaces (the flower heads) and one with `n` leading spaces (the stalks). The whole thing is created for each row (to save bytes), and the row required is sliced out using `[r*n:r*n+n]`. [Answer] # [Python 2](https://docs.python.org/2/), ~~184~~ 179 bytes ``` from random import* m,n=input() s,a=' &' l=[s]*n*-~n while s.count(a)<m:x=randrange(n*n-n);l[x]=a;l[x+n]='|&'[l[x+n]==a];s='\n'.join(''.join(l[i*n:][:n])for i in range(n)) print s ``` [Try it online!](https://tio.run/nexus/python2#Lcy7DoIwAIXhvU/RyV4EgnED@yS1Q4MgNeWUtBAZjG/tjJAwnHxn@tcuhoFGi8eGG8YQJ0mGDMphnCcuSMqsYvTEiFc6GQmZf0HevfMtTUUTZkzcittQLWqPbHu2HBI5RO31YpTdOcMo9jkxfXxlTZ0Uu4MVr@DA2aHXTqIyuoIRXYjUUQd6NIUgY3SYaFrXa5ldyh9C3timb/8 "Python 2 – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 129 bytes ``` from random import* n,m=input();d=n*n-n s='' while d+n:b=0<random()*d<m;m-=b;d-=1;s+=' |&'[-b|(s[~n:-n]=='&')]+'\n'[d%n:] print s ``` [Try it online!](https://tio.run/nexus/python2#Jcu9DoIwFAbQvU/RRS5/TTQ6Ue6TYAegGJrYD9JCXIhv7VxNnM500iMsXoYe9ofz6xK2UqD27LDuW15oyyihICITidfsnpO0FZqBz@1/5UVpW6@94kFbxRcdKyZ5ZNSp4chj90ajYJgpo8JUdAd19oTGiDU4bDKmdK1vHyxq7Md5@gI "Python 2 – TIO Nexus") Generates the output string one character at a time. Randomly chooses whether the current cell is a flower with probability equal to the number `m` of remaining flowers divided by the number of remaining spaces. Adds a newline every `n` characters. A blank cell is filled with a stem `|` if the symbol `n` from the end is a `&`. [Answer] # PHP, 111 Bytes ``` for([,$b,$s]=$argv;$i<$s**2;)echo${+$i}="| &"[(rand(1,$s**2-$s-$i)>$b?0:$b--)>0?2:${$i-$s}!="&"],"\n"[++$i%$s]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/e50caf435686b674b78fbb54367c9a781932e050) -1 Byte for a physical Newline a solution 115 Bytes using max ``` for([,$b,$s]=$argv;$i<$s**2;)echo${+$i}="&| "[rand(1,max($s**2-$s-$i,1))>$b?1+(${$i-$s}!="&"):!$b--],"\n"[++$i%$s]; ``` This way with 137 Bytes shuffles the first part of the string ``` for([,$b,$s]=$argv,$a=str_shuffle(($p=str_pad)($p("",$b,_),$s**2-$s));$i<$s**2;)echo$a[$i]<_?" |"[$a[$i-$s]==_&$i>=$s]:"&","\n"[++$i%$s]; ``` [Answer] ## JavaScript (ES6), 157 bytes ``` f=(n,m,a=[...(` `.repeat(n)+` `).repeat(n)],r=Math.random()*-~n*~-n|0)=>m?(a[r]==` `?a[m--,r]=`&`:0,f(n,m,a)):a.map((c,i)=>c==` `&&a[i+~n]==`&`?`|`:c).join`` ``` ``` <div oninput=o.textContent=f(n.value,m.value)><input id=n type=number min=2 value=2><input id=m type=number min=1><pre id=o> ``` Explanation: Creates an array representing the grid of flowers plus newlines. Recursively randomly searches for empty squares in which to place flowers until the desired number of flowers is reached. Finally the stems of the flowers are generated where there is space for them. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` Nθ↷FN«J‽θ‽⊖θW⁼KK&J‽θ‽⊖θ&¬KK ``` [Try it online!](https://tio.run/##lYy9CsIwFIXn5ilCB7kBHQXBVQc7lFB8gZheTTA/bUzqID57TKGIq9s5h@98UokgvTA5n9yQYpvsBQOMbE@4nnzs9E1FKO3qA4VfhDH6IlWT7HD20AnXe1tua7rEA8qAFl3EvsysGKqn0gYpHMckzAM44h0KX6/qovrHw4N2Eebft7Q@LsKZeOe8I9u8mcwH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ↷ ``` Change the default printing direction to downwards. ``` FN« ``` Input `m` and loop that many times. ``` J‽θ‽⊖θ ``` Jump to a random location on the grid. ``` W⁼KK&J‽θ‽⊖θ ``` If there is already a flower, keep jumping to random locations until a suitable spot is found. ``` & ``` Print the flower head. ``` ¬KK ``` Print the stalk if there is not already a flower head below. ]
[Question] [ What is the smallest possible runnable [Mach-O](https://en.wikipedia.org/wiki/Mach-O) executable on x86\_64? The program can do nothing (not even returning a return code), but must be a valid executable (must run without errors). My try: GNU Assembler (`null.s`): ``` .text .globl _main _main: retq ``` Compilation & Linking: ``` as -o null.o null.s ld -e _main -macosx_version_min 10.12 -o null null.o -lSystem ``` Size: **4248 bytes** Looking at the hex values it seems there is a lot of zero padding which maybe can be removed, but I don't know how. Also I don't know if it is possible to make the exectubale run without linking libSystem... [Answer] Smallest runnable Mach-O has to be at least `0x1000` bytes. Because of XNU limitation, file has to be at least of `PAGE_SIZE`. See `xnu-4570.1.46/bsd/kern/mach_loader.c`, around line 1600. However, if we don't count that padding, and only count meaningful payload, then minimal file size runnable on macOS is `0xA4` bytes. It has to start with mach\_header (or `fat_header` / `mach_header_64`, but those are bigger). ``` struct mach_header { uint32_t magic; /* mach magic number identifier */ cpu_type_t cputype; /* cpu specifier */ cpu_subtype_t cpusubtype; /* machine specifier */ uint32_t filetype; /* type of file */ uint32_t ncmds; /* number of load commands */ uint32_t sizeofcmds; /* the size of all the load commands */ uint32_t flags; /* flags */ }; ``` It's size is `0x1C` bytes. `magic` has to be `MH_MAGIC`. I'll be using `CPU_TYPE_X86` since it's an `x86_32` executable. `filtetype` has to be `MH_EXECUTE` for executable, `ncmds` and `sizeofcmds` depend on commands, and have to be valid. `flags` aren't that important and are too small to provide any other value. Next are load commands. Header has to be exactly in one mapping, with R-X rights -- again, XNU limitations. We'd also need to place our code in some R-X mapping, so this is fine. For that we need a `segment_command`. Let's look at definition. ``` struct segment_command { /* for 32-bit architectures */ uint32_t cmd; /* LC_SEGMENT */ uint32_t cmdsize; /* includes sizeof section structs */ char segname[16]; /* segment name */ uint32_t vmaddr; /* memory address of this segment */ uint32_t vmsize; /* memory size of this segment */ uint32_t fileoff; /* file offset of this segment */ uint32_t filesize; /* amount to map from the file */ vm_prot_t maxprot; /* maximum VM protection */ vm_prot_t initprot; /* initial VM protection */ uint32_t nsects; /* number of sections in segment */ uint32_t flags; /* flags */ }; ``` `cmd` has to be `LC_SEGMENT`, and `cmdsize` has to be `sizeof(struct segment_command) => 0x38`. `segname` contents don't matter, and we'll use that later. `vmaddr` has to be valid address (I'll use `0x1000`), `vmsize` has to be valid & multiple of `PAGE_SIZE`, `fileoff` has to be `0`, `filesize` has to be smaller than size of file, but larger than `mach_header` at least (`sizeof(header) + header.sizeofcmds` is what I've used). `maxprot` and `initprot` have to be `VM_PROT_READ | VM_PROT_EXECUTE`. `maxport` usually also has `VM_PROT_WRITE`. `nsects` are 0, since we don't really need any sections and they'll add up to size. I've set `flags` to 0. Now, we need to execute some code. There are two load commands for that: `entry_point_command` and `thread_command`. `entry_point_command` doesn't suit us: see `xnu-4570.1.46/bsd/kern/mach_loader.c`, around line 1977: ``` 1977 /* kernel does *not* use entryoff from LC_MAIN. Dyld uses it. */ 1978 result->needs_dynlinker = TRUE; 1979 result->using_lcmain = TRUE; ``` So, using it would require getting DYLD to work, and that means we'll need `__LINKEDIT`, empty `symtab_command` and `dysymtab_command`, `dylinker_command` and `dyld_info_command`. Overkill for "smallest" file. So, we'll use `thread_command`, specifically `LC_UNIXTHREAD` since it also sets up stack which we'll need. ``` struct thread_command { uint32_t cmd; /* LC_THREAD or LC_UNIXTHREAD */ uint32_t cmdsize; /* total size of this command */ /* uint32_t flavor flavor of thread state */ /* uint32_t count count of uint32_t's in thread state */ /* struct XXX_thread_state state thread state for this flavor */ /* ... */ }; ``` `cmd` is going to be `LC_UNIXTHREAD`, `cmdsize` would be `0x50` (see below). `flavour` is `x86_THREAD_STATE32`, and count is `x86_THREAD_STATE32_COUNT` (`0x10`). Now the `thread_state`. We need `x86_thread_state32_t` aka `_STRUCT_X86_THREAD_STATE32`: ``` #define _STRUCT_X86_THREAD_STATE32 struct __darwin_i386_thread_state _STRUCT_X86_THREAD_STATE32 { unsigned int __eax; unsigned int __ebx; unsigned int __ecx; unsigned int __edx; unsigned int __edi; unsigned int __esi; unsigned int __ebp; unsigned int __esp; unsigned int __ss; unsigned int __eflags; unsigned int __eip; unsigned int __cs; unsigned int __ds; unsigned int __es; unsigned int __fs; unsigned int __gs; }; ``` So, it is indeed 16 `uint32_t`'s which would be loaded into corresponding registers before thread is started. Adding header, segment command and thread command gives us `0xA4` bytes. Now, time to craft the payload. Let's say we want it to print `Hi Frand` and `exit(0)`. Syscall convention for macOS x86\_32: * arguments passed on the stack, pushed right-to-left * stack 16-bytes aligned (note: 8-bytes aligned seems to be fine) * syscall number in the eax register * call by interrupt See more about syscalls on macOS [here](https://filippo.io/making-system-calls-from-assembly-in-mac-os-x/). So, knowing that, here's our payload in assembly: ``` push ebx #; push chars 5-8 push eax #; push chars 1-4 xor eax, eax #; zero eax mov edi, esp #; preserve string address on stack push 0x8 #; 3rd param for write -- length push edi #; 2nd param for write -- address of bytes push 0x1 #; 1st param for write -- fd (stdout) push eax #; align stack mov al, 0x4 #; write syscall number #; --- 14 bytes at this point --- int 0x80 #; syscall push 0x0 #; 1st param for exit -- exit code mov al, 0x1 #; exit syscall number push eax #; align stack int 0x80 #; syscall ``` Notice the line before first `int 0x80`. `segname` can be anything, remember? So we can put our payload in it. However, it's only 16 bytes, and we need a bit more. So, at `14` bytes we'll place a `jmp`. Another "free" space is thread state registers. We can set anything in most of them, and we'll put rest of our payload there. Also, we place our string in `__eax` and `__ebx`, since it's shorter than mov'ing them. So, we can use `__ecx`, `__edx`, `__edi` to fit the rest of our payload. Looking at difference between address of `thread_cmd.state.__ecx` and end of `segment_cmd.segname` we calculate that we need to put `jmp 0x3a` (or `EB38`) in last two bytes of `segname`. So, our payload assembled is `53 50 31C0 89E7 6A08 57 6A01 50 B004` for first part, `EB38` for jmp, and `CD80 6A00 B001 50 CD80` for second part. And last step -- setting the `__eip`. Our file is loaded at `0x1000` (remember `vmaddr`), and payload starts at offset `0x24`. Here's `xxd` of result file: ``` 00000000: cefa edfe 0700 0000 0300 0000 0200 0000 ................ 00000010: 0200 0000 8800 0000 0000 2001 0100 0000 .......... ..... 00000020: 3800 0000 5350 31c0 89e7 6a08 576a 0150 8...SP1...j.Wj.P 00000030: b004 eb38 0010 0000 0010 0000 0000 0000 ...8............ 00000040: a400 0000 0700 0000 0500 0000 0000 0000 ................ 00000050: 0000 0000 0500 0000 5000 0000 0100 0000 ........P....... 00000060: 1000 0000 4869 2046 7261 6e64 cd80 6a00 ....Hi Frand..j. 00000070: b001 50cd 8000 0000 0000 0000 0000 0000 ..P............. 00000080: 0000 0000 0000 0000 0000 0000 2410 0000 ............$... 00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000a0: 0000 0000 .... ``` Pad it with anything up to `0x1000` bytes, chmod +x and run :) P.S. About x86\_64 -- 64bit binaries are required to have `__PAGEZERO` (any mapping with `VM_PROT_NONE` protection covering page at 0x0). IIRC they [Apple] didn't make it required on 32bit mode only because some legacy software didn't have it and they're afraid to break it. [Answer] # 28 Bytes, Pre-compiled. Below is a formated hex dump of the Mach-O binary. ``` 00 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |---------| |---------| |---------| |---------| |---------| |---------| |---------/ | | | | | | +---------- uint32_t flags; // Once again redundant, no flags for safety. | | | | | +---------------------- uint32_t sizeofcmds; // Size of the commands. Not sure the specifics for this, yet it doesn't particularly matter when there are 0 commands. 0 is used for safety. | | | | +---------------------------------- uint32_t ncmds; // Number of commands this library proivides. 0, this is a redundant library. | | | +---------------------------------------------- uint32_t filetype; // Once again, documentation is lacking in this department, yet I don't think it particularly matters for our useless library. | | +---------------------------------------------------------- cpu_subtype_t cpusubtype; // Like cputype, this suggests what systems this can run on. Here, 0 is ANY. | +---------------------------------------------------------------------- cpu_type_t cputype; // Defines what cpus this can run on, I guess. -1 is ANY. This library is definitely cross system compatible. +---------------------------------------------------------------------------------- uint32_t magic; // This number seems to be provided by the compiling system, as I lack a system to compile Mach-O, I can't retrieve the actual value for this. But it will always be 4 bytes. (On 32bit systems) ``` Consists entirely of the header, and does not need the data nor the cmds. This is, by nature, the smallest Mach-O binary possible. It might not run correctly on any conceivable hardware, but it matches the specification. I'd supply the actual file, but it entirely consists of unprintable characters. [Answer] (uint)0x00000007 is "I386" and "X86" (name depending upon where in the XNU spec you are looking, but it's the correct arch) (uint)0x0x01000007 is X86\_64 Theoretically, you can OR any CPU value with 0x1000000 to make it a 64bit version. XNU seems to not always consider them discrete values; e.g., ARM 32 and 64 are 0x0000000C and 0x0100000C, respectively. Ah heck, here's the list I wound up having to figure out a few years back, note that most of these predate OS/X: ``` VAX = 1, // Little-Endian ROMP = 2, // Big-Endian -- 24bit or 32bit NS32032 = 4, // Hybrid -- Treat as Little Endian -- First 32b procs on the market NS32332 = 5, // Hybrid -- Treat as Little Endian -- These introduced a 20 byte "instruction cache" MC680x0 = 6, // Big-Endian X86 = 7, // Little-Endian I386 = 7, // alias for X86 and gets used interchangeably MIPS = 8, // Big-Endian NS32532 = 9, // Hybrid -- Treat as Little Endian -- These ran from 20MHz up to a stunning 30MHz MC98000 = 10, // Big-Endian HPPA = 11, // Big-Endian ARM = 12, // Both! -- will treat as Little-Endian by default MC88000 = 13, // Big-Endian SPARC = 14, // Big-Endian I860 = 15, // Little-Endian ALPHA = 16, // Big-Endian -- NB, this is a 64-bit CPU, but seems to show up w/o the ABI64 flag . . . POWERPC = 18, // Big-Endian X86_64 = 16777223, // Little-Endian POWERPC64 = 16777234, // Big-Endian ARM_64 = 0x0100000C // Both! -- wil treat as Little-Endian by default ``` ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/V9ZFc.png)](https://i.stack.imgur.com/V9ZFc.png) Found this picture on the web today. Being a lazy programmer, I don't want to actually open google and type a couple of characters. Way too much work! This is such an important task that it should be automated. # Challenge Everyone knows that the [first image](https://www.google.nl/search?q=codegolf&tbm=isch) in a google search result is always the best. Hence it should be presented to the user. You are to write a program or function which takes a string as parameter and displays the first image it finds on google when you search for that name + the words `glamour shot` behind it. # Google search queries To search for images on google, the url should contain the query parameter [`tbm=isch`](https://webapps.stackexchange.com/questions/58550/what-does-tbm-mean-in-google-search) and `q=query`, with `query` being the name you want to search for. A valid query string for my name `Bas` would be `www.google.com/search?tbm=isch&q=Bas` # Input Your program or function takes a single parameter of input, which is the name you want to search for on google. This string will consist of the characters `[a-z]`, `[A-Z]`, `[0-9]` and (space). This string can be space seperated, to search for a space seperated string on google, one should replace the spaces with `+`. For example, this is a valid query: [www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot](http://www.google.com/search?tbm=isch&q=Bassdrop%20Cumberwubwubwub%20glamour%20shot) # Output The image can either be drawn to the screen, or saved to a file (in any format). If the first search result on google is a gif file, you can either show the gif or show any frame of that gif. # Test cases Run this snippet to see the expected results ``` <pre>f('Bas') // www.google.com/search?tbm=isch&q=Bas+glamour+shot <img src="https://i.stack.imgur.com/IViaM.jpg" style="width:40%;height:40%"/> <pre>f('Bassdrop Cumberwubwubwub') // www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot <img src="https://i.stack.imgur.com/tdhvW.png" style="width:40%;height:40%"/> ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! [Answer] ## PowerShell v4+, 160 bytes ``` param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg" ``` Takes input `$a` as a string. Does an `Invoke-WebRequest` (`iwr`) to the appropriate Google location, using inner-string script block to `-replace` spaces with `+` in the input string. We take the `.links` of that, where the `.innerhtml` is `-like` our input string. That yields the links with the proper thumbnail description. Take the first `[0]` one of those, take *its* `.innerhtml` and `-split` it on quotations. The fourth `[3]` element is the text inside the `img src="` portion, so we do another `iwr` on that, specifying `-outf`ile to be `$a.jpg` in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg. [Answer] # Excel VBA ***+***, ~~465~~ 332 Bytes > > ***NOTE:*** Uses References to > > > * Microsoft HTML Object Library > * Microsoft Internet Controls > * Microsoft Scripting Runtime > > > **Golfed:** Full `Sub` routine that takes input `n` (short for name) of expected type `Variant/String` and outputs the first google image search result for the query of that name and `glamour shot` to an internet explorer window. ``` Sub g(n) Set i=New InternetExplorer l="google.nl/search?tbm=isch&q="&Replace(n," ","+")&"+glamour+shot" For y=0To 2 i.navigate l While i.readyState<4 DoEvents Wend j=0 Do Until InStr(1,l,IIf(y,"yp","res")) j=j+1 Set x=i.document.getElementsByTagName(IIf(y,"img","a"))(j) If y Then l=x.src Else l=x.href Loop Next i.visible=1 End Sub ``` -2 bytes for removing white space in `If InStr(1, a.href, "imgres") Then` -2 bytes for changing `.navigate (a.href)` to `.navigate a.href` -27 bytes for reducing `for each a in ... if (...) then ... end if .. next` loop to `do until ... loop` -10 bytes for condensing `imgres` to `res` and `encrypted` to `yp` -8 bytes for removing initalizers for `j`, `k` and assuming clean module -1 byte for changing `google.com` to `google.nl` -3 bytes for replacing `Dim i as New ...` with `Set i=New ...` -8 bytes for removing `SHDocVw.` class reference -12 bytes for removing `with i` block -7 bytes for removing `i.quit` - this causes some memory leakage by leaving internet explorer open in the background, as such it is recommended that either the full ungolfed version is used instead or that the internet explorer task is terminated through task manager after use -6 bytes for moving `i.navigate` into helper subroutine `h` -13 bytes for moving `Do Until ... Loop` into helper subroutine -2 bytes by moving `j=0` into helper and removing `,j`, `,0` (x2) -11 bytes for converting to an anonymous immediate window function -8 bytes for reducing helper function calls into `for .. next` loop -16 bytes for changing output from `Sheets(1)` picture object to displaying via the `InternetExplorer` object **Ungolfed, 1304 Bytes** ``` Option Private Module Option Compare Text Option Explicit Option Base 0 Sub GlamourShot(ByVal name As String) Dim ie As New SHDocVw.InternetExplorer, _ doc As MSHTML.HTMLDocument, _ link As String, _ j As Integer, _ k As Integer With ie On Error GoTo CloseIE #'prevents memory leak Let .visible = True Call .navigate("www.google.com/search?tbm=isch&q=" & _ Replace(name, " ", "+") & _ "+glamour+shot") While .readyState <> READYSTATE_COMPLETE Or .Busy VBA.DoEvents Wend Set doc = .document Let j = 1 Do Until InStr(1, link, "imgres") > 0 Let link = doc.getElementsByTagName("a")(j).href Let j = j + 1 Loop Call .navigate(link) While .readyState <> READYSTATE_COMPLETE Or .Busy VBA.DoEvents Wend Let k = 1 Do Until InStr(1, link, "encrypted") > 0 Let link = doc.getElementsByTagName("img")(k).src Let k = k + 1 Loop With ThisWorkbook.ActiveSheet Call .Range("A1").Select Call .Pictures.Insert(link) Call .Activate End With CloseIE: Call .Quit End With End Sub ``` **Usage gif** [![Usage Gif](https://i.stack.imgur.com/yQFgR.gif)](https://i.stack.imgur.com/yQFgR.gif) [Answer] # [Vimperator](http://vimperator.org/), 30 keystrokes ``` pgi<End> glamour shot<CR>fi222jf<CR>fim2 ``` Alternatively 27 keystrokes if you don't need the highest resolution image: ``` pgi<End> glamour shot<CR>fi222j;I<CR> ``` Video: <https://youtu.be/t8824UjlYt8> Fortunately the standard search engine in Firefox is google, and Vimperator let you type hints by default. This is longer than it has to be to make sure that it always works regardless of what you search for. Takes input through the clipboard. ### Explanation: ``` p Google the contents of the clipboard gi Select the search box <End> Move the cursor to the end of the text glamour shot Type " glamour shot" <CR> Press enter to search fi2 Click the second link that begins with the letter "i" (images) 22j Go 22 scroll steps down on the page. This makes it so that the first row of images are at the very top of the screen. f<CR> Click the first clickable element, which is the first image because we scrolled down fim2 Click the second link containing "im" (view image) ``` Thanks to @TaylorScott for finding an edge case. [Answer] # Python 3.6, ~~247~~ ~~242~~ 232 maybe 224 bytes This is a cute attempt to solve this one. It will save a the file as `p.png` in the current directory. ``` import sys; import requests as r; from bs4 import BeautifulSoup as s; n = sys.argv[1]; open('p.png', 'wb').write(r.get(s(r.get(f'https://www.google.com.br/search?tbm=isch&q={n}+glamour+shot').content,'lxml').find_all('img')[1].get('src')).content) ``` To run it with ease from the command line, just place the above content in a file, such as `glamour.py` and run: ``` $ python glamour.py NAME_YOU_WANT ``` ### Update 1: Better version with new google url ``` import sys; import requests as r; from bs4 import BeautifulSoup as s; n = sys.argv[1]; open('p.png', 'wb').write(r.get(s(r.get(f'http://www.google.nl/search?tbm=isch&q={n}+glamour+shot').content,'lxml').find_all('img')[1].get('src')).content) ``` ### Update 2: I saved a few bytes: * By only importing the get function from the requests module * taking advantage of the new python 3.6 string interpolation `f` flag without allocating the `sys.argv` to a variable * eliminating some white spaces * turning it into a one-liner * removing the parser specification from the `BeautifulSoup` call The last one is controversial, since it results in a std.output message telling the programmer to specify the parser for cross platform compatibility, so it might be considered unwanted output. Here is the 224 bytes version: ``` import sys;from requests import get;from bs4 import BeautifulSoup as s;open('p.png','wb').write(get(s(get(f'http://www.google.nl/search?tbm=isch&q={sys.argv[1]}+glamour+shot').content).find_all('img')[1].get('src')).content) ``` Here is the 232 bytes version: ``` import sys;from requests import get;from bs4 import BeautifulSoup as s;open('p.png','wb').write(get(s(get(f'http://www.google.nl/search?tbm=isch&q={sys.argv[1]}+glamour+shot').content, 'lxml').find_all('img')[1].get('src')).content) ``` But the shorter version could be used if std.out is redirected to `/dev/null` or something :D [Answer] # Racket, 284 byes ``` (require net/url html-parsing sxml racket/draw)(define(g n)(let([g(compose get-pure-port string->url string-append)])(make-object bitmap%(g(car((sxpath"//*[@id='ires']//@src/text()")(html->xexp(g"http://www.google.com/search?tbm=isch&q="(string-replace n" ""+")"+glamour+shot")))))))) ``` Screenshot: [![enter image description here](https://i.stack.imgur.com/2mHzt.png)](https://i.stack.imgur.com/2mHzt.png) ]
[Question] [ Cribbage is an interesting game, because you need a specific board to score your game. A cribbage board looks like this: [![enter image description here](https://i.stack.imgur.com/tfwSC.jpg)](https://i.stack.imgur.com/tfwSC.jpg) Notice how the first column is on the left as it goes up, then on the right as it goes down, then back on the left as it goes up again. And here is what a poorly ~~drawn~~ rendered ASCII art of a cribbage board looks like: ``` * * * ----------- ------- / * \ |*|*|*| /* * *\ |*|*|*| / * * * \ |*|*|*| | * * | |*|*|*| |* * * * * *| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- * * * |* * * * * *| | * * | \ * * * / \* * */ \ * / ----------- ``` Here is your challenge: Step 1: Draw this ASCII art of a cribbage board. Trailing whitespace is OK, provided that there is no visible difference. Step 2: Given three integers as input, display each peg in the correct hole. The pegs can be 0-indexed or 1-indexed. The inputs will be in `[0-121]` inclusive. You can take these inputs in any reasonable manner, for example, 3 separate inputs, an array, command line arguments, etc. Here's an example for the input `(0, 37, 100)` (1-indexed): ``` * * * ----------- ------- / * \ |*|*|*| /* * *\ |*|*|*| / 2 * * \ |*|*|*| | * * | |*|*|*| |* * * * * *| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|3| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- 1 * * |* * * * * *| | * * | \ * * * / \* * */ \ * / ----------- ``` Step 3: Output the whole thing. # Test IO: Since each of these is pretty vertically tall, I will only include 2, but you can see more at [this github gist](https://gist.github.com/DJMcMayhem/a65d03f6f2a9d928438b3fa680fe99e1). ``` #Input: (56, 56, 56) #Output: * * * ----------- ------- / * \ |*|*|*| /* * *\ |*|*|*| / * * * \ |*|*|*| | * * | |*|*|*| |* * * * * *| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |3|2|1| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- * * * |* * * * * *| | * * | \ * * * / \* * */ \ * / ----------- #Input: (120, 89, 23) #Output: * * * ----------- ------- / * \ |1|*|*| /* * *\ |*|*|*| / * * * \ |*|*|*| | * * | |*|*|*| |* * * * * *| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|3| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|2|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| |*|*|*| ------- ------- ------- * * * |* * * * * *| | * * | \ * * * / \* * */ \ * / ----------- ``` Standard loopholes apply, and the shortest answer in bytes wins! [Answer] # [Matricks](https://github.com/jediguy13/Matricks), ~~1441~~ 980 bytes Hooray for esolangs! Edit: compressed checking each number into a loop to save a ton of bytes. Also made the bottom part "copy" the top (I need a reverse function). I also replaced most ascii characters with their raw values to save a few more. Also, I fixed a bug in the interpreter where number input wasn't working right. ``` a45;u[m"|;:5:1;];a[a45;u[m42:5:1;];];a{};a{};z:1;a[m32:6:1;a{a{};};];a{a{};};u{};u{};u{};z5:;v[mic%2:42:32;:1:17;s::"|;;s:16:"|;;s:7:32;s:9:32;v[m32:4:7;s1:2:42;s2:4:42;s3:6:42;a[mi(re3)&(c=1):42:32;:4:3;];a[m32:4:7;s3::42;s2:2:42;s1:4:42;];];s3::"|;;s3:16:"|;;s2::47;s1:1:47;s:2:47;s2:16:92;s1:15:92;s:14:92;v[mi(cT3)&(cE13)&(r=1):45:32;:2:17;];a[m32:7:3;];a[a45;u[m"|;:5:1;];a[a45;u[m42:5:1;];];a{};a{};z:1;v[mic%2:42:32;:1:7;];];];u{z43:10;q1:;u{q5:;};u{q4:;z2:;};u{q3:;z4:;};u{q2:;z6:;};u{q1:;z8:;};u{z10:;};q6:;s2::92;s3:1:92;s4:2:92;s2:16:47;s3:15:47;s4:14:47;b[mi(c%2)&(ce6):42:32;:1:10;];};s:1:48;s:2:-1;j1; s:1:g:1;+1;s:2:g:2;+1;s::n;;ig:;E36:s(40-g:;)*1.2+2:1+g:2;*2:g:1;;:ig:;T80:s(120-g:;)*1.2+2:21+g:2;*2:g:1;;:i(g:;E76)&(g:;T40):s(g:;-31)*1.2-4:15-g:2;*2:g:1;;:ig:;=37:s3+g:2;:2+g:2;*2:g:1;;:ig:;=38:s2+g:2;:8:g:1;;:ig:;=39:s3+g:2;:14-g:2;*2:g:1;;:ig:;=77:s51+g:2;:16-g:2;*2:g:1;;:ig:;=78:s52+g:2;:18:g:1;;:s51+g:2;:20+g:2;*2:g:1;;;;;;;;;;ig:2;e2:j1;:s::;s:1:;;s:2:; ``` Takes input on command line: `python matricks.py <filename> [[]] <num1>,<num2>,<num3> --asciiprint` Matricks is a language of my own creation. Documentation is on the Github page. The most recent update was a bugfix, no new features added or anything. Breakdown of this solution: 1. First block created 2. Block copied to fill entire board 3. Top curve 4. Bottom curve 5. Checking the placement of each number [Answer] # Python 3, 496 bytes ``` z=r"""SSSWT WOSY /UR\UZ /RR*\W Z /WQQQ\WZ MWZ NWZVVVVVVV YWYWY TW NPW MPW \WQQQ/PU\RR*/ PS\UR/PS O""" for y in'M|UQR|,N|TUT|,OY----,P\nS,Q*W,R*U,SWW,T* * *,UW ,V\nYWYWYXXXXX,W ,X\nZ Z Z,Y-------,Z|*|*|*|'.split(','):z=z.replace(y[0],y[1:]) L=list(range(50,-1,-1)) del L[1::6] def f(*s): b=list(z) for p in(0,1,2):b[(L[:-5]+[3+p,2+p,3+p]+L[-6::-1]+[51+p,52+p,51+p]+L)[s[p]]*28+([2*p+1]*37+[2+2*p,8,14-2*p]+[15-2*p]*37+[16-2*p,18,20+2*p]+[21+2*p]*42)[s[p]]]=str(p+1) print(*b,sep='') ``` Running (or importing) the code creates a function that is called with the three players scores: `f(5, 38, 53)`. **Somewhat ungolfed version** ``` z=r"""SSSWT WOSY /UR\UZ /RR*\W Z /WQQQ\WZ MWZ NWZVVVVVVV YWYWY TW NPW MPW \WQQQ/PU\RR*/ PS\UR/PS O""" subs='M|UQR|,N|TUT|,OY----,P\nS,Q*W,R*U,SWW,T* * *,UW ,V\nYWYWYXXXXX,W ,X\nZ Z Z,Y-------,Z|*|*|*|' for y in subs.split(','): z=z.replace(y[0],y[1:]) L=list(range(50,-1,-1)) del L[1::6] def f(*s): b=list(z) for p in(0,1,2): R = L[:-5] + [3+p,2+p,3+p] + L[-6::-1] + [51+p,52+p,51+p] + L C = [2*p+1]*37 + [2+2*p,8,14-2*p] + [15-2*p]*37 + [16-2*p,18,20+2*p] + [21+2*p]*42 b[R[s[p]]*28+C[s[p]]] = str(p) print(*b,sep='') ``` `z` is a coded/compressed version of the empty cribbage board. `subs` contains a comma separated list of substitutions to decode/uncompress `z`. In each substitution, the first letter is the substring to replace and the remainder of the string is the replacement. The `for y in subs.split(','):` loop does the substitutions. For example, `Z|*|*|*|` causes all 'Z's to be replaced by `|*|*|*|`. The compression method was used for its simplicity and effectiveness (its better than the stdlib). But it could probably be improved or replaced with something better. Because, Python strings are immutable, `b` is a list of the characters in the game board. `R` is a list mapping a player and score to a row in the ascii game board. It uses 'L', which is a list or row numbers from which row numbers corresponding to '-------'-rows have been deleted. Similarly, `C` maps a player and score to a column in the ascii game board. Using `R` and `C`, the proper peg hole in the game board can be set to the player's number. Lastly, `print(*b,sep='')` prints each character in `b` without inserting a space between adjacent characters. (Saves a few bytes over using ''.join) [Answer] # Python 2, 615 bytes ``` def f(a): D="-";S=" ";A=S*55+D+S;B="|/4 /41/4 - 2 -4-3 -|/4 /43/4 - 2 -4-1 -".replace("4"," ");C=B.replace("/","\\");s=t=u="";d={"1":0,"2":0,"3":0} for i in range(23):j=15>i>7;k=i-i/8;x=k%7*5;y=(6-k%7)*5;M=A+S*52+("123","321")[i<8]+D+S+A;N=chr((x,y)[j]/10+49);Q=("|"+N)[i%2]*5+D;s+=(S+S*5*(i<7)+C[x+39:x+34:-1]*j+B[y+39:y+34:-1]*(i>15)+("| "[i<7]+N)[i%2]+D+Q*(7+(i>15))+("|"+N)[i%2]+B[x:x+5]*(i<7)+C[y:y+5]*j+S*(i<16),(M[::-1],M)[i<8])[i%8==7] for x in s: if "4">x>"0":d[x]+=1;x=("*"+x)[d[x]==a[x]+1] t+=x for i in range(1512):j=i/27;k=i%27;u+=t[k*57+(56-j,j)[16>k>10and 51>j>5]]+"\n"*(k>25) print u ``` The function is called by passing in a dictionary that contains the scores. For example: ``` f({"1":40, "2":70, "3":76}) ``` The byte count reflects indenting the "for x" loop with tabs instead of spaces. **Explanation** The first loop builds the board horizontally into a 57x27 string, with track numbers instead of "holes". ``` -|||||-|||||-|||||-|||||-|||||-|||||-|||||-||/ 1-11111-11111-11111-11111-11111-11111-11111-1 / -|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 1/ 2-22222-22222-22222-22222-22222-22222-22222-2 - -|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2 - 3-33333-33333-33333-33333-33333-33333-33333-3 - -|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3 - - 321- - \||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|3 - \ 3-33333-33333-33333-33333-33333-33333-33333-3 - \3 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 2 - - 2-22222-22222-22222-22222-22222-22222-22222-2 - - 2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| 1\ - 1-11111-11111-11111-11111-11111-11111-11111-1 \ - 1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-||\ - -321 - - 1|-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| - 1-11111-11111-11111-11111-11111-11111-11111-11111-1 - 2 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| - 2-22222-22222-22222-22222-22222-22222-22222-22222-2 /3 |-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| / 3-33333-33333-33333-33333-33333-33333-33333-33333-3 /||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-|||||-| ``` The second loop copies the string, replacing the numbers with asterisks except at the scoring peg locations. The peg locations in the straight lines in the middle of the track come out backward. The third loop changes the orientation to vertical, correcting the pegs in the middle track and adding newline characters. Try it [here](https://repl.it/C0tM) [Answer] ## Batch, ~~1302~~ ~~1099~~ ~~1096~~ 1079 bytes ``` @set s= set @%s%o=echo @%o%off %s%x=41 %s%y=35 %s%z=121 %s%m=------- %s%w= %s%p=if %1== %s%q=if %2== %s%r=if %3== %s%l=call:l %l% %o%%w%%w%%w%%w% %g% %h% %i% %o% %m%---- %w%%m% %l% %p%38%s%j=1 %o% /%w%%j%%w%\ %n% %l% %q%38%s%j=2 %o% /%f%%w%%j%%w%%a%\ %n% %l% %q%37%s%j=2 %q%39%s%k=2 %o%/ %j% %c% %k% \%n% %l% %o%^|%w%%c% %d%%w%^|%n% %l% %o%^|%a% %b% %c%%w%%d% %e% %f%^|%n% %l% for /l %%a in (1,1,7)do call:b %o%%m% %m% %m% %o% %a% %b% %c% ^|%d% %e% %f%%w%%g% %h% %i%^| %l% %o%%w%%w%^|%w%%f% %g%%w%^| %l% %q%77%s%j=2 %q%79%s%k=2 %o%%w%%w%\ %j% %g% %k% / %l% %q%78%s%j=2 %o%%w%%w% \%i%%w%%j%%w%%d%/ %r%78%s%j=3 %o%%w%%w% \%w%%j%%w%/ %o%%w%%w% %m%---- exit/b :b %o%%m% %m% %m% for /l %%a in (1,1,4)do call:o :o %o%^|%a%^|%b%^|%c%^| ^|%d%^|%e%^|%f%^|%n% :l for %%a in (a b c d e f g h i j k) do%s%%%a=* %p%%x%%s%a=1 %q%%x%%s%b=2 %r%%x%%s%c=3 %r%%y%%s%d=3 %q%%y%%s%e=2 %p%%y%%s%f=1 %p%%z%%s%g=1 %q%%z%%s%h=2 %r%%z%%s%i=3 %s%n= ^^^|%g%^^^|%h%^^^|%i%^^^| set/ax-=1,y+=1,z-=1 ``` Ungolfed: ``` @echo off @rem values that pegs at the very top of each column would be set x=41 set y=35 set z=121 rem deal with the four custom pegs on the top curve call :loop echo %g% %h% %i% echo ----------- ------- call :loop if %1==38 (set j=1) else set j=* echo / %j% \ ^|%g%^|%h%^|%i%^| call :loop if %2==38 (set j=2) else set j=* echo /%f% %j% %a%\ ^|%g%^|%h%^|%i%^| call :loop if %2==37 (set j=2) else set j=* if %2==39 (set k=2) else set k=* echo / %j% %c% %k% \ ^|%g%^|%h%^|%i%^| call :loop echo ^| %c% %d% ^| ^|%g%^|%h%^|%i%^| call :loop echo ^|%a% %b% %c% %d% %e% %f%^| ^|%g%^|%h%^|%i%^| call :loop rem deal with the 7 sets of 5 standard rows call :block call :block call :block call :block call :block call :block call :block rem deal with the four custom pegs on the bottom curve echo ------- ------- ------- echo %a% %b% %c% ^|%d% %e% %f% %g% %h% %i%^| call :loop echo ^| %f% %g% ^| call :loop if %2==77 (set j=2) else set j=* if %2==79 (set k=2) else set k=* echo \ %j% %g% %k% / call :loop if %2==78 (set j=2) else set j=* echo \%i% %j% %d%/ if %3==78 (set j=3) else set j=* echo \ %j% / echo ----------- exit/b :block echo ------- ------- ------- call :output call :output call :output call :output :output rem prints each of the 35 main rows echo ^|%a%^|%b%^|%c%^| ^|%d%^|%e%^|%f%^| ^|%g%^|%h%^|%i%^| :loop rem check for pegs in the current row, also works for some of the curve if %1==%x% (set a=1) else set a=* if %2==%x% (set b=2) else set b=* if %3==%x% (set c=3) else set c=* if %3==%y% (set d=3) else set d=* if %2==%y% (set e=2) else set e=* if %1==%y% (set f=1) else set f=* if %1==%z% (set g=1) else set g=* if %2==%z% (set h=2) else set h=* if %3==%z% (set i=3) else set i=* rem decrement the first and third columns, increment the second column set/a x-=1 set/a y+=1 set/a z-=1 ``` [Answer] # Java, ~~1059~~ 1035 bytes ``` class C{static int[]i=new int[3];String d="-------",l=d+"----";<T>void p(String s,T...o){System.out.format(s+"\n",o);}C(){p("%26s\n%14s%13s\n /%6s \\%15s\n /%s%6s%6s\\%14s\n/%4s%4s%4s \\%13s\n|%6s%4s |%13s\n|%s%10s|%13s",o(121,0),l,d,s(38,0),t(120,0),s(37,0),s(38,1),s(39,0),t(119,0),s(37,1),s(38,2),s(39,1),t(118,0),s(37,2),s(39,2),t(117,0),o(36,0),o(40,2),t(116,0));for(int j=0;j<7;)g(j++*5);d();p(" %s |%s%10s|\n%11s%6s%4s |\n%11s%4s%4s%4s /\n%12s%s%6s%6s/\n%13s%6s /\n%24s",o(0,0),o(76,2),o(80,0),"|",s(77,0),s(79,0),"\\",s(77,1),s(78,0),s(79, 1),"\\",s(77,2),s(78,1),s(79,2),"\\",s(78,2),l);}String s(int r,int c){return r==i[c]?c+"":"*";}String t(int r,int d){return l.format("|%s|%s|%s| ",s(r,d),s(r,1),s(r,2-d));}void r(int r){p(t(35-r,0)+t(41+r,2)+t(115-r,0));}void d(){p(d+"%10s%10s",d,d);}void g(int r){d();for(int j=0;j<5;)r(r+j++);}String o(int r,int d){return l.format("%s %s %s",s(r,d),s(r,1),s(r,2-d));}public static void main(String[]a){for(int j=0;j<3;)i[j]=Integer.decode(a[j++]);new C();}} ``` Ungolfed: ``` class Crib { static int[] input = new int[3]; String divider = "-------", longDivider = divider + "----"; <T> void p(String s, T...o) { System.out.format(s+"\n",o); } Crib() { p("%26s", troika(121,0)); p("%14s%13s", longDivider, divider); p(" /%6s \\%15s", star(38,0), trio(120,0)); p(" /%s%6s%6s\\%14s", star(37,0), star(38,1), star(39,0), trio(119,0)); p("/%4s%4s%4s \\%13s", star(37,1), star(38,2), star(39,1), trio(118,0)); p("|%6s%4s |%13s", star(37,2), star(39,2), trio(117,0)); p("|%s%10s|%13s", troika(36,0), troika(40,2), trio(116,0)); for(int i = 0; i < 7;) group(i++*5); printDivider(); p(" %s |%s%10s|", troika(0,0), troika(76,2), troika(80,0)); p("%11s%6s%4s |", "|", star(77,0), star(79,0)); p("%11s%4s%4s%4s /", "\\", star(77,1), star(78,0), star(79, 1)); p("%12s%s%6s%6s/", "\\", star(77,2), star(78,1), star(79,2)); p("%13s%6s /", "\\", star(78,2)); p("%24s", longDivider); } String star(int row, int cell) { return row == input[cell] ? cell+"" : "*"; } String trio(int row, int diff) { return longDivider.format("|%s|%s|%s| ", star(row, diff), star(row, 1), star(row, 2-diff)); } void printRow(int row) { p(trio(35-row, 0) + trio(41+row, 2) + trio(115-row, 0)); } void printDivider() { p(divider + "%10s%10s", divider, divider); } void group(int row) { printDivider(); for(int i = 0; i < 5;) printRow(row+i++); } String troika(int row, int diff) { return longDivider.format("%s %s %s", star(row, diff), star(row, 1), star(row, 2-diff)); } public static void main(String[] args) { for(int i = 0; i < 3;) input[i] = Integer.decode(args[i++]); new Crib(); } } ``` Abuses formats (printfs) like mad, which is probably why it's not as small as it could be. ]
[Question] [ There's [classic combinatorial result](http://www.cut-the-knot.org/arithmetic/combinatorics/FibonacciTilings.shtml) that the number of ways to tile a `2*n` strip by `1*2` dominoes is the nth Fibonacci number. You goal is to print all the tilings for a given `n`, drawn with dashes and vertical lines like these 8 tilings for `n=5`: ``` |———— |———— ——|—— ——|—— |||—— |||—— ————| ————| ||——| ||——| |——|| |——|| ——||| ——||| ||||| ||||| ``` You are to provide a program or named function that take `n` as input and prints the required output. Fewest bytes wins. **Input** A number `n` between `1` and `10` inclusive via STDIN or function input. **Output** Print every possible domino tilings of the `2*n` strip, drawn horizontally. The tilings may be in any order, but each should appear exactly once. They must be separated by a blank line. A vertical domino is made of two vertical bars (`|`) and a horizontal domino is made of two em dashes (`—`). You may use hyphens (`-`) in place of em dashes to stay in ASCII. You can do anything with whitespace as long as the printed output looks the same. [Answer] # C, 106 **Golfed version** ``` f(n){ for(int i,h=n*2<<n;h--;(i/3|i/3*2)-i||(putchar(i>>h%n&1?45:124),h%n||puts(h%(n*2)?"":"\n"))) i=h/2/n; } ``` **Original version** ``` i,j,n; main(){ scanf("%d",&n); for(i=1<<n;i--;)if((i/3|i/3*2)==i){ for(j=1<<n;j/=2;)printf("%c",i&j?'-':'|');puts(""); for(j=1<<n;j/=2;)printf("%c",i&j?'-':'|');puts("\n"); } } ``` **How it works** The variable `i` runs from `1<<n-1` down to 0, producing all possible binary numbers with `n` digits. 0 encodes for `|` and 1 encodes for `-`. We are interested in numbers that contain 1's in pairs. Obviously such numbers are divisible by 3. When a number is divided by 3, the original number can be recovered by multiplying the result by 2 and adding it to itself (effectively mutliplying by 3.) Most numbers will require a carry, but when the process is carried out on the numbers of interest, no carry is required, so in these cases only, OR can be used instead of addition. This is used to test for the numbers of interest, as they are the only ones where the expression `i/3|i/3*2` returns the original value of `i`. See example below. `1111`=15 ---> `0101`=5 ---> `1111`=15 (valid, `0101|1010`==`0101+1010`) `1001`=9 ---> `0011`=3 ---> `0111`=7 (invalid, `0011|0110` != `0011+0110`) The test value is always equal or less than the original value. As numbers that are not multiples of 3 also return a number less than the original when divided by 3 then multipled by 3, the test gives the desired FALSE on these numbers too. In the original version a couple of loops in `j` are used to scan through the bits of `i` and produce the output. In the golfed version a single `for` loop is used, in which `h` runs through all numbers from `(n*2)*(1<<n)-1` down to 0. Values of `i` are generated by `h/2/n`. The variable `j` is no longer used, as the equivalent quantity is obtained from `h%n`. The use of `n*2` enables both lines to be printed from the same loop, with some nifty multiplexing in the `puts` statement to print either one or two newlines at the end of the row. Note that the meat of this is in the increment position of the `for()` bracket and therefore gets executed *after* the `i=h/2/h`. **Sample output n=6:** ``` $ ./a 6 ------ ------ ----|| ----|| --|--| --|--| --||-- --||-- --|||| --|||| |----| |----| |--|-- |--|-- |--||| |--||| ||---- ||---- ||--|| ||--|| |||--| |||--| ||||-- ||||-- |||||| |||||| ``` [Answer] # CJam, ~~33~~ 27 bytes ``` LN{_'|f+@"——"f++}ri*\;{_N}/ ``` *Thanks to @jimmy23013 for golfing off 6 bytes!* [Try it online!](http://cjam.tryitonline.net/#code=TE57Xyd8ZitAIuKAlOKAlCJmKyt9cmkqXDt7X059Lw&input=Ng) ### Background This is an iterative implementation of a recursive algorithm: The possible tilings for *n* can be obtained by adding a vertical domino to the possible tilings for *n - 1* and two horizontal dominos to the possible tilings for *n - 2*. This way, the number of tilings for *n* is the sum of the numbers of tilings for *n - 1* and *n - 2*, i.e., the *nth* Fibonacci number. ### How it works ``` LN " A:= [''] B:= ['\n'] "; { }ri* " Repeat int(input()) times: "; _'|f+ " C = copy(B); for T ∊ C: T += '|' "; @ " Swap A and B. "; "——"f+ " for T ∊ B: T += "——" "; + " B = C + B "; \; " Discard A. "; {_N}/ " for T ∊ B: print T, T + '\n' "; ``` ### Example run ``` $ alias cjam='java -jar cjam-0.6.2.jar' $ cjam domino.cjam <<< 3 ||| ||| ——| ——| |—— |—— $ for i in {1..10}; do echo $[$(cjam domino.cjam <<< $i | wc -l) / 3]; done1 2 3 5 8 13 21 34 55 89 ``` [Answer] # Haskell, 89 bytes ``` f(-1)=[] f 0=[""] f n=map('|':)(f$n-1)++map("--"++)(f$n-2) g=unlines.(>>= \x->[x,x,""]).f ``` `f` is a function that given a number returns a list of one lines of all the possible Fibonacci tilings of length n possible. it doesn't matter that it returns one line, because both lines of all tilings are the same. `f` works by calling recursively on `n-1` and `n-2` and adding `"|"` and `"--"` (respectively) to the strings. `g` is the function that answers the questions. it basically calls `f` on the input, doubles every string so that it would show two lines and joins them all by newlines. **example output:** ``` *Main> putStrLn $ g 5 ||||| ||||| |||-- |||-- ||--| ||--| |--|| |--|| |---- |---- --||| --||| --|-- --|-- ----| ----| ``` [Answer] # CJam, ~~42~~ 37 bytes ``` 3li:L#,{3b"——|"2/f=s}%{,L=},_&{N+_N}/ ``` I've counted the dashes as one byte each since the question allows to replace them with ASCII hyphens. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") # How it works To obtain all possible tilings of **2 × L**, we iterate over all non-negative integers **I < 3L**, making even digits in base 3 correspond to horizontal dominos and odd digits to vertical ones. Since each **I** has **L** or less digits in base 3, this generates all possible ways of covering the **2 × L** strip. All that's left is to filter out the coverings that are bigger or smaller than **2 × L** and print the remaining coverings. ``` 3li:L#, " Read an integer L from STDIN and push A := [ 0 1 ... (3 ** N - 1) ]. "; { " For each integer I in A: "; 3b " Push B, the array of I's base 3 digits. "; "——|"2/ " Push S := [ '——' '|' ]. "; f= " Replace each D in B with S[D % 2] (the modulus is implicit). "; s " Flatten B. "; }% " Collect the result in an array R. "; {,L=}, " Filter R so it contains only strings of length L. "; _& " Intersect R with itself to remove duplicates. "; {N+_N}/ " For each string T in B, push (T . '\n') twice, followed by '\n'. "; ``` # Example run ``` $ cjam domino.cjam <<< 3 |—— |—— ——| ——| ||| ||| $ for i in {1..10}; do echo $[$(cjam domino.cjam <<< $i | wc -l) / 3]; done 1 2 3 5 8 13 21 34 55 89 ``` [Answer] # JavaScript (E6) 102 Generate configurations from bit sequences, 0 -> '--' and 1 -> '|'. ``` F=n=>{ for(i=0;(j=++i)<2<<n;s.length==1+n&&console.log('\n'+s+s)) for(s='\n';j>1;j>>=1)s+=j&1?'|':'--'; } ``` **Test** In firefox/firebug console ``` F(5) ``` *Output* ``` |---- |---- --|-- --|-- ----| ----| |||-- |||-- ||--| ||--| |--|| |--|| --||| --||| ||||| ||||| ``` [Answer] # Haskell: 109 bytes This is a translation of the well-known Haskell one-liner for lazily computing the sequence of Fibonacci numbers: ``` b=map.map.(++) w=zipWith z=w(++) s=["\n"]:["|\n"]:z(b"--"s)(b"|"$tail s) f=sequence_.map putStrLn.(w z s s!!) ``` The main sequence of tiling strings, ungolfed: ``` dominos = [""] : ["|"] : zipWith (++) ("--" `before` dominos) ("|" `before` tail dominos) where before = map . map . (++) ``` And the Fibonacci one-liner for comparison: ``` fibs = 0 : 1 : zipWith (+) fibs (tail fibs) ``` Usage example: ``` $ ghci fibtile GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. [1 of 1] Compiling Main ( fibtile.hs, interpreted ) Ok, modules loaded: Main. *Main> f 5 ----| ----| --|-- --|-- --||| --||| |---- |---- |--|| |--|| ||--| ||--| |||-- |||-- ||||| ||||| *Main> ``` [Answer] # Cobra - 176 Can't wait till I've finished the Cobra golfing package. ``` def m(n) for t in.f(n),print t+t def f(n,x='')as String* if x.length<n,for i in.f(n,x+'-').toList+.f(n,x+'|').toList,yield i else if not'-'in x.replace('--',''),yield x+'\n' ``` [Answer] # J - 54 char Function taking `n` as argument on the right. ``` 0{::(];'--'&,"1@[,'|',"1])&>/@[&0&((1 2$,:)&.>'';,'|') ``` The main root of this golf is the `(];'--'&,"1@[,'|',"1])&>/`. This takes a list of tilings of length (N-2) and (N-1), and returns a list of tilings of length (N-1) and N. This is the standard Fibonacci recurrence, à la linear algebra. `];` returns the right list as the new left (as there is no change). `'--'&,"1@[` adds `--` tiles to the left list, while `'|',"1]` adds `|` tiles to the right list, and those together are the new right list. We iterate that over and over `n` times (that's the `@[&0`) and start with the empty tiling and the single tiling of length 1. Then we return the first of the pair with `0{::`. Meaning, if we run it zero times, we just return the first i.e. the empty tiling. If we run it `n` times, we calculate up to the `n` and (`n`+1) pair, but discard the latter. It's extra work but less characters. The `(1 2$,:)` is something J has to do in order to make the tilings in the lists easily extendable. We make the left starting list be a 1-item list of a 2-row matrix of characters, each row having length 0. The right starting list is the same, but has the rows be of length 1, filled with `|`. Then, we add the new tiles to each row, and append the lists of matrices when we're joining the two sets of tilings together. It's a simple application of a concept J calls rank: essentially manipulating the dimensionality of its arguments, and implicitly looping when necessary. ``` 0{::(];'--'&,"1@[,'|',"1])&>/@[&0&((1 2$,:)&.>'';,'|')5 ----| ----| --|-- --|-- --||| --||| |---- |---- |--|| |--|| ||--| ||--| |||-- |||-- ||||| ||||| ``` Try it for yourself at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=0%7B%3A%3A%28%5D%3B%27--%27%26%2C%221%40%5B%2C%27%7C%27%2C%221%5D%29%26%3E%2F%40%5B%260%26%28%281%202%24%2C%3A%29%26.%3E%27%27%3B%2C%27%7C%27%295). [Answer] # Python 3: 70 bytes ``` f=lambda n,s="\n":n>0and f(n-1,"|"+s)==f(n-2,"--"+s)or n or print(s*2) ``` Recursively builds all possible strings `s` representing one row of dominos, which are duplicated and printed. Starting `s` as the newline character makes the blank line happen automatically. The `==` between the two calls for `f` is just to perform both function calls. These usually return `None` because they just print, and `==` is one of few operators defined for `None`. The `and`s and `or`s are to produce the right short-circuiting behavior to reproduce the `if`s and `else`s of the ungolfed code. **Ungolfed:** ``` def f(n,s="\n"): if n==-1:pass elif n==0: print(s*2) else: f(n-1,"|"+s);f(n-2,"--"+s) ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 44 bytes *Note: Retina is younger than this challenge.* ``` +`([-|]*)11(1*#) $1|1$2$1--$2 1 | .*?# $0$0# ``` Takes input in unary with a trailing newline. Each line should go to its own file and `#` should be changed to newline in the file. This is impractical but you can run the code as is as one file with the `-s` flag, keeping the `#` markers (and changing the newline to `#` in the input too). You can change the `#`'s back to newlines in the output for readability if you wish. E.g.: ``` > echo 1111# | retina -s fib_tile | tr # '\n' |||| |||| ||-- ||-- |--| |--| --|| --|| ---- ---- ``` Method: * Starting from the input we swap every line with two other: one with the first `1` change to `|` and one with the first two `1`'s changed to `--`. We do this until we have lines with at least two `1`'s. * When there are only single `1`'s left we changed those to `|`'s. * We double each line and add an extra newline to it and we get the desired output. ]
[Question] [ # BrainFlow ## What is BrainFlow? BrainFlow is an extension of BrainF\*\*k (BFk) with 3 additional commands for added functionality and confusion. ## What commands? In addition to the normal [BFk commands](http://en.wikipedia.org/wiki/Brainfuck), we also have: > > **^** *Jumps to the cell # depending on the value in the cell. > Ex: If we are at cell # 0 with a value of 4, ^ will jump us to cell # 4.* > > > > > **=** *Sets the value at the cell to the index of the cell. Ex: If we are at cell # 4 with a value of 0, = will set our value to 4.* > > > > > **&** *Will set the value at the current cell equal to the value at the cell based on the value in our current cell. (This one's hard to word, so here's an example!) Ex: We are at cell # 33 and our current value at this cell is 7, & will set our current value at cell # 33 to whatever value is in cell # 7.* > > > ## Optional Challenges Accomplishing any of the following will apply the specified bonus to your byte count. `Interpreter written in BrainFlow` *(Can be interpreted by the sample and contains at least one meaningful* **^ =** *or* **&**): **Score / 3** `Interpreter written in BrainF**k:` **Score / 2** `Doesn't contain any English letters (in either upper or lower case):` **Score - 20** `Doesn't contain any of the BrainFlow / BFk commands in the interpreter itself:` **Score - 50** # Example An example Java interpreter: ``` import java.util.Scanner; public class Interpreter { private String exp; private int[] values = new int[256]; private int index = 0; private Scanner in; public Interpreter(String exp, Scanner in){ this.exp = exp; this.in = in; } public void run(){ //Reset index and values for(int i = 0; i < values.length; i++){ values[i] = 0; } this.index = 0; System.out.println("Starting..."); this.process(this.exp, false); System.out.println("\nDone."); } private void process(String str, boolean loop){ boolean running = loop; do{ for(int i = 0; i < str.length(); i++){ switch(str.charAt(i)){ case '>':increaseIndex();break; case '<':decreaseIndex();break; case '+':increaseValue();break; case '-':decreaseValue();break; case '[': String s = str.substring(i); int j = this.getClosingIndex(s); if(this.values[this.index] == 0){ i +=j; break; } process(s.substring(1, j), true); i += j; break; case '.': int v = this.values[this.index]; System.out.print((char)v); break; case ',':this.values[this.index] = this.in.next().charAt(0);break; case '^':this.index = this.values[this.index];break;// Jumps to the index specified in the current cell. case '=':this.values[index] = this.index;break;// Sets the value at cell #x to x case '&':this.values[index] = this.values[this.values[index]];break;// If cell contains X, makes value of current cell equal to value in cell X default: //Ignore others break; } } if(this.values[this.index] == 0){ running = false; } }while(running); } private void increaseIndex(){ if(++this.index >= this.values.length){ this.index = 0; } } private void decreaseIndex(){ if(--this.index < 0){ this.index = this.values.length - 1; } } private void increaseValue(){ int newVal = this.values[this.index] + 1; if(newVal >= this.values.length){ newVal = 0; } this.values[this.index] = newVal; } private void decreaseValue(){ int newVal = this.values[this.index] - 1; if(newVal < 0){ newVal = this.values.length - 1; } this.values[this.index] = newVal; } private int getClosingIndex(String str){ int openings = 0; int closings = 0; for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); if(c == '['){ openings++; }else if(c == ']'){ closings++; } if(openings == closings){ return i; } } return -1; } } ``` Not even close to golfed but should provide a good starting point. Lowest final score wins, where score is number of bytes in your program after the applicable Challenge reductions have been taken into account. # Testing The following BrainFlow program should print the specified output after reading a '+' char from stdin: ``` <<,++++[>++++[>++++<-]<-] Set cell #0 to a value dependent on input >>>+[[-]&>=]+& Set every other cell to that value [ Start loop +^ Add one to current value and jump to that cell index . Print the value at that cell & Copy value from specified cell ] End loop ``` Output: ``` ðñðòñðòðôóòñóñôóðòõóñõðôôóòñööõôöðóöðõðùõñô÷ùõóñöóùñô÷øôøõôòöõóðòöóñ÷ðõôûôòú÷úø÷öùøöùñøðùúðûðþöûñùýøðòñ ``` [Answer] # **Perl - 233 230 210 182 180 176 174 171 bytes** `$/=$,;%d=qw(> $p++ < $p-- + $v[$p]++ - $v[$p]-- , $v[$p]=ord+getc . print+chr+$v[$p] [ while+$v[$p]{ ] } ^ $p=$v[$p] = $v[$p]=$p & $v[$p]=$v[$v[$p]]);eval$d{$_}for<>=~/./g` Simply took an existing BrainFuck interpreter of mine, golfed it, and added the BrainFlow functions. Update: Completely restructured the program to lose 28 bytes. [Answer] Let's get this party started. ## C - 408 384 393 390 380 357 352 bytes (still chipping away) Compile with `gcc` on a POSIX compliant system. The first argument is the name of a file containing the Brainflow code to be interpreted. Newlines added to improve readability. ``` i,p,b[9999],*k=b;unsigned char g[9999],a[30000],*d=a;main(c,v)char**v; {read(open(v[1],0),g,9999);while(c=g[i++]){c-62||d++;c-60||d--;c-43|| (*d)++;c-45||(*d)--;c-46||putchar(*d);c==44?*d=getchar():0;c==94?d=a+*d:0; c==61?*d=d-a:0;c==38?*d=a[*d]:0;c==93?i=*(--k):0;if(c==91)if(*d)*k++=i-1;else while(c=g[i++]){c==91?p++:0;if(c==93)if(p)p--;else break;}}} ``` And the ungolfed version if you're interested. Let me know if you see any bugs. ``` int i, depth, buffer[9999], *stack = buffer; unsigned char c, program[9999], array[30000], *data = array; main(int argc, char **argv) { read(open(argv[1], 0), program, 9999); while(c = program[i++]){ if (c=='>') data++; if (c=='<') data--; if (c=='+') (*data)++; if (c=='-') (*data)--; if (c=='.') putchar(*data); if (c==',') *data=getchar(); if (c=='^') data=array+*data; if (c=='=') *data=data-array; if (c=='&') *data=array[*data]; if (c==']') i=*(--stack); if (c=='[') if (*data) *stack++=i-1; else while (c=program[i++]) { if (c=='[') depth++; if (c==']') if (depth) depth--; else break; } } } ``` Updates: * Thanks for the initial feedback which allowed me to knock an extra 24 bytes off. * Sign bug fixed. Added another 9 bytes. * Saved another 3 bytes per es1024's suggestions. * Saved another 10 bytes per more suggestions from es1024. * Just remembered that global variables are initialized to 0. Switched from fread and fopen to read and open. Saved 23 bytes. * Don't need to set null terminator on program because buffer is already initialized to zero. Saved 5 bytes. [Answer] ## AppleScript 972 670 Mostly golfed although there's no way it will ever win. I don't know why I didn't think about just constructing a script like the perl one did (though it still won't win haha). This could probably be golfed more by readjusting how the index values a bit better, AppleScript is frustratingly (for this type of stuff) a 1 index language. Just pass the BrainFlow code in to e(). Note that AppleScript's ASCII commands use MacOSRoman encoding, so while the output will appear different, it is correct looking at its binary representation. You'll need to take that into account when passing in any upper ASCII characters though on "," commands. ``` on e(x) set d to {"", "set b'sitem(i+1)to(b'sitem(i+1)+1)mod 256", "set b'sitem(i+1)to(b'sitem(i+1)+255)mod 256", "set i to(i+1)mod 256", "set i to(i+255)mod 256", "repeat while b'sitem(i+1)≠0", "end", "set o to o&(ASCII character b'sitem(i+1))", "display dialog \"\"default answer\"\" set b'sitem(i+1)to ASCII number result'stext returned'stext1", "set i to b'sitem(i+1)", "set b'sitem(i+1)to i", "set b'sitem(i+1)to b'sitem(b'sitem(i+1)+1)"} set s to "set i to 0 set b to{} repeat 256 set b'send to 0 end set o to \"\" " repeat with c in x'stext set s to s&d'sitem((offset of c in "+-><[].,^=&")+1)&" " end set s to s&"return o" return run script s end ``` (because what f\*\*\*s with your brain more than writing a brainfuck/flow interpreter in another language that f\*\*\*s with your head way too much? ]
[Question] [ Create a function that takes a natural number (starting from 0 inclusive), and returns a pair of positive integers, which are the numerator and denominator respectively. Use the diagonal traversal. Previous-counted numbers must be skipped. (you can memorize the set of skipped values) Diagram: ![enter image description here](https://i.stack.imgur.com/rRQLw.png) Red are skipped values Values: * f(0) = 1, 1 * f(1) = 2, 1 * f(2) = 1, 2 * f(3) = 1, 3 * f(4) = 3, 1 (notice the skip) * f(5) = 4, 1 * f(6) = 3, 2 * f(7) = 2, 3 * f(8) = 1, 4 * f(9) = 1, 5 * f(10) = 5, 1 (notice the skip) You may use the Rational data structure and their operations if they exist. Shortest code wins. [Answer] ## Haskell, 78 characters ``` q(r,f)=[(r-b,b)|b<-f[1..r-1],r`gcd`b==1] d=reverse:id:d f=((zip[2..]d>>=q)!!) ``` Sample run: ``` > map f [0..10] [(1,1),(2,1),(1,2),(1,3),(3,1),(4,1),(3,2),(2,3),(1,4),(1,5),(5,1)] > f 100 (17,1) > f 1000 (3,55) ``` --- * Edit: (100 → 87) silly me, just testing the gcd is enough! * Edit: (87 → 85) clever trick with `cycle` and functions to alternate row order * Edit: (85 → 82) replace `cycle` with the hand-built infinite list `d` * Edit: (82 → 78) applied `gcd` identity as suggested by Matías [Answer] ## J, ~~41~~ 36 characters Takes an integers and returns a vector comprising two integers. My first solution that is neither entirely tacit nor entirely explicit. ``` {3 :'~.;<`(<@|.)/.(,%+.)"0/~1+i.1+y' ``` Here is the solution with spaces inserted where appropriate: ``` { 3 : '~. ; <`(<@|.)/. (, % +.)"0/~ 1 + i. 1 + y' ``` An explanation: 1. `x (, % +.) y`–a vector of length 2 representing the fraction with numerator `x` and denominator `y` reduced to the smallest denominator 2. `1 + i. 1 + y`–a vector of integers from `1` to `y + 1` 3. `(, % +.)"0/~ 1 + i. 1 + y`–a matrix of all reduced fractions with unreduced denominator and numerator in the range from `1` to `y + 1`. 4. `<`(<@|.)/. y`–an array of the oblique diagonals of matrix `y`, each other diagonal flipped 5. `~. ; y`–an array of diagonals collapsed into a vector of elements with duplicates removed 6. `x { y`–the item at position `x` in `y` 7. `(u v) y`–the same as `y u v y`. In this particular use case, `u` is `{` and `v` is `3 : '~. ; <`(<@|.)/. (, % +.)"0/~ 1 + i. 1 + y'` [Answer] ## Python, 144 chars ``` def F(i): r,d,z=[1],1,[] while z[:i]==z:z+=[(x,y)for x,y in zip(r[::d],r[::-d])if all(x%j+y%j for j in r[1:])];d=-d;r+=[r[-1]+1] return z[i] ``` [Answer] ## Ruby 1.9, 109 106 ``` F=->n{x=y=d=1 e=0 n.times{(x+=d).gcd(y+=e)>1&&redo x<2?d<0?d=0:(d,e=1,-1):y<2?e<0?e=0:(d,e=-1,1):0} [x,y]} ``` [Answer] # OCaml + Batteries, 182 168 characters This is what would be natural in Haskell but is only barely possible in OCaml: ``` open LazyList let rec r(i,j)=lazy(let a,b=if(i+j)mod 2=0then i,j else j,i in Cons((a,b),filter(fun(c,d)->a*d<>c*b)(r(if j=1 then 1,i+1else i+1,j-1)))) let f=nth(r(1,1)) ``` *Edit:* The diagonal is unnecessary [Answer] # [Perl 6](https://perl6.org), 75 bytes ``` {(({|(1…($+=2)…1)}…*)Z/(1,{|(1…(($||=1)+=2)…1)}…*)).unique[$_]} ``` [Test it](https://tio.run/##bY/LToQwFIb3fYqzaOR0YKjlMl4mGN9BV47GjNCJRAZwAJMJkPg0PpgvgqdM3RgXbb70/P36t9aHYjV1jYaPlZ@uGdsf4SytMg3J1CP2A6rvzy/kbhIIAiVG2hfiQaLyfofIhyFR4k9E@F2Zv3d6w5@fxom0t61uWkigyEvd@PttfQ394KfV/gXlY@ZK4d1JcAAd8BfgCAc4SDkyZsrd09U1q4ttCe7soaa76mCdyxtA4HlZd63Hy87jmTarSUFAzwDyZplpXRdHMD/DU1J4gBSWFCSc42ycdnguqKPyQLEdKsPBiQN7HhCHlkPiyHBIGcCyavNUQ/uqoXnLa0HT2Eyjk2Flk8ZwYc3GcGltEfGV5di8PleJ/1X/AA "Perl 6 – Try It Online") This basically generates the entire sequence of rational values, only stopping once the indexed value is generated. (Based on [my golf](https://codegolf.stackexchange.com/a/166970) to another challenge.) ## Expanded: ``` { # bare block lambda with implicit parameter $_ ( ( # sequence of numerators { |( # slip into outer sequence (flatten) 1 # start at one … ( $ # state variable += 2 # increment it by two each time this block is called ) … 1 # finish at one ) } … * # never stop generating values ) Z/ # zip using &infix:« / » (generates Rats) ( # sequence of denominators 1, # start with an extra one { |( # slip into outer sequence (flatten) 1 … ( ( $ ||= 1 ) # state variable that starts with 1 (rather than 0) += 2 # increment it by two each time this is called ) … 1 ) } … * # never stop generating values ) ).unique # get only the unique values .[ $_ ] # index into the sequence } ``` --- `({1…($+=2)…1}…*)` generates the infinite sequence of numerators (`|(…)` is used above to flatten) ``` (1 2 1) (1 2 3 4 3 2 1) (1 2 3 4 5 6 5 4 3 2 1) (1 2 3 4 5 6 7 8 7 6 5 4 3 2 1) (1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1) … ``` `(1,{1…(($||=1)+=2)…1}…*)` generates the infinite sequence of denominators ``` 1 (1 2 3 2 1) (1 2 3 4 5 4 3 2 1) (1 2 3 4 5 6 7 6 5 4 3 2 1) (1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1) (1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1) … ``` ]
[Question] [ Given an \$m \times n\$ matrix of integers A, there exist a \$m \times m\$ matrix P, an \$m \times n\$ matrix D, and an \$n \times n\$ matrix Q such that: * \$A = P D Q\$. * P and Q are unimodular matrices (i.e. matrices which are invertible and whose inverses are also integer matrices); * D is diagonal; * each diagonal entry \$d\_{ii}\$ of D is nonnegative; and * \$d\_{11} \mid d\_{22} \mid \cdots \mid d\_{nn} \$. Furthermore, the matrix D is unique in this representation. Depending on context, the Smith normal form of A is either just the diagonal matrix D, or a Smith normal form decomposition of A is the tuple \$(P, D, Q)\$. For this challenge, you only need to calculate D. One common way to calculate D is via an algorithm that looks like a combination of the Euclidean algorithm for calculating gcd and Gaussian elimination -- applying elementary row and column operations until the matrix is in the desired format for D. Another way to calculate D is to use the fact that for each i, \$d\_{11} d\_{22} \cdots d\_{ii}\$ is equal to the gcd of all determinants of \$i\times i\$ submatrices (including non-contiguous submatrices) of A. ## The challenge You are to write a function or program that calculates the Smith normal form of an input matrix. The output may either be in the form of the full matrix D, or in the form of a list of the diagonal entries of D. In an imperative programming language, it is also acceptable to write a function that takes a matrix by reference and mutates the matrix into its Smith normal form. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest code wins. * Standard loophole prohibitions apply. * You do not need to worry about integer overflow, if that applies in your language. ## Examples ``` 1 2 3 1 0 0 4 5 6 -> 0 3 0 7 8 9 0 0 0 6 10 1 0 10 15 -> 0 10 6 0 0 1 0 0 0 10 0 -> 0 30 0 0 0 15 0 0 30 2 2 2 0 2 -2 -> 0 4 2 2 4 6 2 0 0 0 2 -2 0 -2 -> 0 4 0 0 3 3 3 1 0 0 4 4 4 -> 0 0 0 5 5 5 0 0 0 ``` Note: Mathematica already has a built-in to calculate Smith normal form. As such, you can use this to play around with test cases: [Try it online!](https://tio.run/##y00syUjNTSzJTE78/786QMfFQCew1jY4N7MkwyU1OT@3IL84syQzPy@6mktBoVrBUMdIx1ihVgfMMdEx1TGDccx1LHQsFWq5amOtuQKKMvNKol0MYq3//wcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), no SNF builtin, 56 bytes -35 from att ``` (i=0;(!i+1)/1~Max~!i++&/.!a_:>GCD@@Join@@#~Minors~a)/@#& ``` [Try it online!](https://tio.run/##LY3dCoIwAIVfJRFE8djc/MkKY1AQBEL3ETEiaRcqmBfBmK@@Znp1Dt/54DRieL8aMcinMHVpfFnGe9@RIQ0IHSvxHW0PPbJ2xGN3OB9PnF862XLujpVsu/4zioBw1zPXXrbDrSZcKUXBkGioFBlymxsU2GqNlVLMTukfMkQMMdjMC1DLoslfvBTpRHLkoMw2GltElzlBsjzMWmafMq313fwA "Wolfram Language (Mathematica) – Try It Online") From [Wikipedia](https://en.wikipedia.org/wiki/Smith_normal_form#Definition): > > The invariant factors \$\alpha\_i\$ can be computed as > $$\alpha\_i = \frac{d\_i(A)}{d\_{i-1}(A)}$$ > where \$d\_i(A)\$ equals the greatest common divisor of the determinants of all \$i\times i\$ minors of the matrix *A* and \$d\_0(A)=1\$. > > > [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 20 bytes -25 bytes thanks to [@Daniel Schepler](https://codegolf.stackexchange.com/users/73487/daniel-schepler) and [@Parcly Taxel](https://codegolf.stackexchange.com/users/110698/parcly-taxel). ``` m->Vecrev(matsnf(m)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWW3J17cJSk4tSyzRyE0uK89I0cjU1IVI3axMLCnIqNXIVdO0UCooy80qATCUQR0kBrExHITraUMdIx9jaRMdUx8zaXMdCxzIWKGqmY2hgbWigY2gK4RnoGFgDeRAKJmykY2RtpKNrBGXrmABNAPGBCoCCsVBHLFgAoQE) [Related](https://codegolf.stackexchange.com/questions/175090/repeat-this-gcd-operation/175095#175095). [Answer] # C++ with the [Eigen3 library](https://eigen.tuxfamily.org/index.php?title=Main_Page), 470 bytes Since we were not getting submissions using the Gaussian elimination style solution, I thought I would take a crack at implementing and golfing a solution myself. (I won't count a self-answer as a competitor, but if somebody wants to pick this up and run with it, that would be fine with me.) ``` #include<Eigen/Core> #define r M.row #define c M.col #define G goto R; void f(auto&M){int m=M.rows(),n=M.cols(),i,j,k,P,v;for(k=0;k<m&&k<n;++k){R:if(M(k,k)<0)r(k)*=-1;P=M(k,k);for(i=k;i<m;++i)for(j=k;j<n;++j){v=abs(M(i,j));if((v<P||!P)&&v){r(k).swap(r(i));c(k).swap(c(j));G}}if(P){for(i=k+1;i<m;++i){r(i)-=M(i,k)/P*r(k);if(M(i,k))G}for(j=k+1;j<n;++j){c(j)-=M(k,j)/P*c(k);if(M(k,j))G}for(i=k+1;i<m;++i)for(j=k+1;j<n;++j){if(M(i,j)%P){r(i)+=r(k);c(j)-=M(i,j)/P*c(k);G}}}}} ``` For some test code, append this: ``` #include <iostream> void test(Eigen::MatrixXi M) { std::cout << "Input:\n" << M; f(M); std::cout << "\nOutput:\n" << M << "\n\n"; } int main() { Eigen::MatrixXi M(3,3); M<<1,2,3,4,5,6,7,8,9; test(M); Eigen::MatrixXi M2(2,2); M2<<6,10,10,15; test(M2); Eigen::MatrixXi M3(3,3); M3<<6,0,0,0,10,0,0,0,15; test(M3); Eigen::MatrixXi M4(2,2); M4<<2,2,2,-2; test(M4); Eigen::MatrixXi M5(2,4); M5<<2,2,4,6,2,-2,0,-2; test(M5); Eigen::MatrixXi M6(3,3); M6<<3,3,3,4,4,4,5,5,5; test(M6); return 0; } ``` [Answer] # [R](https://www.r-project.org), ~~165~~ ~~163~~ 159 bytes ``` \(m,x,y,R=Reduce,C=combn)R(\(l,k)R(`?`<-\(x,y,z=y%%x)`if`(x&z,z?x,x)+y*!x,sort(abs(C(x,k,\(i)C(y,k,\(j)round(det(t(m[i,j]))))))))/max(1,l),1:min(x,y),1,,T)[-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9daoNAFIXfu4s-pNzbXmk0GtpQyYM7EN9iQONPmSSjYEYY3UofagvdS7fQ3XRmlJC0cwbOhfkO98zbRzN8lv5XK0rr6ec9Bk6SOgr9sMjbrKDAz2q-qzCEGI50UJ6skxcrBk31fjebSUxYmYC866lfS5L40N3fSjrVjYB0d4JAoQeKgWEAnZn22NRtlUNeCBDAN4z2W5zOI08l2HREslecVXqNGoki3Fj2dqr5XQJPRcMUuXqmhVKE2vDm_JDBkuy5uR6SoxQZ00jO0tcz4OH_qGMClvM3eAW4tDQQzSfSHUn3ilyYeq6Rp4WXfcf_DMPovw) -2 bytes thanks to pajonk and further -4 thanks to Giuseppe. Takes input as matrix `m` and its dimensions `x,y`, outputs SNF diagonal. ### Explanation Uses the same algorithm as [Parcly Taxel's answer](https://codegolf.stackexchange.com/a/260852/78274). For each `k` in `1:min(x,y)` compute the minors: `combn(x,k,\(i)...)` generate all combinations `i` of `k` row indices `combn(y,k,\(j)...)` generate all combinations `j` of `k` column indices `round(det(m[i,j]))` calculate the determinants of submatrices and round, as otherwise floating point inaccuracies lead to problems in GCD `sort(abs(...)` discard the signs and sort in order expected by GCD `Reduce('?'<-..., ...)` Reduce by GCD. Overall, a lot of bytes are wasted due to no built-in GCD in R... `Reduce(\(l,k)) .../max(1,l), init=1, accumulate=T)` Divide each term by the previous one, unless it's zero `..[-1]` Drop the initializer `1` and return. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~237~~ ~~229~~ ~~227~~ 225 bytes. *Saved 10 bytes thanks to the comment of @ceilingcat* --- Use the formula in [Wikipedia](https://en.wikipedia.org/wiki/Smith_normal_form#Definition). > > The invariant factors \$\alpha\_i\$ can be computed as > $$\alpha\_i = \frac{d\_i(A)}{d\_{i-1}(A)} $$ > where \$d\_i(A)\$ equals the greatest common divisor of the determinants of all \$i\times i\$ minors of the matrix *A* and \$d\_0(A)=1\$. > > \$ \text{Note that here } d\_i(A)\geq 1 \$ > > > --- Golfed version. [Try it online!](https://tio.run/##ZY/fToMwFMbveYpzt1bPIjCZf05q3BN45dVCTFeK6YQyChiyZb767MCJiW2anv6@r/16KtXKT31ShZYOZFGQKqpG/1SKTnlnVWsqC1Ls2YqvS7SpaMxeMylWVyGnTESUVw6MiB5LY5k3cKrFOh2oE6oqN/aDeRENnw1QTdAO0NtrynTLVsyh4jwlbbNhne1b/7LtSl2wmlMv5KZhrupsxmq25ZyTE4ce3lXm7/b8eGDbp4hfR8fhvskh@xIhSWZ8knA347OZcJeIqcOqa0FAKXdvZ8RK2TqjdMODUVC6KLzAnkel57C/VAgXM8Ls1Rr/6/Kla3ddO0PIZdFoToHPCoKLTxwC8GMdYYwLusUEl3SH9/iQ4igsMQoJohCjZEIhhuTJuP2VYowpxnn8e4YY4BaWQDHMYwhhkha4GBL9pMTnJunAjxRkptmx/@1zOn0D) ``` function a=z(A)[m,n]=size(a=A*0);d=1;for i=1:min(m,n);q=[];for r=combnk(1:m,i)';for c=combnk(1:n,i)';q=[q;det(A(r,c))];end;end;for j=1:numel(q);x=abs(round(q(j)));r={x gcd(r,x)}{(j>1)+1};end;if d~=0;a(i,i)=r/d;end;d=r;end;end ``` Ungolfed version. [Try it online!](https://tio.run/##fVTdb9MwEH/vX3EvqI7wRJOtA2oFUSGBeOKJp6mqPMddrSVOsR3WjcG/Xu6cr3ZFuKp8ud99/u6SWgX5Ux8OE1Vq6UCWpVBl7XUnKTGZbBqrgqktFDp4yKEytnZrfGBLDiaZAJ5X8Gmr1T2YDSzBeJDgfzTSaahkcGYPtQNbh2h6U3GwK4zjzZNmy0REbRfl6wYM@d85LYN2ELbSgrSPUJhKW09V1JiCg9OhcQSBdq520d2Q8weo4Pk5CjZq6UQbNjWgpMU64FafZghbPWbwMcW0K0zb4rjALzoQNaDq6tZYGXp7A65@wL5tgVDZVNZHh6jMo7W9Z@miIsbawGh2AtkR6smwJhhZIk2xQOmcfKRcSL12OAVpQ5ulG8zN6sT9M5Kupdoe10ruLwvlZLBrQpvlKHiMs8EoDoOnizgvcuaQJgO1hKsRp65OcDpxY9BmGd2Z44uEx/6ZQrFruj9YwLp3oCWL8rlNbJhuMXqsRqt@bHTT/2iNpfUPmqKTBhdwUuTEHDUCJscZGcu63WzbGBZ@YP3FW9DPzWlCXN3Ygslbz84dWZr0/VI@Ywu9R5dsYZtKl/9wGIlsg9@pgqHE/58lxk2GVD0ZBUPpdZrkGEFEWrD1lBfYfUtK/qRd7YfuW1KIE3ZMStK/bQUzyZ98NpTYBmEGCckRw0xvyEScTCJOYxhG3QQiU@7WcRrxc6E0tt0CSpclAuxji@wTGM32uES9PYfpd2uw2upbE3CXpxw2svQ6Ed306fTG@a/2Q5TyjF@KKz7n1@Itf8ffr3gLXPN0JiCd8XQ@qmZ8JlDTXsdQxjOR8YtseIYM4AquQWRwkcEMRuiSX8aM@BNzzDtfRf1vMSmM37FzGhJxOPwF) ``` clear all;close all;clc; function dets = minor_det(A, i) % Check if A is a square matrix or not [m, n] = size(A); % If i is greater than any dimension of A, return an error if i > m || i > n error('i cannot be greater than the dimensions of A'); end % Get all combinations of i rows and columns rows = combnk(1:m, i); cols = combnk(1:n, i); % Initialize the array of determinants dets = []; % For each combination of rows and columns, compute the determinant for r = 1:size(rows, 1) for c = 1:size(cols, 1) minor = A(rows(r,:), cols(c,:)); det_minor = det(minor); dets = [dets; det_minor]; end end end function answer = func(A) d=[]; for i=1:min(size(A)) minor_determinants = minor_det(A,i); res = round(abs(minor_determinants(1))); for index = 2:numel(minor_determinants) res = gcd(res, round(abs(minor_determinants(index)))); end d(end+1)=res; end d=[1,d]; answer=zeros(size(A)); for i=1:(min(size(A))) if d(i)~=0 answer(i,i)=d(i+1)/d(i); end end end function out = map_func(matrices) out = cellfun(@(matrix) func(matrix), matrices, 'UniformOutput', false); end matrices={ [1,2,3;4,5,6;7,8,9], [6,10; 10,15], [6,0,0;0,10,0;0,0,15], [2,2;2,-2], [2 2 4 6 ;2 -2 0 -2], [3,3,3;4,4,4;5,5,5] }; disp(map_func(matrices)); ``` [Answer] # [SageMath](https://www.sagemath.org/), ~~26~~ 24 bytes ``` lambda m:m.smith_form(0) ``` [SageMath matrix](https://doc.sagemath.org/html/en/reference/matrices/sage/matrix/constructor.html) as I/O. [Try it online.](https://sagecell.sagemath.org/?z=eJx9zkEKwjAQBdB9IHcIXTXwlSTWqgUP4MoDxCAVKQacWmoKHt-0YrEgnc3MfB7DVPsTZ_eSLtdSUEHLJ_lwO1ePllIlOeMsjoKEr4WlMrT-lVqrYbBysBnWyGPfYIudcxKcibFGnUOriLSCXs8ghV5F9B1mvYGJyGBh5giy4b-exXODdcUHN62vQ5oc6qYLhUjkb0qTLTl24Q-qIpsE8g17k1Ju&lang=sage&interacts=eJyLjgUAARUAuQ==) **Explanation:** Should speak for itself, but I'll add it anyway. ``` lambda m: # Lambda function with matrix as argument: m.smith_form( ) # Get the Smith Normal Form of the given matrix, 0 # but only return its diagonal matrix D ``` [`smith_form()`](https://doc.sagemath.org/html/en/reference/matrices/sage/matrix/matrix_integer_sparse.html#sage.matrix.matrix_integer_sparse.Matrix_integer_sparse.smith_form) will output a tuple of three matrices \$(D,P,Q)\$ by default. But by overriding its first argument with `False`, it'll result in just its diagonal matrix \$D\$, hence the need for the `0`-argument. ]
[Question] [ As the title may suggest, this problem is semi-inspired by the [Polite Near-Sighted Drunk Bot](https://codegolf.stackexchange.com/questions/170229/gold-collector-koth) by @N.P. Our poor bot is placed on a cartesian grid at the origin, and after each minute, it moves 1 unit in one of four directions (Up, Down, Left, Right). After *n* minutes, all of the latent mines on the grid activate, killing any poor bot that might find themselves over them. The mines are located at all integer coordinates satisfying the equation |y|=|x|. # Challenge You will be provided *n*, the number of minutes before the mines blast, as an input, and as an output, you must find the probability that the bot is **dead**. **Input**: An natural number representing *n*. **Output**: Let the probability the bot is **dead** be p/q, where p and q are relatively prime whole numbers (q can't be 0, but p can). Output p. # Rules * Your algorithm **must not** run in exponential or higher time. It ideally should run in polynomial time or less. * Your algorithm must be able to handle inputs of `n`<20 (can be adjusted if too hard) in a reasonable time. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. * Iterating over all possibilities for a given *n* will most definitely not be accepted as an answer. # Test Cases `1`->`0` `2`->`3` `4`->`39` `6`->`135` `8`->`7735` `10`->`28287` # Example Calculation for *n*=6 We have 4 possible moves: U, D, R, and L. The total number of paths that could be taken is 4^6, or 4096. There are 4 possible cases that land along the line y = x: x,y = ±1; x,y = ±2; x,y = ±3; or x = y = 0. We will count the number of ways to end up at (1,1), (2,2), and (3,3), multiply them by 4 to account for the other quadrants, and add this to the number of ways to end up at (0,0). **Case 1:** The bot ends at (3, 3). In order for the bot to end up here, it must have had 3 right moves, and 3 up moves. In other words, the total number of ways to get here is the ways to rearrange the letters in the sequence RRRUUU, which is 6 choose 3 = 20. **Case 2:** The bot ends at (2,2). In order for the bot to end up here, it could have had 2 up moves, 3 right moves, and 1 left move; or 2 right moves, 3 up moves, and 1 down move. Thus, the total number of ways to get here is sum of the ways to rearrange the letters in the sequences RRRLUU and UUUDRR, both of which are (6 choose 1) \* (5 choose 2) = 60, for a total of 120 possibilities. **Case 3:** The bot ends at (1,1). In order for the bot to end up here, it could have had: 1 right move, 3 up moves, and 2 down moves. In this case, the number of ways to rearrange the letters in the sequence RUUUDD is (6 choose 1)\*(5 choose 2) = 60. 1 up move, 3 right moves, and 2 left moves. In this case, the number of ways to rearrange the letters in the sequence URRRLL is (6 choose 1)\*(5 choose 2) = 60. 2 right moves, 1 left move, 2 up moves, and 1 down move. In this case, the number of ways to rearrange the letters in the sequence UUDRRL is (6 choose 1)\* (5 choose 1)\*(4 choose 2) = 180. Thus, the total number of ways to end up at (1,1) is 300. **Case 4:** The bot ends at (0,0). In order for the bot to end up here, it could have had: 3 right moves and 3 left moves. In this case, the number of ways to rearrange the letters in the sequence RRRLLL is (6 choose 3) = 20. 3 up moves and 3 down moves. In this case, the number of ways to rearrange the letters in the sequence UUUDDD is (6 choose 3) = 20. 1 right move, 1 left move, 2 up moves, and 2 down moves. In this case, the number of ways to rearrange the letters in the sequence RLUUDD is (6 choose 1)\* (5 choose 1)\*(4 choose 2) = 180. 1 up move, 1 down move, 2 right moves, and 2 left moves. In this case, the number of ways to rearrange the letters in the sequence RRLLUD is (6 choose 1)\* (5 choose 1)\*(4 choose 2) = 180. Thus, the total number of ways to end up at (0,0) is 400. Adding these cases together, we get that the total number of ways to end up on |y| = |x| is 4(20 + 120 + 300) + 400 = 2160. Thus, our probability is 2160/4096. When this fraction is fully reduced, it is 135/256, so our answer is **135**. [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` def p(n):b=2**n;r=b*b-((~b)**n/b**(n/2)%-b)**2;print~n%2*r/(r&-r) ``` [Try it online!](https://tio.run/##HcwxDoMwDEbhuT2FFyrbIorwSMRhahValp/IYunC1UPp@ElPr373zwZr7TUvVBky@mSqKDG5emI@XH7MrsrIJl26bKXGiv1AZxqZ45FC2rIFgVZQPPGeeejJBhnvt39K6Mu1byc "Python 2 – Try It Online") The probability the bot is dead can be expressed as: > > $$ f(n) = 2s-s^2\text{, where } s=\frac{1}{2^n}\binom{n}{n/2}$$ > > > and the binomial is understood to equal \$0\$ when \$n/2\$ isn't whole. We can reason like this. What's the probability that the bot lands on the \$y=x\$ line? This happens if the total number of up and left moves equals the total number of down and right moves. This is the same probability that, say, you flip a coin \$n\$ times and get as many tails as heads. You must choose \$n/2\$ flips to be heads of \$n\$ flips, which can be done in \$\binom{n}{n/2}\$ ways, of \$2^n\$ possible sequences overall, giving probability $$s=\frac{1}{2^n}\binom{n}{n/2}$$ The probability of landing the \$y=-x\$ line is also \$s\$. So, the probability of landing on either line is the sum of these or \$2s\$, except we're double-counting the probability of landing of \$x=y=0\$ in both lines, and must subtract it to compensate. It turns out the probability of landing on \$x=y=0\$ is just \$s^2\$, the product of the probability of landing on each line. We can argue the events are independent as follows: if we pick a random sequence of equal numbers of "Up or Left" and "Down or Right" to land on \$x=y\$ and likewise with "Up or Right" and "Down or Left" for \$x=-y\$, we can uniquely combine them into a sequence of Up, Down, Left, Right by taking the intersection of the pairs of directions at each position. So, the probability of landing on \$x=y\$ or \$x=-y\$ is \$2s-s^2\$. The code computes the binomial \$\binom{n}{n/2}\$ using [this expression](https://codegolf.stackexchange.com/a/169115/20260) as `(b+1)**n/b**(n/2)%b` with base `b=2**n`. To extract the numerator from the probability fraction, we note that the denominator is a power of 2, so we use the expression `r/(r&-r)` to divide out the maximal power of 2 is `r`, expressed as the classic bit trick `r&-r`. The solution is golfed by writing \$2s-s^2\$ as \$1-(1-s)^2\$ so that \$s\$ is only referenced once, and working without the \$1/2^n\$ fractions to stay within the integers. The computation is polynomial-time in \$n\$ even with the funky way of computing binomials. --- After writing the proof of the probability the bot dies, I found a possibly cleaner way to prove it and present it. Let's keep track of the values of \$a=x+y\$ and \$b=x-y\$ after each move of the bot. Each of the four directions up, down, left, and right either increments or decrements each of \$a\$ and \$b\$, with the four directions corresponding to the four combinations. So, a random move is equivalent to randomly adding \$\pm 1\$ to \$a\$ and independently \$\pm 1\$ to \$b\$. This is equivalent to doing separate random walks on \$a\$ and \$b\$. Now, the robot ends on the line \$x=y\$ or \$x=-y\$ exactly when \$a=0\$ or \$b=0\$. So, the probability of ending with \$a=0\$ is \$s=\frac{1}{2^n}\binom{n}{n/2}\$ and likewise for \$b=0\$. Since the walks are independent, the probability that \$a\neq 0\$ and \$b\neq 0\$ is \$(1-s)^2\$, so the probability that at least one is zero is the complement \$1-(1-s)^2\$. ]
[Question] [ We all know what a [quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine?) is. An *inverted* quine is a non-empty program that prints the inverse of its source code without reading its source code, and consists solely of printable-ASCII characters (space through `~`). Here, “inverse of the source code” means the following: the output of your program must contain each printable ASCII character **(m − c)** times, where **c** is the number of times said character occurs in your code, and **m** is the maximum number of times any character is repeated in your code. (In other words: **your code** + **your output** = permutation of **m** times all of printable-ASCII.) For example, if your program is `12345`, then **m = 1**, and you should output any permutation of this string: ``` !"#$%&'()*+,-./06789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` If your program is `AAB`, then **m = 2**, and you should output any permutation of: ``` !!""##$$%%&&''(())**++,,--..//00112233445566778899::;;<<==>>??@@BCCDDEEFFGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ[[\\]]^^__``aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~ ``` Note how there are two missing `A`s, and one missing `B`. Although a program that contains all the printable ASCII characters and outputs nothing is a valid inverse quine (satisfying **m = 1**), such an answer would not be very competitive, given its length. You are to write a program that is an inverted quine, as described in the above paragraph. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program in bytes will win. Good luck! [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~221~~ 207 bytes Includes +1 for `-A` ``` (((((((()()()()){}){}()){}){})()){}{}){({}[()]<((((((()()()()){}){}){})<>[()()()])[()])((((()()()){})){}{})<>((()()()()){}){({}[()]<(({})())>)}{}({}()())<>{{({}<>[()]<(({})())><>)}{}<>(({}())()())<>}<>>)}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMKNCFQs7oWiGA0RADE1KiujdbQjLXBphqEbOyiIUKxmiB1mghVIFmIITZ2aDoRhkKsstMEKtMAWQ/k2NhVgxSADUZSYgNWBDIK7EyoUqAAWPz///@6jgA "Brain-Flak – Try It Online") ``` # Push 206 (the number of times to duplicate the output) (((((((()()()()){}){}()){}){})()){}{}) # For 0 to 206 {({}[()]< # Push 32 on this stack and 18, 28 and 29 to the other # 18, 28 and 29 are the distances between the sets of braces ((((((()()()()){}){}){})<>[()()()])[()])((((()()()){})){}{})<> # For 0 to 8 ((()()()()){}){({}[()]< # Push TOS, TOS + 1 (({})()) # end For 0 to 8 >)}{} # Push TOS + 2 # skips '(' and ')' ({}()()) # For each value on the off stack (18, 28, 28) <>{ # For 0 to that number {({}<>[()]< # Push TOS, TOS + 1 (({})()) # End for 0 to that number ><>)}{} # Push TOS + 1, TOS + 3 (skips this set of braces) <>(({}())()())<> # End for each value on the off stack (18, 28, 28) }<> # End for 0 to 206 >)}{} ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 17 bytes ``` {s95c+'|,32>\-}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v7rY0jRZW71Gx9jILka3Nr7u/38A "CJam – Try It Online") Prints ``` !"#$%&()*./014678:;<=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^`abdefghijklmnopqrtuvwxyz ``` ### Explanation The goal was to modify the standard quine ``` {"_~"}_~ ``` such that no character is repeated in the program. The reason for this is that CJam has a set different operator which we can use to remove characters from the printable ASCII range, but it doesn't take number of occurrences into account. Implementing that by hand would probably be longer, so I needed to make sure that every character appears only once and we don't have to worry about occurrences. ``` { e# Quine framework. Executes the block while leaving another copy of the e# block on the stack. s e# Stringify the block, giving us "{s95c+'|,32>\-}". 95c e# Convert 95 to a character, which gives us '_' without repeating e# it in the source code. + e# Append it to the string. We don't need to worry about '~', we'll just e# leave it out of the printable ASCII range to begin with. '|, e# Get a character range from the null byte up to '{'. This omits "|}~", e# but those are in the program anyway, it doesn't matter. 32> e# Discard the unprintable characters. \- e# Subtract the source string from the printable ASCII range. }_~ ``` [Answer] # [Python 3](https://docs.python.org/3/), 83 bytes ``` print(~2/8,6>9)#!"$%&'*+14:;<=?@ABCDEGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdfghjkmoquvwxyz{|} ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo85I30LHzM5SU1lRSUVVTV1L29DEytrG1t7B0cnZxdXdw9PL28fXzz8gMCg4JDQsPCIyKjomNi4@ISk5JS09Iys7N7@wtKy8orKquqb2/38A "Python 3 – Try It Online") Prints `-0.375 False`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~95~~ ~~61~~ 60 bytes (not 58 b/c I dislike that one) ``` A?9L<J, !"'#$%&()*+-./:;=>@BCDEFGHIKMNOPQRSTUVWXYZ[\]^_`{|}~ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0d7Sx8ZLR0FRSV1ZRVVNQ1NLW1dP38ra1s7BydnF1c3dw9Pb188/IDAoOCQ0LDwiMio6JjYuPqG6prbu/38A "05AB1E – Try It Online") Old answer invalidated by "only-ASCII characters", [a lot of commands aren't valid here.](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt) It prints `abcdefghijklmnopqrstuvwxyz012345678` one time as there are no duplicated characters. --- # Version with `BCDEFGHIKMNOPQRSTUVWXYZ` removed: *Work in progress... I think ~60 bytes is as low as you get without non-ASCII characters in 05AB1E..* # [05AB1E](https://github.com/Adriandmen/05AB1E), 58 bytes ``` T5+FA'uK?Au"ADLJFKST"SK?9L<5KJ?} !#$%&()*>-./:;=@[]^_`{|~\ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/xFTbzVG91NvesVTJ0cXHy807OEQp2Nve0sfG1NvLvlZBUVlFVU1DU8tOV0/fytrWITo2Lj6huqYu5v9/AA "05AB1E – Try It Online") Prints the output x12 due to the repeated characters: ``` ['""', '55', '???', 'AAA', 'FF', 'JJ', 'KKKK', 'LL', 'SS', 'TT', 'uu'] ``` It also doesn't terminate quite correctly, working on that now... --- Invalid old answers (due to non-ASCII characters) have been removed, see edit history. [Answer] # Java 8, ~~106~~ ~~99~~ 190 bytes ``` class i {/*{}!"#$%&'()+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bdefghjkmnopqrtuvwxyz|~!"#$%&'()+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`claibdefghjkmnopqrtuvwxyz|~*/} ``` [Answer] # Javascript (ES6), ~~103~~ 101 bytes ``` _=>` !"#$%&'()*+,-.0123456789:;<?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^abcdefghijklmnopqrstuvwxyz{|}~`//_=>\\ ``` **Old solution (103 bytes using `alert`)** ``` alert;;alert`\ \!"#$%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_bcdfghijkmnopqsuvwxyz{|}~` ``` **Old (invalid) solution (96 bytes)** ``` alert()// !"#$%&'*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdfghijkmnopqsuvwxyz{|}~ ``` ]
[Question] [ Write a quine, that when run, creates itself in the current directory, in a source file named itself. We will be using Windows in this, so the file name (and therefore quine) must have the following limitations: * None of these characters `\ / : ? * < > |` * Fewer than 211 255 characters ### Limitations and assumptions * Your code must be a full program (It's going to be run after all). * No copying from the source file. * You can assume that there isn't another file with your Quine as its name (as it would produce *Quine* (1)). * Errors are allowed (as long as they don't get into the source code This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! ### Edit Maybe I wasn't clear, the file with the name of the quine has to actually contain the quine. My bad. [Answer] # Node.js, ~~56~~ 52 bytes ``` function f(){require('fs').writeFile(f+='f()',f)}f() ``` This prints the warning > > DeprecationWarning: Calling an asynchronous function without callback is deprecated. > > > If you want the all-green, it costs 4 bytes to change `writeFile` to `writeFileSync`. [Answer] # Vitsy, ~~10~~ 27 bytes ``` 'rddd++&"rdd8++a[v}v1-D);]. ``` If `:` was allowed, I could shorten this to 11 bytes. :( Explanation: ``` 'rddd++&"rdd8++a[v}v1-D);]. ' Capture all instructions as a string until encountering ' again, looping if necessary. r Reverse the current stack (output is top-down). ddd++ Push char literal ' to the stack. & Push a new stack to the stack stack. " Same as ', but " specific. r Reverse the current stack. dd8++ Push char literal " to the stack. a Push 10 to the stack. [ ] Loop forever. v Capture the top value as a variable. } Take the bottom item of the stack and put it on the top. v Dump the variable to the stack. 1- Subtract 1. D Duplicate the top item. ); Pop n; if n is 0, exit the loop. a[v v1-D);] This is a makeshift for loop with 10 iterations. . Pop the top stack as n, and the second stack as o. Write a file called "n" with the contents of "o". ``` The two stacks will be identical at the end. On some Java versions, this may throw a `FileNotFoundException` due to different implementations of the `FileInputStream` class. ### Previous answer before edit: ``` &'rddd++}. ``` Explanation: ``` & Push a new stack to the stack stack. 'rddd++ Modified standard quine. } Move the ' to the right place. . Pop the top stack as n, and the second stack as o. Write a file called "n" with the contents of "o". (Quine name, no content) ``` Because I might as well, here's a diagram of the steps that occur within the stacks (each stack is represented by `[]`): ``` Initial state: [[]] & [[], []] Push a new stack to the stack stack. ' [[], ["r", "d", "d", "d", "+", "+", "}", ".", "&"]] This stack state occurs because ' will loop around the line until finding the next '. r [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r"]] Reverses the top (last) stack. ddd [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", 13, 13, 13] Push thirteen thrice. ++ [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", "'"] Because char ' is 39 = 13 + 13 + 13. } [[], [".", "}", "+", "+", "d", "d", "d", "r", "'", "&"]] Takes the bottom item, then puts it on the top. . [] Writes a file with content from the second-to-top stack and the name as the concatenation of all elements in the top stack, with top member priority (backwards from my representation). ``` I'm actually not sure how this works right; minute changes cause this to break. For example, placing the `&` in various other locations should work just as well, but it causes `ClassCastException`s, `IOException`s, and `ArrayOutOfBoundsException`s depending on where you put it. I might need to do some bugfixing. [Answer] # Lua, 96 bytes. ``` s="s=%qs=string.format(s,s)f=io.open(s)f.write(f,s)"s=string.format(s,s)f=io.open(s)f.write(f,s) ``` Typed this on my phone, should work, but I'll test it when I get to a computer. [Answer] # C, 134 bytes ``` s[255];fd;char p[255]="s[255];fd;char p[255]=%c%s%c;main(){sprintf(s,p,34,p,34);creat(s,0);}";main(){sprintf(s,p,34,p,34);creat(s,0);} ``` [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` a="s='a=%r;exec(a)'%a;open(s,'w').write(s)";exec(a) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9FWqdhWPdFWtcg6tSI1WSNRU1010Tq/IDVPo1hHvVxdU6@8KLMkVaNYUwmm4P9/AA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), ~~87 79 71~~ 62 bytes Since windows is not allowing double quote `"` anymore ([more infos](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions)), I made an other solution verifying the new convention: ``` w='w=%r;open(w%%w,w[0]).write(w%%w)';open(w%w,w[0]).write(w%w) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v9xWvdxWtcg6vyA1T6NcVbVcpzzaIFZTr7wosyQVLKCpDpNElyvX/P8fAA "Python 3 – Try It Online") ]
[Question] [ ## Credit My thanks to [Rand Al'Thor's letter-based question](https://puzzling.stackexchange.com/questions/42709/a-triangle-formed-of-three-letters) for the inspiration for this code-golf challenge. ## Background The nature of this challenge is based off the algorithm mentioned by Rand in his "A Triangle Formed of Three Letters": > > * Start with a sequence of 10 letters each of which is X, Y, or Z. > * Under each row, construct the next row as follows. If two adjacent letters are the same, write the same letter beneath them; if they're different, write the third letter beneath them. > > > You would then repeat the previous step until you have one letter in your tenth row. ## Challenge We're going to put a mathematical spin on the above algorithm: * Let's start with a sequences of 10 digits, each separated by a space, and each of which is either 1, 2 or 3. * Under each row, construct the next row as follows. If two adjacent digits are the same, write the same digit beneath them; if they're different, write the third digit beneath them. * Repeat the previous step until you have one final number. So, following this algorithm, if starting with the row `1 2 3 3 1 3 1 3 1 2`, for example, the following triangle is generated: ``` Input: 1 2 3 3 1 3 1 3 1 2 Output: 1 2 3 3 1 3 1 3 1 2 3 1 3 2 2 2 2 2 3 2 2 1 2 2 2 2 1 2 3 3 2 2 2 3 1 3 1 2 2 1 2 2 3 2 3 2 1 1 1 3 1 1 2 1 3 ``` I'm also curious to know the sum of all the digits in the number triangle, so add all these digits, and put this total in an eleventh row, right-justified to the last digit in the first row. So, our number triangle will look something like the following (spaces in my example are represented below by the `.` character to show formatting.) ``` Input: 1 2 3 3 1 3 1 3 1 2 Output: 1.2.3.3.1.3.1.3.1.2 .3.1.3.2.2.2.2.2.3. ..2.2.1.2.2.2.2.1.. ...2.3.3.2.2.2.3... ....1.3.1.2.2.1.... .....2.2.3.2.3..... ......2.1.1.1...... .......3.1.1....... ........2.1........ .........3......... ................109 ``` Your challenge is to write code that can start with an inputted string/array/etc. of ten digits, as per my example, and then apply the algorithm to generate the ten rows that would create the number triangle, followed by an 11th row that would display the total of all digits with right-justification. ## Testing Testing of this string can be performed with a randomly generated string of ten digits of your choosing, or one generated from the snippet below... ``` c1=()=>('1331123221'+(Math.random()*(1<<24)|0).toString(4)).replace(/0/g, "").slice(-10).split("").join(" "); $("#btn").click(function(){ $("#str").val(c1()); }); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="str"><button id="btn">Get numbers</button> <br> Please use this snippet to generate a starting row for testing your code. Alternatively, you can also use a string of your choice, so long as it's ten digits (ranging from 1 to 3), separated by single spaces. ``` ## Rules 1. Code-golf rules apply, so lowest number of bytes wins the challenge. In the event that there are two entries with the same low score, the winner will be awarded based on the number of up-votes. 2. What we're basically after is 11 rows, 19 characters long... How you render your final output is entirely up to you: array, console, file output, STDOUT, etc., so please use whatever output method you like that will work to your advantage. The only rule in the output is that we have 11 rows with 19 characters in each row in a similar format to above... 3. If it helps your code, use whatever separator for the digits... Just remember that legibility may be a contributing factor. 4. [No silly loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny). 5. Hard-coding of the input is not allowed. The purposes of this code is such that it can be used to produce different results each time with varying input. Hard-coding of `1 1 1 1 1 1 1 1 1 1` for example, completely negates the whole point of the algorithm. Look forward to seeing what you all can come up with! [Answer] # Mathematica, ~~104~~ ~~97~~ ~~90~~ 94 bytes ``` {Grid[List@*Row/@#],#~Total~2}~Column~Right&[NestList[3-Mod[+##,3]&@@@Partition[#,2,1]&,#,9]]& ``` # Explanation ``` Partition[#,2,1] ``` Partitions the input into length 2, offset 1 partitions. ``` 3-Mod[+##,3]&@@@ ``` Takes each partition, and calculates the corresponding output. A trick involved here. I added up the two numbers, took mod 3, and subtracted that result from 3. That gives the desired number. (e.g. 3 - ((2 + 1) mod 3) = 3) ``` NestList[ ... ,9] ``` Repeats the above process nine times, giving all iterations as the output. ``` Grid[List@*Row/@#] ``` Format each iteration into rows, and put the entire thing in one column (center aligned), creating a triangle. ``` #~Total~2 ``` Take the total of all numbers. ``` {...}~Column~Right ``` Combine the triangle and the total, and right align the entire thing (triangle is already aligned, so its alignment is not affected). [Answer] # JavaScript (ES6), ~~143~~ 142 bytes *Saved 1 byte thanks to @Neil* ``` a=>a.map((_,i)=>(q=" ".repeat(i))+(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+q,x=0).join` `+` `+(" ".repeat(18)+x).slice(-19) ``` I tried combining various parts, but it ended up 5 bytes longer: ``` a=>[...a.map((_,i)=>(a=a.map(c=>(x+=r=i&&p^(p=c)||c,r),p=i&&a.shift())).join` `+" ".repeat(i),x=0),x].map(q=>(" ".repeat(18)+q).slice(-19)).join` ` ``` [Answer] # Ruby, ~~134~~ 101 bytes Using JHM's modulo trick. ``` ->a{b=*a (0..8).map{|i|[" "*i,a=a.each_cons(2).map{|x,y|b<<n=3-(x+y)%3 n}]*" "}<<"%19d"%b.reduce(:+)} ``` See it on eval.in: <https://eval.in/649993> [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), ~~44~~ 40 bytes ``` l~{S*\_S*\2ew{:+3%3^}%2$N@}A%_s:~:+sJSe[ ``` [Try it online!](http://cjam.tryitonline.net/#code=bH57UypcX1MqXDJld3s6KzMlM159JTIkTkB9QSVfczp-OitzSlNlWw&input=MSAyIDMgMyAxIDMgMSAzIDEgMl0) ### Explanation ``` l~ e# Read and evaluate input. { e# Map this block over i in the range [0 1 ... 9]. S* e# Get a string of i spaces (the indentation). \_ e# Swap with the current line of trits and duplicate it. S* e# Join the trits with spaces. \2ew e# Swap with the other copy of the trits and get all consecutive pairs. { e# Map this block over the pairs... :+ e# Sum the pair. 3% e# Modulo 3. 3^ e# XOR 3. e# This expression (x+y)%3 ^ 3 computes the required mapping. }% e# Now this is the next line. 2$ e# Copy the indentation (to pad the lines to equal length). N e# Push a linefeed. @ e# Pull up the next line. }A% e# The result of this is a nested array whose string representation is e# the required triangle. _s e# Duplicate and flatten into a string. :~ e# Eval each character which gives a list of all the trits. :+ e# Sum that. s e# Turn the sum into a string. JSe[ e# Left-pad it with spaces to width 19. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~32~~ 26 bytes ``` DvÐOˆðýðN×.ø,ü+3%3^}\¯O19j ``` **Explanation** ``` D # duplicate input v # for y,N in input,len(input): (10 times do) Ð # triplicate current list Oˆ # sum one copy and add it to global array ðý # merge one copy on spaces ðN×.ø # surround it with N spaces , # and print it ü+ # reduce one copy by addition 3% # modulus 3 3^ # XOR 3 # this is the list sent to the next iteration } # end loop \ # drop empty list left over from last iteration of loop ¯O # sum the global array giving the triangles total sum 19j # join with spaces up to 19 chars ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RHbDkE_LhsOww73DsE7Dly7DuCzDvCszJTNefVzCr08xOWo&input=WzEsIDIsIDMsIDMsIDEsIDMsIDEsIDMsIDEsIDJd) [Answer] # Python 2, 164 bytes A relatively simple iterative solution. ``` L=input() s=0 for i in range(len(L)): print" "*-~i+" ".join(`L`[1::3]);s+=sum(L);N=L;L=[] for a,b in zip(N,N[1:]):L+=[list({1,2,3}-{a,b}),[a]][a==b] print"%19s"%s ``` [**Try it online**](https://repl.it/Dhy4) [Answer] ## JavaScript (ES6), ~~112~~ ~~100~~ 96 bytes Takes an array as input and recursively builds a comma-separated triangle. ``` f=(s,p=` `,S=0)=>p+(s[0]?s+f(s.map((v,i)=>(S+=v,v^s[i-1]||v)).slice(1),p+' ',S):(p+S).slice(-9)) console.log(f([1,2,3,3,1,3,1,3,1,2])); // reference example console.log(f([3,3,2,1,3,1,2,1,2,1])); // random example console.log(f([1,1,1,1,1,1,1,1,1,1])); // all ones (test case for sum < 100) ``` [Answer] # PHP, 143 Bytes ``` <?for($t=$_GET[t];$i<181;$s+=$v,$i+=2)$t[$i+20]=($v=$t[$i])*($z=$t[$i+2])>0&$i!=18?($v+$z)%3^3:" ";echo chunk_split($t.str_pad($s,8," ",0),19); ``` ]
[Question] [ As of time of submission to the sandbox, I had 17017 reputation, which you will all be able to factorise as 7×11×13×17, a product of 4 consecutive primes. Please write a function or program to output all the products of two or more consecutive primes up to an input integer `n`. For example, given `n=143` you should output `6, 15, 30, 35, 77, 105, 143` (or equivalent output format). Normal restrictions on I/O and loopholes apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (no doubt there is golfing to do here! - yep...) -4 bytes thanks to @Dennis - replace check for greater than n by using a range ``` ÆRẆP€ḟÆRfR ``` Note - this is both extremely inefficient *and* the results are unsorted. Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=w4ZS4bqGUOKCrOG4n8OGUmZS&input=&args=MTQz) How? ``` ÆRẆP€ḟÆRfR - main link takes an argument, n ÆR ÆR - primes up to n Ẇ - all sublists P€ - product for each ḟ - filter out the primes (since the sublists include those of lnegth 1) fR - filter out any not in range [1,N] (yep, it's calculating all products of primes up to n - gross) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~25~~ 20 bytes ``` Zq&Xf"@gnq?2MpG>~?6M ``` Approach similar to that in [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/92238/36398). [Try it online!](http://matl.tryitonline.net/#code=WnEmWGYiQGducT8yTXBHPn4_Nk0&input=MTQz) --- ### Old version, 25 bytes ``` :YF!"@2<@sq0@0hhdz2=v?X@D ``` This obtains the exponents of prime factor decomposition for all numbers from `1` to the input. For each it checks: 1. If all exponents are less than 2. 2. If the sum of all exponents is greater than 1. 3. The array of exponents is extended with an additional zero on each end. The consecutive differences of the extended array are computed. There should be exactly 2 nonzero differences. If the three conditions are fulfilled the number is displayed. Results are in incresing order. [Answer] # Javascript (ES6), ~~105~~ 104 bytes ``` n=>{for(i=1,P=[];i++<n;P[P.every(v=>i%v)?i:n]=i);P.map(i=>P.map(j=>j>i&&(p*=j)<=n&&console.log(p),p=i))} ``` ### Demo ``` var f = n=>{for(i=1,P=[];i++<n;P[P.every(v=>i%v)?i:n]=i);P.map(i=>P.map(j=>j>i&&(p*=j)<=n&&console.log(p),p=i))} f(143) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~17~~ 15 [bytes](http://www.cp1252.com/) ``` L<ØŒ€PD¹>‹ÏDp_Ï ``` **Explanation** ``` L<Ø # get the first N primes, where N is the input Œ # get all combinations of consecutive primes €P # calculate the product of these sublists D¹>‹Ï # keep only the products less than or equal to N Dp_Ï # keep only those that aren't prime ``` [Try it online!](http://05ab1e.tryitonline.net/#code=TDzDmMWS4oKsUETCuT7igLnDj0RwX8OP&input=MTQz) [Answer] # Pyth, 18 bytes ``` f}PTftlY.:fP_YSQ)S ``` A program that takes input of an integer on STDIN and prints a list of integers. [Try it online](https://pyth.herokuapp.com/?code=f%7DPTftlY.%3AfP_YSQ%29S&input=143&debug=0) **How it works** ``` f}PTftlY.:fP_YSQ)S Program. Input: Q SQ Yield [1, 2, 3, ..., Q] fP_Y Filter that by primality .: ) Yield all sublists of that f Filter the sublists by: lY Length t -1 removing sublists of length 1 f S Filter [1, 2, 3, ..., Q] (implicit input fill) by: PT Prime factorisation } is in the sublists Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆfÆCI=1Ȧµ€T ``` Not the shortest Jelly answer, but this approach is rather efficient and the output is sorted. [Try it online!](http://jelly.tryitonline.net/#code=w4Zmw4ZDST0xyKbCteKCrFQ&input=&args=NTAwNQ) ### How it works ``` ÆfÆCI=1Ȧµ€T Main link. Argument: n µ€ Map the preceding chain over each k in [1, ..., n]. Æf Compute all prime factors of k, with multiplicities. ÆC Count the number of primes less than or equal to each prime factor. This maps the j-th to j. I Increments; compute the forward differences of consecutive indices. =1 Compare each difference with 1. Ȧ All; return 1 iff the array is non-empty and has no zeroes. T Truth; yield all indices for which the chain returned 1. ``` ]
[Question] [ You're tasked with writing a program that syllabifies words in a string of text, by separating them with a hyphen. That would be a lot of work, so you want to skip some parts, mainly because you don't want to have a table of the pronunciations required for perfect algorithm. You also want to make it as short (and thus unreadable and unmaintainable) as possible as a revenge for being given this assignment. You have two choices: * Write a program that takes the string from STDIN and outputs the result to STDOUT. * Write a function that takes the string as a single parameter, and returns the result. ## Specification * In this case, string means any string-like construct in your language of choice (byte arrays, character arrays, strings...). * Vowels are `a, e, i, o, u` * The string given has `1 <= n <= 10` words, where each has a length between `1 - 30` characters, inclusive.. Your output should be those words hyphenated. * All letters are lowercase and words are always separated with spaces. Thus, the input consists of characters `[a-z ]` * Apply rules in order of importance. * When a word is divided, start again with the right half of the word. **Rules for syllabification**, in order of importance Two consecutive same vowels count as one (ie. `feet` has only one vowel, but `beat` and `finding` have two). Every syllable has exactly one vowel, thus there is one syllable for each vowel. 1. If the **whole word** has only four letters, return it unchanged. (skip this for the rest of the word) 2. If the word has only one vowel, return the word unchanged. 3. If the word has two consecutive vowels, divide between them (ie. `diaspora` -> `di-as-po-ra`) 4. When two or more consonants come between two vowels (same or different), divide after the first consonant (ie. `sis-ter`) unless the consonant part is `ck`, in which case divide the word after it. (ie. `nickel` -> `nick-el`) 5. When a `y` comes between two vowels, divide the word after it (e.g. `paying` -> `pay-ing`). 6. When one consonant comes between two vowels (same or different), divide before the consonant (ie. `dra-gon`) 7. Return the word unchanged if no division could be done. I chose these rules, because they can be applied recursively without problems and require no pronunciation tables. Thus, they are not accurate, and for example rule #5 is often not correct. In general case though, it is. ## Example ``` In: hello world Out: hel-lo world In: have a nice day Out: have a nice day In: pour some nickel and xenon there Out: pour some nick-el and xe-non the-re ``` [Answer] # Lua, 292 Lua might not have been the best language to do this in, but it works. It pretty much flows like the question asked. The rules are mainly in order with some optimizations: #2 is skipped (it isn't needed unless there is a one vowel word with "ck" at the beginning), and the ck and y rules are gone through before the rest of #4 and #6, which are combined. Since some vowels in the word need to be captured twice (after one hyphen and before another), that search is performed twice. ``` i=io.read()v="([aeiou])"for s in i:gfind("%l+ ?")do if s:len()~=4 then s=s:gsub(v..v,function(x,y)if x==y then return x..y;end;return x.."-"..y;end)s=s:gsub("ck"..v,"ck-%1")s=s:gsub(v.."y"..v,"%1y-%2")for b=1,2 do s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4")end end io.write(s)end ``` ## Ungolfed ``` function checkEquals(x,y) if x==y then return x..y end return x.."-"..y end i=io.read() v="([aeiou])" for s in i:gfind("%l+ ?") do if s:len()~=4 then s=s:gsub(v..v,checkEquals) s=s:gsub("ck"..v,"ck-%1") s=s:gsub(v.."y"..v,"%1y-%2") for b=1,2 do s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4") end end io.write(s) end ``` Test it here: <http://ideone.com/g57TzA> [Answer] # Ruby, 144 bytes If we're going for unmantainable, how about a single giant regex? ``` puts gets.split.map {|w| w.scan(/(^.{4}$|[^aeiou]*([aeiou])\2?((?=[^aeiouy]?[aeiou])|ck|[^aeiou]((?=.*[aeiou])|.*$)|$))/).map(&:first)*'-'}*' ' ``` some output: ``` echo "hello world" | ruby syllable.rb hel-lo world echo "have a nice day" | ruby syllable.rb have a nice day echo "pour some nickel and xenon in there" | ruby syllable.rb pour some nick-el and xe-non in the-re echo "diaspora dragon paying sister hemlock happy quicksilver" | ruby syllable.rb di-as-po-ra dra-gon pay-ing sis-ter hem-lock happy qu-ick-sil-ver ``` [Answer] # Bash+coreultils, 173 bytes I think I have all the latest rule changes: ``` v=aeiou r="[$v])/\1-\2/g" s=s/\([$v] e="$s[^$v-])([^$v-]+$r " tr \ \\n|sed -r "/^([a-z]{4}|[^$v]*[$v][^$v]*)$/bx $s)($r ${s}ck)($r $e$e${s}y)($r $s)([^$v-]$r :x"|tr \\n \ ``` Note the last character of the last line is a (space). I think this sufficiently satisfies *"unreadable and unmaintainable"* ;-) Takes input from STDIN. Mostly straight regex substitution. The first line of the `sed` expression matches for rules 1 and 2, then simply jumps to the `:x` label at the end of the expression. The `tr`s at the start and end of the pipeline make the words newline-separated, so they are easier for `sed` to deal with. I was hoping to do and all `sed` answer, but this way is simpler and easier. ### Example: ``` $ ./sylabify.sh <<< "diaspora nickel sister dragon hello world have a nice day pour some nickel and xenon there paying tricks quicksilver" di-as-po-ra nick-el sis-ter dra-gon hel-lo world have a nice day pour some nick-el and xe-non the-re pay-ing tricks qu-ic-ksil-ver $ ``` ]
[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/17588/edit). Closed 2 years ago. [Improve this question](/posts/17588/edit) In the [2014 challenge](https://codegolf.stackexchange.com/a/17094/2605), Michael Stern suggests using OCR to parse ![an image of the number 2014](https://i.stack.imgur.com/MncwS.png) to 2014. I'd like to take this challenge in a different direction. Using built-in OCR from the language/standard library of your choice, design the smallest image (in bytes) which is parsed into the ASCII string "2014". Stern's original image is 7357 bytes, but with a bit of effort it can be losslessly compressed to 980 bytes. No doubt the black-and-white version (181 bytes) works as well with the same code. Rules: Each answer should give the image, its size in bytes, and the code needed to process it. No custom OCR allowed, for obvious reasons...! Any reasonable languages and image formats are allowed. *Edit:* In response to comments, I'll broaden this to include any preexisting library, or even <http://www.free-ocr.com/> for those languages where no OCR is available. [Answer] # Shell (ImageMagick, Tesseract), 18 bytes ``` file=golf_2014 echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png tesseract $file.png $file digits cat $file.txt rm $file.pbm $file.png $file.txt ``` The image is 18 bytes and can be reproduced like this: ``` echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > 2014.pbm ``` It looks like this (this is a PNG copy, not the original): ![2014](https://i.stack.imgur.com/mAyeW.png) After processing with ImageMagick, it looks like this: ![2014 big](https://i.stack.imgur.com/zl7Eq.png) Using ImageMagick version 6.6.9-7, Tesseract version 3.02. The PBM image was created in Gimp and edited with a hex editor. --- This version requires `jp2a`. ``` file=golf_2014 echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png tesseract $file.png $file digits cat $file.txt convert -background black -fill white -border 2x2 -bordercolor black -pointsize 100 label:$(cat $file.txt) $file.jpg jp2a --chars=" $(cat $file.txt) " $file.jpg rm $file.pbm $file.png $file.txt $file.jpg ``` It outputs something like this: ``` 2014444444102 01144444102 214441 214441 1 1 24 1 04 4 0 4 1 410201 0 0 410004 1 2014 4 21 4 24 42 0 4 4 0 1 0 24 4 04 4 22222 1 1 0 42 0 4 2 4100 4 1 41 4 1 42 0 4 2 2 2412 0 4 24 420 4 04 42 0 1 2 2 0 4 0 40 0 4 204 42 0 1 2 2 0 4 24 42 0 4 21 12 0 4 0 42 0 4 2 411114 1112 04 412 24 0 1 0 0 4 0 0 24 1111111110 1 42 21 4 0 4 200011111001 40002 4 4 04 44 42 0 4 0 4 0 4 214 10 0 4 0 4 22222222222222222 222222 22222 22222 ``` [Answer] # Java + Tesseract, 53 bytes Since I don't have Mathematica, I decided to ~~bend the rules a bit and~~ use [Tesseract](https://code.google.com/p/tesseract-ocr/) to do the OCR. I wrote a program that renders "2014" into an image, using various fonts, sizes and styles, and finds the smallest image that gets recognized as "2014". Results depend on the available fonts. Here is the winner on my computer - 53 bytes, using the "URW Gothic L" font: ![2014](https://i.stack.imgur.com/3abHX.gif) Code: ``` import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.imageio.ImageIO; public class Ocr { public static boolean blankLine(final BufferedImage img, final int x1, final int y1, final int x2, final int y2) { final int d = x2 - x1 + y2 - y1 + 1; final int dx = (x2 - x1 + 1) / d; final int dy = (y2 - y1 + 1) / d; for (int i = 0, x = x1, y = y1; i < d; ++i, x += dx, y += dy) { if (img.getRGB(x, y) != -1) { return false; } } return true; } public static BufferedImage trim(final BufferedImage img) { int x1 = 0; int y1 = 0; int x2 = img.getWidth() - 1; int y2 = img.getHeight() - 1; while (x1 < x2 && blankLine(img, x1, y1, x1, y2)) x1++; while (x1 < x2 && blankLine(img, x2, y1, x2, y2)) x2--; while (y1 < y2 && blankLine(img, x1, y1, x2, y1)) y1++; while (y1 < y2 && blankLine(img, x1, y2, x2, y2)) y2--; return img.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1); } public static int render(final Font font, final int w, final String name) throws IOException { BufferedImage img = new BufferedImage(w, w, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = img.createGraphics(); float size = font.getSize2D(); Font f = font; while (true) { final FontMetrics fm = g.getFontMetrics(f); if (fm.stringWidth("2014") <= w) { break; } size -= 0.5f; f = f.deriveFont(size); } g = img.createGraphics(); g.setFont(f); g.fillRect(0, 0, w, w); g.setColor(Color.BLACK); g.drawString("2014", 0, w - 1); g.dispose(); img = trim(img); final File file = new File(name); ImageIO.write(img, "gif", file); return (int) file.length(); } public static boolean ocr() throws Exception { Runtime.getRuntime().exec("/usr/bin/tesseract 2014.gif out -psm 8").waitFor(); String t = ""; final BufferedReader br = new BufferedReader(new FileReader("out.txt")); while (true) { final String s = br.readLine(); if (s == null) break; t += s; } br.close(); return t.trim().equals("2014"); } public static void main(final String... args) throws Exception { int min = 10000; for (String s : GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()) { for (int t = 0; t < 4; ++t) { final Font font = new Font(s, t, 50); for (int w = 10; w < 25; ++w) { final int size = render(font, w, "2014.gif"); if (size < min && ocr()) { render(font, w, "2014win.gif"); min = size; System.out.println(s + ", " + size); } } } } } } ``` [Answer] # Mathematica ~~753~~ 100 ``` f[n_,format_]:= Module[{filename}, Print["raster: ",n," by ", n]; filename="2014At"<>ToString[n]<>"."<>format; Print["filename: ",filename]; Print["format: ",format]; Print["raster image: ",rasterImg=Rasterize[Style[2014,"OCR A Std"], RasterSize->n,ImageSize->1n,ImageResolution->6n]]; Export[filename,rasterImg]; Print["Actual imported image: ",img=Switch[format,"PDF"|"HDF",Import[filename][[1]], _,Import[filename]]]; Print["Identified text: ",TextRecognize[ImageResize[img,Scaled[3]]]]; Print["filesize (bytes): ",FileByteCount[filename]]] ``` My best case so far: ``` f[24, "PBM"] ``` ![efficiency](https://i.stack.imgur.com/UKUn0.png) [Answer] ## Mathematica, 78 bytes The trick to winning this in Mathematica will probably be use of the ImageResize[] function as below. First, I created the text "2014" and saved it to a GIF file, for fair comparison with David Carraher's solution. The text looks like ![2014](https://i.stack.imgur.com/tBtiv.gif). This is not optimized in any way; it's just Geneva in a small font size; other fonts and smaller sizes may be possible. Straight TextRecognize[] would fail, but TextRecognize[ImageResize[]]] has no problem ``` filename = "~/Desktop/2014.gif"; Print["Actual imported image: ", img = Import[filename]] Print["Identified text: ", TextRecognize[ImageResize[img, Scaled[2]]]] Print["filesize (bytes): ", FileByteCount[filename]] ``` ![results](https://i.stack.imgur.com/v24TM.png) Fussing with the typeface, font size, degree of scaling, etc., will probably result in even smaller files that work. ]
[Question] [ Given an initial \$n\$-tuple \$t\_0=(t\_{0,1},...,t\_{0,n})\$, we can obtain its corresponding [Ducci sequence](https://en.wikipedia.org/wiki/Ducci_sequence) \$\{t\_0, t\_1, ...\}\$ by the recurrence \$\displaystyle t\_{i+1}=\left(\left|t\_{i,1}-t\_{i,2}\right|,\left|t\_{i,2}-t\_{i,3}\right|,...\left|t\_{i,n}-t\_{i,1}\right|\right)\$. That is, to obtain the next term of the sequence, we take the absolute differences of successive terms of \$t\_i\$, treating it as cyclic; by convention, the first element corresponds to the difference of the first two elements of \$t\_i\$. When the initial tuple \$t\_0\$ consists of integers, such sequences are always eventually periodic. For example, \$(3,1,4)\to(2,3,1)\to(1,2,1)\to\underline{(1,1,0)}\to(0,1,1)\to(1,0,1)\to\underline{(1,1,0)}\$ has a cycle of length 3. ## Task Given a length \$n\$, compute the maximum cycle length among all Ducci sequences on tuples of \$n\$ integers. This is [A038553](https://oeis.org/A038553) on OEIS. ### Test cases ``` 1 1 2 1 3 3 4 1 5 15 6 6 7 7 8 1 9 63 10 30 11 341 12 12 13 819 14 14 15 15 16 1 17 255 18 126 19 9709 20 60 21 63 22 682 23 2047 24 24 25 25575 37 3233097 51 255 ``` [Answer] # JavaScript (ES6), 62 bytes ``` n=>eval(`for(m=1,o=j=[];!o[m^=m/2^m%2<<n-1];o[m]=j++);j-o[m]`) ``` [Try it online!](https://tio.run/##FYtBCoMwEEX3nmIKFhKsbdVlnF5ElAQbS0MyU1TciGdP4@o/Pu85s5llnL@/tSR@2zhhJHzZzXihJ55FwOrG6LDr1YW7MGB41EO41m1LZdWrdPXoikIqV56sZTwrb1cgQKhUmhaheSZIFuwZwMi0sLd3zx@hjch3OmRy830SJA8tVXbEPw "JavaScript (Node.js) – Try It Online") --- ## 54 bytes A recursive version, failing earlier. ``` f=(n,m=1,j=o=[])=>++j-o[m]||f(n,m^m/2^m%2<<n-1,o[m]=j) ``` [Try it online!](https://tio.run/##FYxBCoMwEEX3nmIWFjJEW3RV0OlFRFGsloZkRlS6iZ49jav34T2@GX7DNq7fZc9Z3lMIMynOHBWZIaGmRXppbXJpXHsc86U69yg7dyvrmvMiuwQZDLOsyk47MBAUVUQd@YxDawSfAIzCm9jpbuWj@kGlnk@MberjKZ49VskZ/g "JavaScript (Node.js) – Try It Online") --- ## 65 bytes (ES11) A BigInt version. This one can process all test cases on TIO. ``` n=>eval(`for(m=1n,o=j=[];!o[m^=m/2n^m%2n<<~-n];o[m]=j++);j-o[m]`) ``` [Try it online!](https://tio.run/##FcvBCoJAEIDhe08xQcEMrhsa0kFXqFvPIIZLabi4s6IihNmrb3X7@eEzetbjfWj7KWT3qH2jPKu8nnWHVeMGtCpi4ZRRRZluXWFvyh5ivtl9zFn2CblMf7NUJggoNeG/K/J/2NUTMLgGCinleRj0C@OEBBxPApKolFb3iLOAlkDlcGmfV55whvcbWgggIiJYNgB3x6Pratm5J1YadwuvPwC7pUGmtaJ0s/ov "JavaScript (Node.js) – Try It Online") --- ## How? The main observation here is that a necessary condition for a cycle to appear is that the only remaining elements in the tuple are \$0\$ and some \$v>0\$. And because we're only interested in the maximum cycle length, it doesn't matter what happens before we reach this state. When all elements in the tuple are in \$\{0,v\}\$, we have: $$\left|t\_{i,j}-t\_{i,j+1}\right| = t\_{i,j} \operatorname{XOR} t\_{i,j+1}$$ We can arbitrarily choose \$v=1\$ and turn the \$n\$-tuple representation into a bit mask \$m\$. This allows us to apply all updates at once by doing the following 'XOR rotation': ``` m ^= m / 2 ^ m % 2 << n - 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 8 bytes ``` Ṭṙ1ạƊÐḶL ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//4bms4bmZMeG6ocaKw5DhuLZM/8OHKVn//zI1 "Jelly – Try It Online") *-2 [thanks to Bubbler](https://chat.stackexchange.com/transcript/message/64427282#64427282)* Just another port of Arnauld's approach. Now very straightforward, but check the edit history for a good laugh. ``` Ṭ Create a list with a 1 at index n and 0s elsewhere. ƊÐḶ Repeat while unique, collecting only the cycle: ṙ1 rotate once ạ and take element-wise absolute differences with unrotated elements. L How long is the cycle? ``` # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` &NṬnṬṙ1nƊƬL ``` [Try it online!](https://tio.run/##y0rNyan8/1/N7@HONXlA/HDnTMO8Y13H1vj8P9yuGfn/v5EpAA "Jelly – Try It Online") It's longer, but worth showing off how to apparently guarantee starting within a cycle. Namely, when starting with the single-1 tuple as in the approach above, the state that begins the cycle appears to always be the XOR of two single-1 states, rotated relative to each other by the largest power of 2 that divides the length. ``` &N Bitwise AND n with its two's complement. &N This gives the largest power of 2 which divides it. Ṭ Create a list with a 1 at that index and 0s elsewhere. Ṭ Create a list with a 1 at index n and 0s elsewhere. n For each element, are they not equal? ƊƬ Repeat while unique: n elementwise inequality with ṙ1 the current tuple rotated once. L How many distinct tuples did this produce? ``` [Answer] # Python3, 145 bytes: ``` def f(n): m=[];v=[I==0for I in range(n)] while v not in m:m+=[v];v=[abs(v[I]-v[I+1if I+1<n else 0])for I in range(n)] return len(m)-m.index(v) ``` Times out on \$n = 37\$. [Try it online!](https://tio.run/##bZLLboMwEEXXna8YZQNWHmLMO627z6Y/QLMAxTSWwCBDaaso306hNXRTL6yrueN7rLHbr/7aaD9pzTheZImlq9kRsBbZ@XEQ2UkIr2wMnlBpNLl@k5N/Bvy4qkrigLrpZ6c@1luRDT9H8qJzh@x03k/bllSJ0/6kUVadRO/M/kszsn83Giup3Zrt64PSF/npDmzsBG42GyD8XQR8Vb5VPgRrLVxUCJGVEcRWxZCsjeni@kCezfGALMcPCMiSiANZVEIpkIVRABSuMIqWYLI0Hk7VZImIgCwxjb0UuEVGHnBaL8ItMUo4cIvkXhADt0weAA/X@DiEkP5g85jm0ap5tKWqemncl0bLHXaHrq1U7zqv2mHT2z7kOyxQYJ23rtL9DpVtYGzyuk6afvoFOUMhsICH1kxNbunc8juKZ7wVd4eN3w) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` LaVb.<b1l.uyNuyGU ``` [Try it online!](https://tio.run/##K6gsyfj/3ycxLEnPJskwR6@00q@00j30/38jYwA "Pyth – Try It Online") Relies on the same as yet unproven assumption that @Arnauld makes, being that the maximum cycle can always be found by starting with `[1, 0, 0, 0, ...]`. ### Explanation ``` LaVb.<b1l.uyNuyGUQ # implicitly add Q # implicitly assign Q = eval(input()) L # define y(b) aV # absolute difference, vectorized of b.<b1 # b and b shifted one left (cyclically) UQ # list(range(Q)) uyG # repeatedly apply y until a result that has been seen occurs .uyN # repeatedly apply y until a result that has been seen occurs and accumulate all intermediate results l # take the length of this list ``` [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` f=lambda n,k=1:~-2**2**n*k%~-2**n<1or-~f(n,k^1^k*2%~-2**n) ``` [Try it online!](https://tio.run/##LYlLCsIwAAX37xTZCEmw4Es/arFXKVQ0NKRNQ4mIm149FhFmMczETxqXYHK23TTM98cgwtF3bLfCaL0TtD/8PNy4rMVm5f579l6bf1f5PbrpKdjG1YUkrHQhvpJUKhMGJSrUaHDGBVfwBBI0YAlWYA02Xw "Python 2 – Try It Online") A recursive function, outputting True for 1. This will fail on large outputs due to exceeding the maximum recursion depth, which is around 1000 by default. Here's a longer iterative version, though it times out for larger inputs thanks to its double-decker power \$2^{2^n}\$. **62 bytes** ``` N=2**input() k=i=1 while~-2**N*k%~-N:k^=1^k*2%~-N;i+=1 print i ``` [Try it online!](https://tio.run/##HYxLCsIwAAX37xQlIGik0Jf@K7lCjtCNBBoiaZCIuunVY@tyhmHiNy1rUPm9uIctONmPvQshstFKShfiK50v8Npp4p9s5e6N9KetNJOfNWcv1QE3d92b@HQhFS4fC0KhRoMWHXoMGMEKJKjAGmzAFuzAHhzAEar6AQ "Python 2 – Try It Online") Here's the above but more optimized for speed. **70 bytes** ``` n=input() N=2**n k=i=1 while~-2**(N%n)*k%~-N:k^=1^k*2%~-N;i+=1 print i ``` [Try it online!](https://tio.run/##HYxNCoMwGET3cwoRBE0RnC/Gv5IreAQ3RTCkpKFY2m68utUu3/Dmxe@6PILs78Xd54TD/JlvaZruwboQX2teYLSiVIC3zhJ/bSuPJR@zUCifbeU4@Mly8kpOuLrL4cWnC2vi9jNFCDRqGDRo0aEHK5CggBqsQQM2YAt2YA@pIMdHIBpSQwx0C8Mf "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ≔EN∧ι¹θW¬№υθ«⊞υθ≔Eθ⁼κ§θ⊕λθ»I⊕⌕⮌υθ ``` [Try it online!](https://tio.run/##TY7NCoMwEITP5ily3IA9eCyeRFrwoEjfINWlhsZV82MLpc@eRuzB28wwfDPdIE03SR1CYa16ENRyhopm7xo/3tGASHlBPaiUZyLqReTsNSiNHJrJQTl5cuC3XAj@YUnr7bD7nCUH5JLyy@KltvCMQFdRj@8trKgzOCI57EFHxn/iy1qjIrmU1sGxc1XxzA1XNBbBi31Y5CFk53Ba9Q8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Ajax1234's Python answer, but with inverted logic. ``` ≔EN∧ι¹θ ``` Start with an array of length `n` whose first entry is `0` and remaining entries are `1`. ``` W¬№υθ« ``` Repeat until a cycle is detected. ``` ⊞υθ ``` Save the current state. ``` ≔Eθ⁼κ§θ⊕λθ ``` Update the state by comparing each value to the next. ``` »I⊕⌕⮌υθ ``` Output the length of the cycle. A more efficient version using a dictionary and bit twiddling weighs in at 48 bytes, but can handle `n=29` on ATO: ``` ≔⊖X²Nθ≔¹η≔⦃⦄ζW¬§ζη«§≔ζηLζ≔﹪⊗ηθε≔⁻|ηε&ηεη»I⁻Lζ§ζη ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZC9TgMxEIRFydU8wCrVWnKKpCJKdZAmEoT0iOJ-ltiSY4O9zqGL8iQ0EQLBM-VpuHAWRJQz-41mtK9flSp85Qqz339EfhxeHs4u8hD0yuKMKk9rskw1Ll1DHscS5vYp8iKuy04KISQ8i2mWAiMJ6k9tdxLaTjZKGwJcOMac57amF2yPoBCwzc57-PQg4YbsihW2oksnAG9dHY3DmYul6faon2YJdIpoGwNeaW50oDuP6niWkIzc1r0j-pW7bOm1ZbwuAqfob6-Ef0vF9D2UVUgv-rwfDDdm8PA2nvTGNw "Charcoal – Attempt This Online") Link is to verbose version of code. ]
[Question] [ *Inspired by [this challenge](https://puzzling.stackexchange.com/questions/90301/can-you-put-l-trominos-to-fill-the-figure) from puzzling.SE.* Polyominoes are fun - you can fill all sorts of shapes with them. But as soon as you have limits on what polyominoes you can use, you sadly start running into shapes you *can't* fill. Today we'll be looking at the L tromino - a shape made up of three conjoined squares, in such a way that all three squares are of the same size, and there is a corner which they all share. It looks like this: ![An L tromino](https://i.stack.imgur.com/V1kdh.png) Now, given a shape made out of equal-size squares as input, the challenge is to find out whether that shape can be filled using only non-overlapping L-trominoes that are placed entirely within the input figure. You may have any number of these trominoes, and you may rotate each of them by any integer multiple of 90°. ### Rules * The challenge is to make a program or function. * Your program will recieve as input a two-dimensional list of values. * Each entry in the list will contain one of two consistent values of your choice - one to signify that a square should be filled, and the other to signify that it shouldn't. * You may assume there will be at least one row and at least one column, and that every row and every column will contain at least one cell that needs to be filled. You may also either assume that all rows have been padded to be of equal length, or that they contain nothing after their last filled cell - you may also independently assume either of those for the columns. That is to say, with `1` as squares you need to fill, and `0` as squares you need to not fill, you only need to be able to handle one of these four inputs (if given one of the others, your program's behaviour is undefined): ``` 1 1 0 1 1 1 0 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 ``` * To fill some square, you must also fill two other squares. Exactly two of the three squares filled must be diagonally adjacent to (sharing a corner with) eachothers, and they must both be orthogonally adjacent to (sharing a side with) the third. * You may assume the input shape is contiguous. * You may assume the input's dimensions will be no greater than 5x5. * You may not assume the number of rows and the number of columns in the input will be equal. Originally, all this question's test cases featured inputs with an equal number of rows and columns. This was a result of poorly chosen test cases and was not intended to indicate that this would be the case for all inputs. * Your program either needs to output a single consistent value of your choice if filling exactly the squares specified by the input with L-trominoes is possible, and any other value if it is impossible, or vice versa. For example, you may decide to output `false` if the input shape can be filled, in which case that is the only acceptable output for shapes that can be filled, and any output except `false` is acceptable for input shapes that can't be filled. * However, the output of your program must not vary between runs given identical input, if said input is valid. That means if you have output `2` for some particular valid input, any later runs with exactly that input must also output `2`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - make your code as short as you can. ### Examples The examples use `1` and `0` to represent squares that should and shouldn't be filled respectively, uses `true` as the only output for fillable shapes, and `false` as the only output for non-fillable shapes. ``` 1 -> false 0 1 1 1 -> true 1 1 1 1 1 1 1 1 1 -> false 0 1 0 1 1 1 0 0 1 -> false 1 0 0 1 1 1 0 1 1 -> true 1 1 0 1 0 1 1 1 1 1 0 1 -> false 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 -> true 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 0 -> true 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 -> true 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 -> true 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -> false 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -> true ``` [Answer] # JavaScript (ES6), ~~196 ... 185~~ 182 bytes Takes input as a binary matrix. Returns a Boolean value. ``` f=m=>!/1/.test(m)||m.some((r,y)=>r.some((v,x)=>v&&[0,1,2,3].some(d=>([X,V]=(g=d=>[v=x+--d%2,R=m[y+--d%2]||0,R[v]])(d))[2]&g(d+1&3)[2]&&(r[x]=V[X]=R[r[x]=V[X]=R[v]=0,o=f(m),v]=1)&o))) ``` [Try it online!](https://tio.run/##jZBNboNADIX3nIIuCjOKITNkPRyCRRTJnQUKP2kFTAUUgcTdKTSVCA1T2L1ny5@f/RE2YXUt3z9rp1BRPAyJyIX/cuRHt46rmuS073O3UnlMSAkdFX756xpoR9dYFjLg4MFJ3huR8Ale4CwFScVosBHtwXGiVw8CkWN317LvGQTYSElJRCl60kpJdODW6UdbpMRWijNepAjwUTdSMFAiGZPBqDm1FKV0uKqiUlnsZiolNiZhVnXSpsZjOSFomGhyUxqSrrfGQ8Y2aLRubLqfrYwxYLCxbR5jms0zYsGw3wqsy6/6pjtzwfsvBNNk51vZlymZ1u343vLVK8NzpintftRfx/ai@CbqCbyBWr75GbfHTyuGbw "JavaScript (Node.js) – Try It Online") This algorithm is too slow for the penultimate test case on TIO, but it does find the answer on my laptop in about 90 seconds. ### How? This is a brute force search that looks for all possible trominos in the input matrix and attempts to remove them (one at a time) until the matrix is cleared or all combinations are proven to fail. Given a reference cell at \$(x,y)\$ (in blue below) and a direction \$0\le d\le 3\$: * We invoke the helper function \$g\$ with \$d\$ to get a first neighbor cell (in yellow) whose coordinates are `x+(d-2)%2` and `y+(d-1)%2`. * We invoke \$g\$ again with \$(d+1)\bmod 4\$ to get a second neighbor cell (in red). This gives: [![trominos](https://i.stack.imgur.com/Ozp1m.png)](https://i.stack.imgur.com/Ozp1m.png) ### Commented ``` f = m => // f is a recursive function taking the matrix m[] !/1/.test(m) || // stop if m[] does not contain any 1 anymore (success) m.some((r, y) => // otherwise, for each row r[] at position y in m[]: r.some((v, x) => // for each value v at position x in r[]: v && // abort right away if this cell is already empty [0, 1, 2, 3].some(d => // otherwise, for each direction d: ( [X, V] = ( // get the 1st neighbor cell g = d => [ // g is a helper function taking a direction // and returning the corresponding neighbor cell: v = x + --d % 2, // save the x-coordinate in v R = m[y + --d % 2] // extract the row R[] || 0, // (0 is used as a default object to prevent // an access to an undefined row) R[v] // get the value of the cell ] // return the tuple [v, R, value] )(d) // )[2] & // get the value of the 1st neighbor cell g(d + 1 & 3)[2] // get the value of the 2nd neighbor cell && ( // if both neighbor cells are set, this is a r[x] = V[X] = R[ // valid L-tromino: r[x] = // remove it by clearing the current cell V[X] = R[v] = 0, // and its 2 neighbors o = f(m), // save the result of a recursive call in o v // and restore the tromino ] = 1 // ) & o // yield the result of the recursive call ) // end of loop over the directions ) // end of loop over the columns ) // end of loop over the rows ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~136~~ 131 bytes ``` lambda S:g(int((len(S)*'{:0<6}').format(*S),2))<1 g=lambda b:b*all(b>>i&t^t or g(t<<i^b)for i in range(30)for t in(67,131,193,194)) ``` [Try it online!](https://tio.run/##bVBfa8IwEH/PpzgymIkUSXQ4VqofYt2bU0jXtIa1aUkjQ8TP3iW12io@JHf3@3N3SX20@0ov2mz13RaiTFIBcZgTpS0hhdQkptPJKWTR8jyhs6wypbBkGtNgTmnEUb7qPUmYTEVRkGS9Vq92Z6EykBMbRWqXUGcDBUqDETqXZME6xDqELN8DvuAB/1i480Zp@7dXhYQvc5AhghhWsNkiMC5ijOAFPqVIodLSeeuDhaQSJkVwZ4LGqTua0FljjaoJdajKHOF2INg6HQ5wJopGYuod3YDGJ73PTfqpdHMoJciytkcolJaeT4wUvy6pjf@hxjeOZ6KupU5JswnD@dZBFzLDp8x93xk2J3Pe4htOWw6oG44QA464O34l5LNLfbsHGbAeYuCrK@PwEePjqBfr6KHjvXFA2V3k4zYMhnVGdI@zZ7IhskcZfyq7yR9k14eNpc@zq/Ef "Python 3 – Try It Online") **Input:** A list of strings, each string must be a binary string. The length of the strings can be different. **Output:** `True` if the shape can be tiled, `False` otherwise. *-5 bytes thanks to @Lynn*! ## Big idea: As with most code golf solutions, this is a brute-force recursive search. The program simply tries to remove an L-tromino from the shape, then recurs on the new shape. By representing the shape using a bitboard (one integer, where each bit represents whether a cell is occupied or not), we can: * Use bit-wise AND to check if an L-tromino fits within a shape * Use bit-wise XOR to remove an L-shaped part from the shape. ## Program explanation Constructing the bitboard: ``` int( (len(S)*'{:0<6}').format(*S) # left pad each row with '0' to length 6 # then concat all rows together ,2) # interpret the result string as binary integer ``` Recursive function that returns 0 if the shape can be tiled, or a positive integer if the shape cannot be tiled. ``` g=lambda b:\ # receive a bitboard as argument b * # tilable if b is 0 all( # tilable if any of the following is False, i.e. all(...)==0 b>>i&t^t or # tromino doesn't fit shape or g(t<<i^b) # the remaining is not tilable, i.e. g(...)==0 for i in range(30) # for each position in shape for t in(67,131,193,194) # for each tromino orientation ) ``` ## More details **Bitboard layout** The following diagram specifies which cell in the shape correspond to which bit in the bitboard: ``` 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 ``` The size of the bitboard is 5 x 6, which is enough to store 5 x 5 shapes. If the shape has less than 6 columns, it is padded with `0` to the left. For example: ``` 111 ...111 1.1 ----> ...1.1 ----> ...111 ...1.1 ...11. ----> 0x7146 11. ...11. shape padded bitboard (binary) bitboard (hex) ``` (**Note:** `0` is denoted by `.` for visual clarity) Since each shape has at most 5 columns as specified in the problem, there will always be an empty column to the left of the bitboard. This will be important to prevent wrap-around later. Each tromino orientation can be represented by 1 bitboard: ``` ...... ...... ...... ...... ...... ...... ...... ...... tromino ...... ...... ...... ...... .....1 ....1. ....11 ....11 ....11 ....11 .....1 ....1. bitboard 67 131 193 194 (decimal) ``` **Check if a tromino fits within the shape** To check if an L-tromino `t` fits inside a certain position in shape `b`, we can use bit-wise AND: ``` ...... ...... ...... ...... shift to ....1. AND tromino ....1. ...... position ...11. with shape ...11. .....1 ---------> ...... -----+--------> ...... ....11 ...... | ...... t t << 13 | (t << 13) & b | ...... | ...1.. | ..111. -----+ ...1.. ...... b ``` We can see that the tromino fits inside the shape if and only if `(t << i) & b == (t << i)` (where `i` is the desired position). This is equivalent to: ``` (b >> i) & t == t ``` **Remove an L-shaped region from the shape** We can use bit-wise XOR to remove a tromino from the shape: ``` ...... ..1111 ..1111 ....1. ..1111 ..11.1 ...11. XOR ..1111 ----> ..1..1 ...... ..1111 ..1111 ...... ..1111 ..1111 t << 13 b b2 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 81 bytesSBCS ``` L←⊂⍤2⊢4 2 2⍴∘.≠⍨⍳4 {∧/~,⍵:1⋄∨/∇¨⍵∘{r c l←-⍵⋄⍺>c⌽r⊖(⍴⍺)↑L⊃⍨-l}¨⍸{∧/∘,¨L≤⊂⍵}⌺2 2⊢⍵} ``` [Try it online!](https://tio.run/##hZC/SsNQFIf3PMUZE2jsvUknBxcXCwHB@gKlUpeA0k1KHazU5NpbdFActRTM5qCBEnDJo5wXiefmD@SmRpebe/h957s/Mrz07bOroX9xnuHqqX@MiweWeXSiuEG5cVCse@CAg/ILg5c9DF9RRig/e8YUg/fudQdlvM/x/haDqIvBXUphTOR0AiPwyWOrmWKZHIxw@T1B8WwqmUwsXDx6KOYktP2ZWtzmTtrupJGH4SbvEM9wmagGYq2GbKzKyVXRVszTD5c8NA1ODuk8PeoPMgYYvsEYOHB6ihu8nAk0GXDLpMAyKsoFN6eYTgHLOYUzUFuahmIN0IwFUBqqB4vPL6JaxhqXImr2r3iuY2XE/uBrF9bC8xa@tvgPX2l3o50f1PSzlsUf "APL (Dyalog Unicode) – Try It Online") Monadic dfn that takes a binary matrix and gives 1 if it can be tiled with L-triominoes, 0 otherwise. A brute-force recursive search by removing one triomino at a time. Uses the fact that every orientation of an L-triomino fits within a 2x2 box, so the code tests all 2x2 submatrices of the input array to search for possible L-triomino placements. The Stencil operator `⌺` fits perfectly for this purpose. The algorithm becomes much faster if we limit the branches to the first 5 placements (which is guaranteed to include all possible placements that includes the top-left cell) at the cost of 8 bytes `(⊢↑⍨5⌊≢)`: ``` L←⊂⍤2⊢4 2 2⍴∘.≠⍨⍳4 {∧/~,⍵:1⋄∨/∇¨⍵∘{r c l←-⍵⋄⍺>c⌽r⊖(⍴⍺)↑L⊃⍨-l}¨(⊢↑⍨5⌊≢)⍸{∧/∘,¨L≤⊂⍵}⌺2 2⊢⍵} ``` [Try it online!](https://tio.run/##hZDNSsNAFIX3fYpZJtDamaRuXLhxY6EgWF@gVOomoHQnpS6s1CRmgi4qLrUUzM6FBkrATR7lvEi8kx9I0tZuZu6d891zLjO4sVqXtwPr@iqBv@ieYf7Mkx6dcO8hVwbcZYcZzID8gf12AOcdMoD87jQmsD/bd03I8Ejg6QF20Ib9GJMYEjkZsyGzyKelepJldDyE9zuG@6opMxnpmL/04M7IsGVN40CjLHqi9hCeC2epQ67TFPJrxkEPzirdKpzCi9ROxFOTjNS60s/2d2fxl6ls/EX//ITOi9NuP@EMzgcbMcEEhYuGyHsCNc6ErpGgNwrKZGZK8SrFeMopnDM1VbEhuQJUHDMgdygCs2uLUUnjtSKT6vsXvKhiucT/4UsF38GLHXxpcA9f2G5KGx9U9@e7BrcklvT9Jd@avW@OV1//AA "APL (Dyalog Unicode) – Try It Online") ### Ungolfed with comments ``` ⍝ 4 rotations of L-triomino; looks like ⍝ ┌───┬───┬───┬───┐ ⍝ │0 1│1 0│1 1│1 1│ ⍝ │1 1│1 1│0 1│1 0│ ⍝ └───┴───┴───┴───┘ L←,{0@(⊂⍵)⊢2 2⍴1}¨⍳2 2 ⍳2 2 ⍝ Indexes of 2-by-2 matrix { ⊢2 2⍴1}¨ ⍝ For each, modify [1 1][1 1] so that 0@(⊂⍵) ⍝ that position becomes 0 , ⍝ Flatten top level ⍝ Main function; 1 if L-triomino tiling is possible, 0 otherwise f←{ ⍝ If no cells left, return True ∧/~,⍵: 1 ~,⍵ ⍝ Boolean negation of flattened input matrix ∧/ ⍝ All; reduce by And : 1 ⍝ If true, return 1 ⍝ Get possible placements as (row_idx, col_idx, L_idx) triples places←⍸{∧/∘,¨L≤⊂⍵}⌺2 2⊢⍵ { }⌺2 2⊢⍵ ⍝ Map over 2x2 submatrices... ∧/∘,¨L≤⊂⍵ ⍝ Can each of L be placed on a submatrix? L≤⊂⍵ ⍝ Compare each cell of each of L with each cell of the submatrix ⍝ so that L(1) vs. ⍵(0) gives False and anything else gives True ∧/∘,¨ ⍝ Reduce by And on all cells of each comparison matrix ⍸ ⍝ Indexes of ones places← ⍝ Assign to places ⍝ For each possible placement, remove the cells and ⍝ recursively try L-triomino placements ⍝ If no possible placement, ∨/ automatically gives False ∨/∇¨⍵∘{r c l←-⍵⋄⍺>c⌽r⊖(⍴⍺)↑L⊃⍨-l}¨places ⍵∘{ }¨places ⍝ Map each on the places... r c l←-⍵⋄ ⍝ Dissect the placement; negate due to built-in rotation direction L⊃⍨-l ⍝ Fetch the target L-triomino (⍴⍺)↑ ⍝ Overtake to fit the size of input matrix c⌽r⊖ ⍝ Rotate to move the L-triomino to correct position ⍺> ⍝ Remove L-triomino cells from input matrix ∇¨ ⍝ Recursively test for L-triomino placements ∨/ ⍝ True if at least one is successful } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~146 112~~ 108 bytes ``` ->m{g=->q{[7,11,13,14].any?{|x|t=x/4|x%4>>~m[0].size;t*=2until t>=q||q&t==t&&g[q-t];t<=q}};g[(m*?0).to_i 2]} ``` [Try it online!](https://tio.run/##ZZDhCoJAEIRfRYSk4rTdEvphdz3IcURBiZDW1QpXnr26laVd9WcHZr5llj2Vm0uz400o8irlodCVnDNEhjOGsYrWxWVZWWOJm0lszSAW4pZLUNE5u24TGvNpWVC290hwba0OiHMKglTqkFRCC67rOknlMB8vYRTRYZV5U1U3UvroK/aYiD5z5tMDhN4D6LjWA4eGjm6tFwXOJvYNLxxc@XS9qz92uwrfaSfgpvib9lCXvq/p839VKsrXx@eDjyWdPcN20jz@cwc "Ruby – Try It Online") ]
[Question] [ I'm a big fan of number theory. A big thing in number theory is modular arithmetic; the definition being \$a\equiv b\mod m\$ if and only if \$m\mid a-b\$. A fun thing to do is raising to powers: especially when the modulus is a prime number. In particular, it has been proven that if \$a\$ and \$m\$ are relatively prime (share no common factors besides \$1\$) then there exists a number \$e\$ such that \$a^e\equiv 1\mod m\$. I will explain what the exercise is by an example. Let's take a modulus \$m=7\$. A possible output of the program or function would be: ``` 3 2 6 4 5 1 2 4 1 2 4 1 6 1 6 1 6 1 4 2 1 4 2 1 5 4 6 2 3 1 1 1 1 1 1 1 ``` Each row is a list of the powers of the first number in that row: the first row is \$3, 3^2, 3^3, \cdots, 3^6\$, which is equivalent to \$3,2,6,4,5,1\$ modulo \$7\$. The second row of the square above is the powers of \$2\$, etcetera, up to the last row, which are just powers of \$1\$. This is a magical modulo square because: * The square is symmetric; that is, the \$i\$th column is the same as the \$i\$th row. * All values \$1\$ to \$m-1\$ appear at least once. Below is the only other valid output for \$m=7\$, starting with powers of \$5\$: ``` 5 4 6 2 3 1 4 2 1 4 2 1 6 1 6 1 6 1 2 4 1 2 4 1 3 2 6 4 5 1 1 1 1 1 1 1 ``` ## The challenge Create a function or program that given a prime `p` outputs a magical modulo square, that is, a square with side lengths `p-1`, such that each row is a list of the consecutive powers of the first element in the row, and the same for the columns. All numbers between `0` and `p` must occur, and the square can only contain numbers in that range. Input is a number or a string, and output can be ascii, a matrix, an array of arrays (any reasonable format). This is code-golf, so the shortest code wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -3 thanks to Nick Kennedy ~~Feels like~~ the repeated code ~~should be~~ is golf-able, but I ~~have~~ did not manage~~d~~ it... ``` *€Ṗ%µQƑƇḢị ``` **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//KuKCrOG5liXCtVHGkcaH4bii4buL/8OHR///Nw "Jelly – Try It Online")** (footer pretty-formats as a grid) ### How? ``` *€Ṗ%µQƑƇḢị - Link: integer, p € - for each n in [1..p] * - exponentiate with: Ṗ - pop = [1..p-1] - ...i.e [[1^1,1^2,...,1^(p-1)],[2^1,2^2,...,2^(p-1)],...,[....,p^(p-1)]] % - modulo p µ - start a new monadic chain (call that list of lists X) Ƈ - keep those which: Ƒ - are invariant under: Q - de-duplicate Ḣ - head ị - index into the list of lists X ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ≔E…¹θ﹪Xι…¹θIθηE⊟Φη⁼¹№ι¹⪫E§η⊖ι◧IλL⊖θ ``` [Try it online!](https://tio.run/##TY3BDoIwEETvfkXDaUnqgZMHTgQ10UDS@AcNXWmT2kJb1L@vC1447WTnzcygZRi8tDk3MZrRQS8neEg3IlSczSVnvVeL9SD8BwMYznYmua2MCUiR1GV9EMG4tHUIP8HV2EQhzdllXqSNa6r1CxHUU5Vb6u7Nf7RJN6fwu9JnHAK@0CVUYFZISNXhM8G2ZunRoRuThj04//sKVtCtcz7l49v@AA "Charcoal – Try It Online") Link is to verbose version of code. Note: Trailing space. Explanation: ``` ≔E…¹θ﹪Xι…¹θIθη ``` Create a `p-1` by `p-1` array of powers of `1..p-1` to indices `1..p-1` (modulo `p`). ``` E⊟Φη⁼¹№ι¹ ``` Map over one of the rows which has exactly one `1`. ``` ⪫E§η⊖ι◧IλL⊖θ ``` Rearrange the rows into the order given by the selected row and format the output. [Answer] # [J](http://jsoftware.com/), ~~35~~ ~~32~~ 31 bytes ``` [:(/:0/:@{]\:#@~."1)]|^/~@}.@i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6009K0M9K0cqmNjrJQd6vSUDDVja@L06xxq9Rwy9f5rcqUmZ@QrpCmY/wcA "J – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~46~~ 43 bytes ``` Mod[PrimitiveRoot@#^Array[1##&,{#,#}-1],#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zc/JTqgKDM3sySzLDUoP7/EQTnOsagosTLaUFlZTadaWUe5VtcwVkc5Vu2/BlBhHlCBNReYoe@Q5qCsqabvAOLmpjoEJealp0Yb6ZjH/gcA "Wolfram Language (Mathematica) – Try It Online") -3 thanks to alephalpha [Answer] # [Zsh](https://www.zsh.org/), ~~117~~ 90 bytes ``` b=$1 c=(eval set -- '$[x**'{1..$[b-1]}%b\]) for ((;${#${(u)@}}-b+1;++x))$c for x;$c&&<<<$@ ``` ~~[Try it online!](https://tio.run/##VY5NCoMwEIX3c4pZTDFRIoylCEZPYl0EjBgoCtpSbcjZbeyub/V@vsX7rOPxHt3D4mJNjw83WY39DKt9olJIZ3EMQnrTCKmHeUGHwnOeU0uFKrogTdaIGDhN3YWKTgaIKEs4WSE0efKV4lClJmgpB6Q2y7YOiX/EjoIMsvRx2GOp67omc0cOR3RJ868EXtP5zOCGO/TzZOG4wg1KYAYu4Qs "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##VU5LCoMwFNy/Uzzoq0mUCKEUF1HwHtaF0ZQKoqC1DRXPnqp009kM84GZz/Tw70fbWRxt1WDX9lZjM8Bknygl0m4AP5TzJiMFdcbtq@rw12BUuDBki4pjKoxU5Xo2t1LAfRiRc03LiRY@i3xdpYmUjiInBNVH7DTVQZCmKeVewMYs@weDud9nDDpohu2Iv8AVElAKVAJf "Zsh – Try It Online") May God have mercy on my soul. There's a lot of bad practice all wrapped up here, let me explain the biggest offender at least: ``` c=(eval set -- '$[x**'{1..$[b-1]}%b\]) {1..$[b-1]} # brace expansion, expands immediately '$[x**' %b\] # string literals, expand during eval eval set -- # sets the positional parameters c=( ) # defines c to the words contained ``` Example for `b=4`: ``` c=(eval set -- '$[x**'{1..$[b-1]}%b\]) c=(eval set -- '$[x**'{1..3}%b\] ) # $[b-1] => 3 c=(eval set -- '$[x**1%b]' '$[x**2%b]' '$[x**3%b]' ) # brace expansion ``` Finally, where `$c` appears in the rest of the program, the array elements are evaluated as `eval set -- ....`. Lastly, `${#${(u)@}}` counts the unique elements int the positional parameters (i.e.: is there a cycle / are there `1`s?) Comments relevant to the 117 byte answer below. --- Challenges we have to overcome: * No multidimensional or nested arrays. Instead we print out the strings as we get them in a loop. * Options for testing if a given row has multiple 1s: + `${#${(M)a:#1}`: `:#` removes matching, and `(M)` reverses the match. So, this will expand to the number (`${# }`) of `1`s in the array. Unfortunately this expansion doesn't play nicely with the arithmetic for loop we use here. If it did, it could potentially save a byte. + `${${:-1}:*a}`: This is the set intersection between the singleton `1` and the set `a`. This will expand to the single `1` if it is found in the array. Using this option, we save one character here, but lose 1 overall having to put off adding the `1`s in the last row and column until the end. ``` f(){ # f [element] [modular base], puts powers up to n-2 into array $a a=() for i ({1..$[$2-2]}) a+=($[$1**i%$2]) } a=(1) # put 1 in a to force first loop iteration for ((;${${:-1}:*a};)) # test for 1 in array $a f $[++x] $1 # increment x, iterate through all elements mod $1 for y ($a 1){ # for all elements in the [last array, 1] f $y $1 # put that row in $a <<<$a\ 1 # print out $a with 1 appended (space-delimited string) } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~65~~ 57 bytes ``` {.[|.first(*.Set+2>$_)]}o{.&{@=(($++X**1..^$_)X%$_)xx$_}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi@6Ri8ts6i4RENLLzi1RNvITiVeM7Y2v1pPrdrBVkNDRVs7QkvLUE8vDigeoQokKipU4mtr/6flFylo5GTmpRZrKlRzKSjoqaXp5SYWAI0pTqzU5Kr9b85laAgA "Perl 6 – Try It Online") There's probably some way to just output the square itself, but this does the same process outlined in the question, sorting the lists by their positions in the first list that is just a permutation of 1 to input-1. Returns as a list of lists. BTW, there's a lot of jockeying around, trying to get around some of Perl 6's annoying limitations involving sequences vs arrays, and anonymous variables. ### Explanation: ``` $++ xx$_ # Map 0 to i-1 to ( X**1..^$_) # n, n^2, n^3... n^(i-1) ( X%$_) # All modulo i { }o{.&{ }} # Pass to the next function .[ ] # Index into that list of lists |.first( ) # The list of the first list that *.Set+2>$_ # Has all the elements in the range 1 to i-1 ``` [Answer] # JavaScript (ES7), ~~91~~ 86 bytes This version attempts to compute the powers before applying the modulo and will fail for \$p\ge11\$ because of loss of precision. It is otherwise using the same logic as the commented version below. ``` f=(p,k)=>(g=k=>[...Array(i=p-1)].map(_=>k**++i%p))(k).sort()[1]>1?g(k).map(g):f(p,-~k) ``` [Try it online!](https://tio.run/##FcxBCsIwEEDR0wgzrRnIShAm4jlKkVCbEFM7Q1IKbrx6tNvP47/87utUkm5mlefcWmDQc0Z2EDmzG4joXor/QGI1Fkd6e4UHu9x1fZ9OiggZqUrZAAc7OnuLRzhUxGv4z8w3Y5tkrbLMtEiEABfE9gM "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~92~~ 87 bytes This version uses modular exponentiation to support (much) higher input values. ``` f=(p,k)=>(g=k=>[...Array(p-1)].map(_=>n=n*k%p,n=1))(k).sort()[1]>1?g(k).map(g):f(p,-~k) ``` [Try it online!](https://tio.run/##PczLCsIwEIXhV@lGOiPtQHQnJOIzdFmLhF5CmzoJaSi48dVjq@Du43D4J73qpQ2jjyW7rk9pkOALi1KBkVaqmohuIegX@FJgQ0/t4SEVSz7agy9YCkSwSIsLEbAWjRJXsw/70eBl2Grl22JqHS9u7ml2BgY4nX@PkEmVhS/XnStFV8UwsgEkr7sq6q17RqTJjQx5/tedN6cP "JavaScript (Node.js) – Try It Online") ## How? ### Finding the first row Given \$1\le k<p\$, we use the helper function \$g\$ to compute \$a\_k(n)=k^n\bmod p\$ for \$1\le n<p\$. ``` g = k => // k = input [...Array(p - 1)] // generate an array of size p - 1 .map(_ => // for each entry in there: n = n * k % p, // update n to (n * k) mod p n = 1 // starting with n = 1 ) // end of map() ``` We look for \$k\$ such that there's only one value \$n\$ such that \$a\_k(n)=1\$. We do that by sorting the array and testing if the 2nd element is greater than \$1\$. ``` g(k).sort()[1] > 1 ``` This works even in lexicographical order -- which is the default behavior of [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) -- because: * if there are several \$1\$'s, they will all be moved to the front just like they would in numeric order * if there's only a single \$1\$, the 2nd value will be greater than \$1\$, no matter if it's really the 2nd value in numeric order or not *Example:* For [\$p=17\$](https://tio.run/##PczLCsIwEIXhV@lGOiPtQHAhCIn4DF3WIqGX0KZOQhoKbnz12Cq4@zgc/kmvemnD6GPJrutTGiT4wqJUYKSVqiaiWwj6Bb4U2NBTe3hIxZKP9uALlgIRLNLiQgSsRaPE1ezDfjR4GbZa@baYWseLm3uanYEBxPn3CJlUWfhy3blSdFUMIxtA8rqrot66J0Sa3MiQ53/deXP6AA): * for \$k=1\$, we get: + \$a\_1=[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]\$ + sorted as \$[ 1, \color{red}1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]\$ * for \$k=2\$, we get: + \$a\_2=[ 2, 4, 8, 16, 15, 13, 9, 1, 2, 4, 8, 16, 15, 13, 9, 1 ]\$ + sorted as \$[ 1, \color{red}1, 13, 13, 15, 15, 16, 16, 2, 2, 4, 4, 8, 8, 9, 9 ]\$ * for \$k=3\$, we get: + \$a\_3=[ 3, 9, 10, 13, 5, 15, 11, 16, 14, 8, 7, 4, 12, 2, 6, 1 ]\$ + sorted as \$[ 1, \color{red}{10}, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9 ]\$ ### Building the matrix Once we've found \$k\$, we invoke \$g(k)\$ again (to retrieve the unsorted version of the array) and invoke \$g\$ on each element of \$g(k)\$ to build the rows of the matrix. This part can be simply written as: ``` g(k).map(g) ``` [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` def f(p):R=range(1,p);return[m for m in[[[j**(k*i)%p for i in R]for k in R]for j in R]if sorted(m[0])==R][0] ``` [Try it online!](https://tio.run/##RY0xDsMgDEXncAovlSBiKKmqSomy9gCsiKFSoCVRHOTSoaenkAyd/Pz/sxy/6bVhl/PkPHgeRa9HeuDTcSWjGMilD6FZwW8EKwQ0xsxty5c2iFPc01BS0Lbi8sf5wODhvVFyE1/N2Ypx1LbM/dmdo@hZU2Wqsj/2JlLABMRYbbA2ppMXeZU3qZQtRj1kh5Z/ "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LεI<LmI%}ÐΘOÏн<è ``` -3 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##ASMA3P9vc2FiaWX//0zOtUk8TG1JJX3DkM6YT8OP0L08w6j/wrv/Nw) (the footer is to pretty-print the 2D list). **Explanation:** ``` L # Create a list in the range [1, (implicit) input] ε # Map each number `y` in the list to: I<L # Create a list in the range [1, input-1] m # Get number `y` to the power of each number in this list I% # Take modulo-input on each number }Ð # After the map: triplicate this modified matrix ΘO # Get the amount of 1s in each row Ï # And only leave the rows with exactly one 1 н # Then only leave the first row which contains a single 1 < # Decrease each value by 1 to make it 0-indexed è # And index each into the rows of the modified matrix to create a new matrix # (which is output implicitly as result) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes ``` (s=Thread@Mod[x^#&/@(x=Range[#-1]),#])[[#&@@Select[s,Sort@#==x&]]]& ``` [Try it online!](https://tio.run/##BcFBCoNADADArxQCi4JFevIUyAcKpXoLEYKGVagKaw77@3TmUN/sUN8XjYzR3DhtxXSl97VynSH11FT86pmN4fmStgNpmSERjfazxfnuxqs4AWJNIpLiU/bTHz1lHiTiDw "Wolfram Language (Mathematica) – Try It Online") [Answer] # APL(NARS), 29 chars, 58 bytes ``` {k←⍵∣⍺*⍳⍵-1⋄⊃{m∣k*⍵}¨⍳¯1+m←⍵} ``` test: ``` f←{k←⍵∣⍺*⍳⍵-1⋄⊃{m∣k*⍵}¨⍳¯1+m←⍵} 3 f 7 3 2 6 4 5 1 2 4 1 2 4 1 6 1 6 1 6 1 4 2 1 4 2 1 5 4 6 2 3 1 1 1 1 1 1 1 5 f 7 5 4 6 2 3 1 4 2 1 4 2 1 6 1 6 1 6 1 2 4 1 2 4 1 3 2 6 4 5 1 1 1 1 1 1 1 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes ``` n->lift(matrix(n-1,,i,j,znprimroot(n)^(i*j))) ``` [Try it online!](https://tio.run/##PYqxDoMwDAV/xWJ6Rs7ASBF8SiUGUhmBY1kZqv58Wga63enO19D08pZpbpaWQ3PFudbQNywNIiq7fMxDzyilwvgJ7XdmbrkElGYahEYh/9F1bVCeLrIKp@7R3ebIcP43nrh9AQ "Pari/GP – Try It Online") ]
[Question] [ *I know, I know, yet **another** primes challenge...* [Related](https://codegolf.stackexchange.com/q/94714/42963) A lonely (or isolated) prime is a prime number `p` such that `p-2`, `p+2`, `p-4`, `p+4` ... `p-2k`, `p+2k` for some `k` are all composite. We call such a prime a **`k`th-times-isolated prime.** For example, a 5th-times-isolated prime is `211`, since all of `201, 203, 205, 207, 209, 213, 215, 217, 219, 221` are composite. (`p-2*5=201`, `p-2*4=203`, etc.) ### Challenge Given two input integers, `n > 3` and `k > 0`, output the smallest `k`th-times-isolated prime that is strictly larger than `n`. For example, for `k = 5` and any `n` in range `4 ... 210`, the output should be `211`, since that's the smallest 5th-times-isolated prime strictly larger than the input `n`. ### Examples ``` n=55 k=1 67 n=500 k=1 503 n=2100 k=3 2153 n=2153 k=3 2161 n=14000 k=7 14107 n=14000 k=8 14107 ``` ## Rules * If applicable, you can assume that the input/output will fit in your language's native Integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 13 bytes ``` _æR+⁼ḟ ‘ç1#Ḥ} ``` [Try it online!](https://tio.run/##y0rNyan8/z/@8LIg7UeNex7umM/1qGHG4eWGyg93LKn9f3i5/qOmNd7//0ebmuooGMbqKESbGhhAWUaGIKYxhGlqDGUamhiAhM2R2BaxAA "Jelly – Try It Online") ### How it works ``` ‘ç1#Ḥ} Main link. Left argument: n. Right argument: k ‘ Increment; yield n+1. Ḥ} Unhalve right; yield 2k. ç1# Call the helper link with arguments m = n+1, n+2, ... and k until 1 one them returns a truthy value. Return the matching [m]. _æR+⁼ḟ Helper link. Left argument: m. Right argument: k _ Subtract; yield m-2k. + Add; yield m+2k. æR Prime range; yield the array of primes in [m-2k, ..., m+2k]. ḟ Filterfalse; yield the elements of [m] that do not occur in [k], i.e., [m] if m ≠ 2k and [] otherwise. The result to the left will be non-empty when m = 2k, as there always is a prime in [0, ..., 2m], since m > n > 3. ⁼ Test the results to both sides for equality. This yields 1 iff m is the only prime in [m-2k, ..., m+2k]. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ḟ§=;ofṗM+ṡD⁰→ ``` [Try it online!](https://tio.run/##ASUA2v9odXNr///huJ/Cpz07b2bhuZdNK@G5oUTigbDihpL///8x/zU1 "Husk – Try It Online") ## Explanation Pretty straightforward. ``` ḟ§=;ofṗM+ṡD⁰→ Inputs are k and n. → Increment n ḟ and find the first number m >= n+1 such that: ṡD⁰ Take symmetric range [-2k,..,2k]. M+ Add m to each. ofṗ Keep those that are prime. §= Check equality with ; the singleton [m]. ``` [Answer] # Java 8, ~~144~~ 143 bytes ``` (n,k)->{for(k*=2;;)if(p(++n)>1){int i=-k;for(;i<=k&p(n+i)<2|i==0;i+=2);if(i>k)return n;}}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;} ``` **Explanation:** [Try it online.](https://tio.run/##pdBBb8IgFAfwu5/iXbbAWmupVhMRPe04Lx6XHVjFBWtfmxbdFtfP3kHVLC5Gs@wCecDvwZ@13MluXihcL9Mm2ciqgiepcd8B0GhUuZKJgrkr2wVIiBvRb4uUcrtRd@wwBwQBDUE/pd3pfpWXJH0QEedUr0hBPA/plNG9U1p0U@4OcD0R6X1B0NN0En1pIUKuPRFRbo2eprRUZlsiIK9r7mRxuJy27Q@tItsEOQq80543YbNwjJT/uAag2L5udAKVkcZOu1wvIbMJycKUGt@eXyQ9pHOxIbMhUL23BWnTASw@K6OyIN@aoLDEbJBkAQYJiWOfUcrdmV4PHj8KlRi1HMNwdMOF4QmeuTjsX4cRs7LfyjMYsfimjPuX5ZBdlwM/Pmb8LdnNx57oXyG7CGfXGRuE9ndGDp4xNmDh6H@07tTNNw) ``` (n,k)->{ // Method with two integer parameters and integer return-type for(k*=2; // Multiply `k` by 2 ;) // Loop indefinitely if(p(++n)>1){ // Increase `n` by 1 before every iteration with `++n` // And if it's a prime: int i=-k;for(;i<=k // Loop `i` from `-k` to `k` (inclusive) &p(n+i)<2|i==0; // As long as `n+i` is not a prime (skipping `n` itself) i+=2); // And iterate in steps of 2 instead of 1 if(i>k) // If we've reached the end of the loop: return n;}} // We've found our result, so return it // Separated method to check if `n` is a prime // `n` is a prime if it remained unchanged, and not when it became 0 or 1 int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;} ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ 104 bytes -1 byte thanks to ovs ``` n,k=input() n+=1 while sum(all(x%i for i in range(2,x))^(x==n)for x in range(n-k*2,2*k-~n)):n+=1 print n ``` [Try it online!](https://tio.run/##RcyxCsIwEAbgvU9xi3BX06FXXIS8itCh2iPxb4gpxsVXj@ji/MGXXmXdoK3BBW9Ie2HpcPRj91wtLvTY7zzHyPVgdN0yGRkoz7gtrK6KXLh6D/lS/ROG0KvTPgxviJx/X8qGQmhNx9PkaPoA "Python 2 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` åΣ▀ë F▬&■º↔╔^∞ ``` [Run and debug it](https://staxlang.xyz/#p=86e4df8920461626fea71dc95eec&i=1+55%0A1+500%0A3+2100%0A3+2153%0A7+14000%0A8+14000&a=1&m=2) This is the corresponding ascii representation. ``` w^x:r{Hn+|p_!=m0# w while; run the rest of the program until a falsy value remains ^ increment candidate value. x:r [-x, ..., -1, 0, 1, ... x] where x is the first input { m map using block, using k from -x to x Hn+ double and add to candidate value - this is "p+2k" |p is it prime? produces 0 or 1 _! k is zero? = two values are equal; always true for a passing candidate 0# any falses left after mapping? if so, continue running ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~94~~ ~~92~~ 89 bytes ``` f=(n,k)=>(Q=y=>y<-k||(P=(a,b=2)=>a>b?a%b&&P(a,b+1):1)(n+2*y)^!!y&&Q(--y))(k,++n)?n:f(n,k) ``` [Try it online!](https://tio.run/##dczRCoIwFIDh@97Ci8Y5bYtNk0KavoK@QDDNRU22yAgGvvuyLsNuP37@m37psXtc70/u/LmP0ShwzKIqoVFBleHI7TRBrUCzVqWz67Kt9LolpP4QlVhIBEfTTcBTkgRCGuA8IIJllDqsXGG@x9h5N/qh3w7@AgbynEnE1Q8KsaCpnDlb4DxbYLkTc77/4wfE@AY "JavaScript (Node.js) – Try It Online") ~~Mysteriously, further golfs end up stack overflow. Only this works at the size of 14000.~~ Finally one golf that won't end up stack overflow at 14000. **Explanation** ``` f=(n,k)=> // Two inputs (Q=y=> // Function checking whether all numbers in // [n-2*k, n+2*k] except n are all composite y<-k // The counter runs from k to -k // If none breaks the rule, return true ||(P=(a,b=2)=> // Function checking primality a>b? // Check if a>b a%b&&P(a,b+1) // If a>b and a%b==0 return false, else proceed :1 // If a<=b return 1 (prime) )(n+2*y)^!!y // If n+2*y is prime, then y must be 0 // If n+2*y is not prime, then y must be non-zero // If none of the conditions are met, return false &&Q(--y) // Else proceed to the next counter ) (k,++n)? // Add 1 to n first, then start the check n // If conditions are met, return n :f(n,k) // Else proceed to the next n. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 113 bytes ``` P(n,d,b){for(b=d=n>1;++d<n;)b=b&&n%d;n=b;}f(n,k,i,f){for(f=n;f;)for(f=i=!P(++n);i++<k;f|=P(n+i+i)|P(n-i-i));f=n;} ``` [Try it online!](https://tio.run/##hcxBCsIwEIXhtZ4iCkqGpJBYY4UxegUP4MY0RAZxFHHX9uw1UsFdXc2/@ObVxaWu@/4oWUcdoEn3pww@et5bVCruGCH4sFzyIiL7gF3K8qpJp8Emz5gQhiQ/O0qlGJCU2l0xtT4PK1IEbY6CCgLAz0vX387EEprp5PEkfiU5X7goDl7kc@K5TlII4Zy2oHNsKsAx6YwZpDPlqFzZLMssV9b9k678yo0dk3Zt8mYF2q6tqf7L7U92/Rs "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) + `-rprime`, ~~73~~ ~~71~~ ~~61~~ 57 bytes ``` ->n,k{n+=1;(-k..k).all?{|i|(i*2+n).prime?^(i!=0)}?n:redo} ``` [Try it online!](https://tio.run/##VdDRaoMwFAbg@z7Fv4Cga5REmzo6rA8iDlwTmeiiGIWN2lefi7Pt6N3hO//5L04/vn/PZTL7R03rs94m/NX16yCovaBomvQ8VZNbPYdb7QVdX32q9M2tnhLmXVJ96JVsL3O2ATIAQlBwagfs45yuKBi7omDRFUO@YGQx5OIfRXTDPV@R79iSjG3DjrP4AV9uuMkDVZw@IFtMmqKmUF@dOg1KTjbeKzM2AxKU2bLMLXXjYEAcISkcieQIO8J1jEfgIFsr1jN6P0/upUhBusIYggNIWVQNyTdKy/mn7Yaq1Wb2@783/QI "Ruby – Try It Online") It feels good to be learning! I'm ~~using the `Integer#[]` and `redo` techniques that I learned here on PPCG.~~ getting lost in the weeds of fun techniques... -1 byte: Use `n%2` instead of `n[0]` to get the least significant bit. Thanks, [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid)! -1 byte: Use a ternary operator instead of a boolean expression. Thanks, [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid)! -10 bytes: Use the XOR operator to avoid typing out `.prime?` twice... This is just as much [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid)'s answer as mine now :) -4 bytes: There's no harm in checking even values of `n`. [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid) is non-stop. Ungolfed: ``` ->n,k{ n += 1; # Increment n (-k..k).all?{|i| # In the set [n-2*k, n+2*k], is every number (i*2+n).prime? ^ (i!=0) # EITHER prime XOR different from n itself? } ? n # If yes, return the current value of n : redo # Otherwise, restart the block } ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 55 bytes ``` f(n,k)=until(isprime(n++)&&#primes([n-2*k,n+2*k])<2,);n ``` [Try it online!](https://tio.run/##TcrNCsMgEATgV1lSCG5VUFNpoT8vIh6kNEViFknSQ5/emjaHXoZvhslhivKZS@kZiQGvL1piYnHOUxwfjDjHtt19y8wcSbMfBPGaHi9G4JlKyDm9WQB5g3qjpbJZSwP3kBLrBQREAc5ZK0D7KqvUJqNXdj/abqM@qHU@/vnkPZYP "Pari/GP – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 63 bytes ``` {$^k;first {[grep *.is-prime,$_-2*$k..$_+2*$k]eqv[$_]},$^a^..*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/WiUu2zots6i4RKE6Or0otUBBSy@zWLegKDM3VUclXtdISyVbT08lXhvEiE0tLItWiY@t1VGJS4zT09Oq/W/NVZwIMkrD1FRHwVATwTUwQOEbGYIEjJEFTI1RBAxNDEBKzDFELDSt/wMA "Perl 6 – Try It Online") ]
[Question] [ *Clarification: Basically, you need to make [this](https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/p/euler-totient-exploration)* Euler's totient function has the name phi. Let's try to calculate phi(8) First, list all numbers 8 and under backwards, not including 0 or under ``` 8 7 6 5 4 3 2 1 ``` Now find which numbers don't share a factor with 8 (1 doesn't count), and place a `#` in their place. ``` 8 # 6 # 4 # 2 # ``` Remove the numbers. ``` # # # # - ``` Now do this, but string the outputs together in a triangle ``` 9 88 777 6666 55555 444444 3333333 22222222 111111111 --------- 123456789 ``` `#` out non-factor sharing numbers ``` 9 8# 7## 6#66 5#### 4#4#4# 3##3##3 2#2#2#2# ######### ``` Remove numbers: ``` # ## # #### # # # ## ## # # # # ######### ``` This would be the output for input 9 (since 9 columns.) Leading + trailing newlines allowed. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 15 bytes ``` :Gq:!Zd1=RP35*c ``` [**Try it online!**](http://matl.tryitonline.net/#code=OkdxOiFaZDE9UlAzNSpj&input=OQ) If a leading newline is acceptable: **13 bytes**: ``` :t!Zd1=RP35*c ``` ### Explanation ``` : % Take input N. Generate row vector [1 2 ... N] Gq: % Row vector [1 2 ... N-1]. % (In the 13-byte version this is replaced by function `t`, which duplicates % the array [1 2 ... N]) ! % Transpose into column vector Zd % GCD, element-wise with broadcast. Gives (N-1)×N matrix 1= % True for entries that equal 1, corresponding to relatively prime pairs. % The rest of entries are set to false, i.e. 0. R % Upper triangular part: set values below diagonal to 0 P % Flip matrix vertically 35* % Multiply each entry by 35 (ASCII for '#') c % Convert to char. 0 will be displayed as a space. Implicitly display ``` [Answer] # Jelly, ~~20~~ 18 bytes ``` RR⁶”#g’¥?€"Rz⁶U'j⁷ ``` [Try it online!](http://jelly.tryitonline.net/#code=UlLigbbigJ0jZ-KAmcKlP-KCrCJSeuKBtlUnauKBtw&input=&args=OQ) [Answer] # Pyth - 22 bytes Will try to golf further. ``` j_.tmsm@"# "n1idkSdSQd ``` [Try it online here](http://pyth.herokuapp.com/?code=j_.tmsm%40%22%23+%22n1idkSdSQd&input=9&debug=0). [Answer] ## JavaScript (ES6), 112 bytes ``` n=>[...s=` `.repeat(n)].map(_=>s.replace(/./g,_=>`# `[+g(n+1,i++)],n-=i=1),g=(i,j)=>i?i>j||g(j%i,i):j>1).join`\n` ``` Where `\n` represents the literal newline character. Alternative solution, also 112 bytes: ``` n=>(s=`# `.repeat(n)).replace(r=/../g,_=>s.replace(r,m=>m[+g(n+1,i++)],n-=i=1)+` `,g=(i,j)=>i?i>j||g(j%i,i):j>1) ``` [Answer] # Java, ~~162~~ 158 bytes ``` int g(int a,int b){return a<1?b:g(b%a,a);} String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;)r+=i+j<n|g(n-i,j++)>1?" ":"#";r+="\n";}return r;} ``` Full program (not updated) ``` import java.util.Scanner; public class Q79082 { int gcd_ungolfed(int a,int b){ if(a==0) return b; return gcd_ungolfed(b%a,a); } void draw_ungolfed(int n){ for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(i+j<=n || gcd_ungolfed(n+1-i,j)!=1){ System.out.print(" "); }else{ System.out.print("#"); } } System.out.println(); } } int g(int a,int b){return a<1?b:g(b%a,a);} String d(int n){String r="";for(int i=0;i<n;i++){for(int j=1;j<=n;j++)r+=(i+j<n||g(n-i,j)>1)?" ":"#";r+="\n";}return r;} public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); new Q79082().draw_ungolfed(n); System.out.println(new Q79082().d(n)); } } ``` Input/output: ``` 9 # ## # #### # # # ## ## # # # # ######### # ## # #### # # # ## ## # # # # ######### ``` [Answer] # SQL (PostGreSQL9.4), 239 ~~291~~ bytes Creates a prepared statement that can be executed. I'm sure I can probably take quite a few bytes out of this, but I'll have to pick away at it later. Does a cross join on a range of 1 to n. Calculates the GCD in a lateral join. Where the GCD is 1 and the series A is greater than series B output a '#' otherwise a space. Aggregate the results up into a string grouped by series B. ``` prepare p(int)as select string_agg(coalesce(CASE WHEN b<=a AND x=1THEN'#'END,' '),'')from generate_series(1,$1)a,generate_series(1,$1)b,LATERAL(SELECT MAX(G)x FROM generate_series(1,LEAST(a,b))g WHERE a%g+b%g=0)g group by b order by b desc ``` Run in the following way ``` execute p(13) string_agg ---------------- # ## # # ## # # # # ###### # # # #### ### # # # # # ## ## ## # # # # # # # ############# ``` And cleaned up with ``` deallocate p ``` [Answer] # Ruby, 84 bytes ``` ->n{s=[];n.times{|i|j=0;m=n-i;s<<(?#*n).gsub(/./){m.gcd(j+=1)>1||m>j ?' ':$&}};s*$/} ``` [Answer] ## Python 2 (120 bytes) ``` g=lambda m,n:m if n<1 else g(n,m%n) r=range(input()) for i in r[:0:-1]:print''.join('# '[i>j+1 or g(i,j+1)>1]for j in r) ``` ]
[Question] [ Implement a [CipherSaber](http://en.wikipedia.org/wiki/CipherSaber) encryption program, as described below. Guidelines: * The smallest entry, in bytes, wins. + However, in a departure from [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") norms, you are welcome to post interesting entries, even if they aren't serious golf entries. * An entry would typically be a program that takes the plaintext from standard input, and writes the ciphertext to standard output, with the key specified (by the user) in some way you prefer. + However, if you wish to implement this as a procedure, that is fine too. * The IV must come from a cryptographically secure pseudorandom number generator. If your language doesn't support that, choose a different one. ;-) * Please do not use any crypto-specific libraries, system calls, or instructions (other than the PRNG, as stipulated above). Of course, generic low-level bitwise operations are okay. CipherSaber is a variant of RC4/Arcfour, so I'll start by describing the latter, then the changes CipherSaber makes thereto. # 0. RC4/Arcfour [Arcfour is fully specified elsewhere](http://tools.ietf.org/id/draft-kaukonen-cipher-arcfour-03.txt), but for completeness, I'll describe it here. (In case of any discrepancies between the Internet-draft and this description, the former is normative.) ## Key setup Set up two arrays, `S` and `S2`, both of length 256, where `k_1` is the first byte of the key, and `k_n` is the last. ``` S = [0, ..., 255] S2 = [k_1, ..., k_n, k_1, ...] ``` (`S2` is filled with the bytes of the key, again and again, until all 256 bytes are filled up.) Then, initialise `j` to 0, and shuffle 256 times: ``` j = 0 for i in (0 .. 255) j = (j + S[i] + S2[i]) mod 256 swap S[i], S[j] end ``` This completes key setup. The `S2` array is no longer used here, and can be scrubbed. ## Cipher stream generation Initialise `i` and `j` to 0, then generate the key stream as follows: ``` i = 0 j = 0 while true i = (i + 1) mod 256 j = (j + S[i]) mod 256 swap S[i], S[j] k = (S[i] + S[j]) mod 256 yield S[k] end ``` ## Encrypting/decrypting data * To encrypt, XOR the keystream output with the plaintext * To decrypt, XOR the keystream output with the ciphertext # 1. CipherSaber CipherSaber (which is what we're implementing in this question) is a variation of RC4/Arcfour in two ways: ## 10-byte IV/nonce When encrypting a message, 10 random bytes should be obtained, such as via `/dev/urandom`, and be written into the first 10 bytes of the encrypted output. When decrypting a message, the first 10 bytes of the input is the IV used to encrypt it. The RC4/Arcfour key setup stage is run with `passphrase || IV` as the key, where `passphrase` is the user-specified passphrase, `IV` is as described above, and `||` is concatenation. So, a passphrase of "Hello, world!" and an IV of "supercalif" (however unlikely that is :-P) would result in a key of "Hello, world!supercalif". ## Multiple iterations of key setup In order to help prevent the vulnerability that made WEP encryption completely broken, the shuffling loop of the key setup stage of RC4 is run a user-specified number of times. The value of `j` should be retained between iterations. # 2. Test vectors Here are some [test vectors](http://www.cypherspace.org/adam/csvec/) you can use to test your programs. Furthermore, [squeamish ossifrage](https://codegolf.stackexchange.com/users/11006) created a [CipherSaber encryption & decryption tool](http://ruletheweb.co.uk/cgi-bin/saber.cgi) that you can use to validate your results. You only need to implement the encryption program. You do not need to supply the decryption program, but your encryption program's output must roundtrip correctly to the original input when processed with a correctly-implemented decryption program using the correct key. [Answer] # Pyth, 100 bytes ``` $import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw ``` This script uses the `$` command, which allows executing Python code. To prevent executing malicious code on the server, the this command is disabled in the online compiler. You have to run it with the off-line compiler which you can find [here](https://github.com/isaacg1/pyth). The input is in the format: ``` secret key 5 (number of repeats) secret message ``` The program outputs the encrypted string, which might contain unprintable chars. If you want to verify it using the [CipherSaber Encryption & Decryption Tool](http://ruletheweb.co.uk/cgi-bin/saber.cgi), you can use the following code, which converts the string to a series of hexadecimal digits. ``` $import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0 jdm.[2.HCd`0 sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw ``` Pyth doesn't support cryptographically secure pseudorandom numbers and importing them from Python costs 25 bytes. A shorter code, which uses Pyth's/Python's normar pseudorandom-number generator and also works in the online compiler is: ``` KmO=b256TJuuXN@LN,T=+Z+@NT@+CMzKT)bGQUb=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw ``` Try it online: returning a [string](http://pyth.herokuapp.com/?code=KmO%3Db256TJuuXN%40LN%2CT%3D%2BZ%2B%40NT%40%2BCMzKT%29bGQUb%3DZ0sCM%2BK.exCb%40%3DXJ%3DN%40LJ%2Chk%3D%2BZ%40Jhk%29sNw&input=53cr37%20k3y%0A5%0AA%20good%20glass%20in%20the%20bishop%27s%20hostel%20in%20the%20devil%27s%20seat%20twenty-one%20degrees%20and%20thirteen%20minutes%20northeast%20and%20by%20north%20main%20branch%20seventh%20limb%20east%20side%20shoot%20from%20the%20left%20eye%20of%20the%20death%27s-head%20a%20bee%20line%20from%20the%20tree%20through%20the%20shot%20fifty%20feet%20out.&debug=0) or a [series of hexadecimal digits](http://pyth.herokuapp.com/?code=KmO%3Db256TJuuXN%40LN%2CT%3D%2BZ%2B%40NT%40%2BCMzKT%29bGQUb%3DZ0%0Ajdm.[2.HCd%600%0AsCM%2BK.exCb%40%3DXJ%3DN%40LJ%2Chk%3D%2BZ%40Jhk%29sNw&input=53cr37%20k3y%0A5%0AA%20good%20glass%20in%20the%20bishop%27s%20hostel%20in%20the%20devil%27s%20seat%20twenty-one%20degrees%20and%20thirteen%20minutes%20northeast%20and%20by%20north%20main%20branch%20seventh%20limb%20east%20side%20shoot%20from%20the%20left%20eye%20of%20the%20death%27s-head%20a%20bee%20line%20from%20the%20tree%20through%20the%20shot%20fifty%20feet%20out.&debug=0) The code is nothing special. Just a lot of dirty assignments and immediate reuses of computed results and applying twice the [list-swap](https://codegolf.stackexchange.com/a/49162/29577) trick. ### Explanation: ``` implicit: z = 1st input (= key string) Q = 2nd input (number of repetitions) $import os$KsM$os.urandom(10)$ $import os$ import Python's os module $os.urandom(10)$ create 10 cryptographically secure pseudo-random bytes sM convert them to ints K store them in K JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256 =b256assign b with 256 u QUb start with G = [0, 1, ..., 255], evaluate the following expression Q times and update G with the result each time: u bG start with N = G, for each T in [0, 1, ..., 255] evaluate the following expression and update N each time: CMz convert key to list of ints + K extend it with K @ T take the Tth element (modulo length) @NT take the Tth element of N + add these two values +Z add Z (with is initially 0) = and update Z with the result ,T Z make the pair of indices [T, Z] @LN look-up their values in N XN ) and switch these two values in N J assign the result (the key setup) to J =Z0 set Z to 0 sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw w read a string from input (message) .e map each index k, char b in message to: @Jhk look-up the (k+1)th element in J =+Z add it to Z and update Z ,hk Z make the pair of indices [k+1,Z] @LJ look-up their values in J =N assign the result to N XJ N ) swap these values in J = and update J with the result @ J sN take the sum(N)th element of J Cb convert b to int x bitwise xor of these two elements +K insert K at the beginning CM convert each element to char s sum them (generate a string) implicitly print ``` [Answer] # Python 2 - 373 ~~350~~ ~~326~~ 317 bytes Pyth possibly coming later. Defines one function, `c(p,d,r,m)` which takes byte lists for passphrase and data, and int for repetitions and mode which encrypts when 1 and decrypts when 0. This is because the only difference in them is dealing with the IV. Returns byte list. ``` import os B=256 def c(p,d,r,m): if m:v=map(ord,os.urandom(10)) else:v,d=d[:10],d[10:] p+=v;S=range(B);T=(p*B)[:B];j=0;exec"for i in range(B):j=(j+S[i]+T[i])%B;S[i],S[j]=S[j],S[i]\n"*r;o=[];i=j=0 for b in d:i=-~i%B;j=(j+S[i])%B;S[i],S[j]=S[j],S[i];k=(S[i]+S[j])%B;o+=[S[k]^b] return v+o if m else o ``` Here is some test code / Helper functions: ``` phrase = "hello" text = "Mary had a little lamb, little lamb, little lamb" N = 5 def make_bytes(string): return map(ord, string) def make_string(bytes): return "".join(map(chr, bytes)) def make_hex(bytes): return " ".join("%02x" % i for i in bytes) def from_hex(hex_str): return [int(i, 16) for i in hex_str.split()] cipher = c(make_bytes(phrase), make_bytes(text), N, 1) print make_hex(cipher) plain = c(make_bytes(phrase), cipher, N, 0) print make_string(plain) ``` [Answer] ## Ruby - 263 chars This is my Ruby answer to the original question on stackoverflow back in 2010! It is a encoder and decoder all in one program Parameters are: e or d (for encode or decode) key number of times ``` $ ruby saber.rb e gnibbler 10 < in.txt | ruby saber.rb d gnibbler 10 o,k,l=ARGV;print o<'e'?(v=STDIN.read(10))*0:v=(0..9).map{rand(256).chr}.join;j=0;E=255 S=Array 0..255;(S*l.to_i).each{|i|j=j+S[i]+((k+v)*E)[i].ord&E;S[i],S[j]=S[j],S[i]};i=j=0 STDIN.each_byte{|c|i=i+1&E;j=j+S[i]&E;S[i],S[j]=S[j],S[i];print (c^S[S[i]+S[j]&E]).chr} ``` [Answer] # C, 312 bytes Accepts a key and key mixing iteration count on the command line, then encrypts everything on stdin to stdout. This uses the BSD/Darwin library function `arc4random()`, which is a PRNG based on RC4. It automatically seeds itself, so the results will be different every time. ``` unsigned char n,i,j,q,x,t,s[256],k[256];main(int c,char**v){for(strcpy(k,v[1]),n=strlen(k);x<10;x++)putchar(k[n++]=arc4random());do{s[i]=i;}while(++i);for(x=atoi(v[2]);x--;)do{t=s[i];s[i]=s[j+=s[i]+k[i%n]];s[j]=t;}while(++i);for(;(c=getchar())>0;){q+=s[++i];t=s[i];s[i]=s[q];s[q]=t;t=s[i]+s[q];putchar(c^s[t]);}} ``` Tidier version: ``` unsigned char n,i,j,q,x,t,s[256],k[256]; main(int c,char**v) { for (strcpy(k,v[1]),n=strlen(k);x<10;x++) putchar(k[n++]=arc4random()); do { s[i]=i; } while(++i); for (x=atoi(v[2]);x--;) do { t=s[i]; s[i]=s[j+=s[i]+k[i%n]]; s[j]=t; } while (++i); for (;(c=getchar())>0;) { q+=s[++i]; t=s[i]; s[i]=s[q]; s[q]=t; t=s[i]+s[q]; putchar(c^s[t]); } } ``` ### Example: ``` $ echo -n 'Ciphersaber' | ./csgolf 'hello' 20 | xxd -p 0f6257c330e5e01c3eab07bc9cb4ee4c3eaa514a85 ``` [Answer] ## Python - 266 chars This is my Python answer to the original question on stackoverflow back in 2010! It is a encoder and decoder all in one program Parameters are: e or d (for encode or decode) key number of times ``` $ python saber.py e gnibbler 10 < in.txt | python saber.py d gnibbler 10 ``` This version attempts to merge the 2 loops of the rc4 into one (saves 11 bytes so far...) ``` import os,sys;X,Y=sys.stdin.read,os.write;_,o,k,l=sys.argv;p='d'<o V=(X,os.urandom)[p](10);Y(1,V*p);E,S=255,range(256) for q in S*int(l),X(): t=q<'';j=0;i=-t for c in q:i=i+1&E;j=j+S[i]+t*ord(((k+V)*E)[i])&E;S[i],S[j]=S[j],S[i];t or Y(1,chr(ord(c)^S[S[i]+S[j]&E])) ``` ]
[Question] [ When one performs a search query using [Google](https://www.google.com), one of the first things you see is an approximation of how many results were found. Today, you'll be simulating this in as few bytes as possible. ## Input A short string of length at most 10 with characters from a-z. ## Output The approx count that Google reports for the number of hits. ## Test Cases ``` query string -> approximate number of results fish -> 2340000000 quantock -> 1390000 codegolf -> 891000 google -> 9340000000 e -> 22500000000 bzoea -> 34700 zoea -> 529000 ``` ## Extra Clarifications You may use any regional Google you like. You can either scrape the page resulting from the search query, or interface with Google APIs. Search queries are usually in the format `https://www.google.com/query?q=<query>` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Python 3](https://docs.python.org/3/), ~~158~~ ~~137~~ 131 bytes Using [`requests`](https://requests.readthedocs.io/) module and a doctored User-Agent header. Still looking for a shorter functioning UA header. ``` lambda q:get(f'http://goo.gl/search/{q}',headers={'User-Agent':'Firefox/8'}).text.split('out ')[1].split()[0] from requests import* ``` [Try it online!](https://tio.run/##pZRLj5swEMfP9aew9lCHyuGRF7s0ibSHXWkP7V62p21U8RjAKtjENtukUT57akhQqqoNlTISlj2e8Q/w/Kfa6lzw8SFdfD0UYRklIV4HGehBSnKtq8BxMiHsrHAUhDLOnd16T2gOYQJSLXbkiwI5vM@AaxKQRyYhFRvnluwtW8NG26oqmB4QUWtMrFdvdXJYr@4KpVKUWMK6BqUVZmUlpP5waL01Z1obt12K@PtpC38yc4RMuNx@y3VZ4AXeoXckZSonASbzhL1hlixuJKi60EOlQ61ulvdRAx/RietS9/jgY4SacxHJJR649szFCmLBE2W955GqPs6ddm/umENPI6EGtq5Drs179AI9Ovb/AfNnl2AtJhYJZKJIezG3s@nfISO/F2LuNSug/0tcOvIv/LvppJfUDxl51Btdgri9kOingLAXNJ7Qu6sq4L8o/ti7stBi8caSoXfXj6Le9OrK3iNkJG8EdeoAtSwo7kT@WXAIWvUNGk0vzgq0mz5hYjuZO0bjQ29FMSGWhZCW2wBhYz9yVgB@kTUc141pkKUBMl7Vph@c3V1OZ5VkvGlGuyZhj4dLvEsHzdzak3MabGKoNH7iCWwepBTyj0NCpdAp5uH58beIZufQtBDUSRt14kNHgSBAbWmhduju5Rc "Python 3 – Try It Online") [Answer] # Bash + curl + grep, 61 ``` curl -LA Firefox/8 goo.gl/search?$1|grep -Po "bout \K[0-9,]*" ``` This will output `curl`'s progress indicator to stderr. If you want to suppress that, change the `-LA` to `-sLA`. [Answer] # Applescript, 389 This is perhaps the most inefficient golfing language, but it is still fun to golf in: ``` open location"http://goo.gl/search?"&(display dialog""default answer"")'s text returned repeat with l in{"a","c"} delay 2 tell application"System Events"to keystroke l using command down end delay 1 set d to the clipboard set Applescript's«class txdl»to" " set c to d's text items set p to"" repeat with w in c considering case if p contains"About"then display alert w end set p to w end ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ ~~61~~ ~~56~~ 75 bytes ``` iwr goo.gl/search?$args -User Firefox/8|sls '(?<=">About )[\d,]*'|% M*|% V* ``` [Try it online!](https://tio.run/##nVVrU9pAFP2eX3GHogEbJEQeOgTU2nHGD46t9PHBOp08LiE17IbdjY@iv51uXggdiCAzMMk9u/cc9t57NqQPyPgIg2BWHkIPpjP/gYFH6b4X1DlazBkdly3mcah958jg3Gc4pI/1w2cecFArx2av1D@1aSSgevPL1W731OcduNyTPz/2Zi@K8gEuqXMHQ8pAjBBCKh8s4s4D3y6ulPJYLkH3GnlICUcudZxMFQXkR12WknF9bBqqXKSaPgkl870VRNgr7U4iKrqZmqZR6puufw@@2ysx5FEgalxYgudyGy1Nb@uaridfSJdwk1Cb9aGi77fawNGhxOXVXWLzsGvWE8ysy6x9k4cWmVPBMwxGPhPUd816gqjdVfLXa99Q85GxXnCz9bbgTwmNDvZTrPpz5HlQgwGNiHsW0KhY/NDnoxXK4/Absg2tqRecdFvf4qRjOmRjJIVaJ5FFhGyqVG@SpvBctYPOGnGdwjZYze5QFz0aDDdkP2y3VnMbne255ZsX4Kb/W9eMTtEMNLcXsCm30dAaRhG3vj23/ZeitSH/QVM7ekc3FrBvQd45aLxrFnJ2aazDiDjCpwQuyD29w9pl4qE/0b7GSYRcKNNEY2gxa1wpR8yvJu83XwZnERd0fGX/QUfcnkzhjBKBREjl/xvxTbzv9kVJfLx2TpmDIKhU7eLQJ5gYuB35gfAJWIFvcZC3hzJAUTvN39bJy9IpyklFUbSKuuDsGqjL5qxW4xWL8KsPpljiTRJYcpoUmltBvC@f8xSaz6mEsiFMgWyI4h1LE5KiCbDcvpnCpAMkmPZWGsxjWcllUKnK@2IH0vqU5Wmwp4FgPvE0KONjKKuCblyM3@kVWE6bREZ25RW9uH5dQQeR4yCPr9F8bw0nr7m7cJ1nzPAufH3NGocXSECWf/YP "PowerShell – Try It Online") The correct solution is `parseHtml` method and `xPath` query `div[@id="result-stats"]` of course. But we are in CodeGolf! So let's look for a shorter code :) The CodeGolf solution is based on the following: * the search string contains chars `"` and `>` * this chars are regular for `regex` and special for `Html` * any Html document should to escape this chars in `value` attributes and in the inner text - `&quot;` and `&lt;` * so we can found the string `">About` only in a Raw content of a Html page. --- Less golfed: ``` Invoke-WebRequest goo.gl/search?$args -UserAgent Firefox/8| Select-String '(?<=">About )[\d,]*'|% Matches|% Value ``` The script assumes the English locale is default. The script returns a string same format as Google itself, So comma as thousand separators is fine. See comment from author `Anush`. `iwr` is the alias for [Invoke-WebRequest](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest). `M*` is shortcut for the `Matches` method and `V*` is shortcut for the `Value` method. --- * Thanks @MarcMush for the brilliant question! * Thanks to [mhawke](https://codegolf.stackexchange.com/a/217924/80745) for `Mock for TIO` idea. [Answer] # [Go](//golang.org), 260 bytes Most answers on this page are now wrong, as Google no longer accepts `Firefox/8` as a valid User-Agent: ``` package main import(."io" ."net/http" ."regexp") func main(){e,_:=NewRequest("GET","http://goo.gl/search?codegolf",nil) e.Header.Set("User-Agent","Firefox/51") s,_:=new(Client).Do(e) b,_:=ReadAll(s.Body) print(string(MustCompile(`About \S+ results`).Find(b)))} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~26~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ’й.ŒŒ/€±?q=ÿ’žZì.w”€«”¡1è#1è ``` +1 byte as bug-fix if the input is `about`. +3 bytes, because it apparently doesn't work without the `www.` Outputs the result in the same format as on the Google page itself (so with dots for thousand separators). If it should be returned as an integer, an additional trailing `þ` can be added to the program. Builtin `.w` (read data from an URL) is disabled on TIO, so the TIO's are split into two parts: Creating the Google search URL based on the input: ``` ’й.ŒŒ/€±?q=ÿ’žZì ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcPMowsO7dQ7OunoJP1HTWsObbQvtD28HyS8L@rwmv//0zKLMwA) Get the amount of results from the Google page: ``` ”€«”¡1è#1è ``` [Try it online.](https://tio.run/##1TvZcqPIlu/1FTirwwVthEHyCsYOeaty2a7NS7na7fFNyJSEjAQFaLOsiIn5j3mYt4mY@Yo7f3J/pOecBCS02F01MffGTHRbQObJs@VZEyqIqePxP/742z//69/@5T//@h9w/eu/Gf/176/h748/CCGvdpZY4CaDkEuNpOXv7uCv5CW8FbtByG1CxAMC2KSRJKG5uhq7Dd6iWhDVVy84jdzGFx53/CT@ROucSD5t123C26UPZwTQccp2d1o8oZLboFHME5tcXR6Xtkg@GrQT3obRIPLqXptIbdoCUhGv8SjiEdmVNE2TXNuVvHac0LbLg5r08PS01NISHieyq@y5Zpv3pAfZVRuK5SzZ7vKyPA2@59iuKcOP6syggUESOE3uJsS2UUoYdpaXHc3bc7SGrJgXSeS167KjqH5K0FHSVdQJOonptbvU99jrxwM/iDsRfySK6tgpPw7woygq1RogjT1NGUmA6HESddwkiGzbBia1ukmQh3sQPYjMC1rjV5FPlFHEk07UXtJH1kjRXOr7ctLwYsWSa522m3hBW1aGr7o0kmo2Tjw9xdyvWUJzgjZZjcVG7X23a17cWKat0Ir7cVSzq2f89EGvsJvrjyfs@7ej@6T1tbK/fvWg8/vNZO1b9Nk0NgyjUt6ubG5tbW@lS4NO5HLbb7di8Zw4LbvrsXSO2jfipsuZXaaNq9Ojnvd5@1P02ya971Qb1@9K3z@fvvu6fnN4//nzffUqqFaCo4P9q8/7n8Em4pC2JdencWyTd8fbpz5s5HvGYodIcTLw0Qi5V28kwFXYt3oeSxriFpd261ItcDtg8ghXo34M5tj1eM8J@jbRJV0qr8H/ABrSpCExm5wbumRsaOv@RmlNWy@J3@724/m6VNYbxho1JEPSxX9GybhenzyX4Pnd1LNkdKcXSMZjywB8UhkAK1IlQ1MpVa7XtLVqWQNe4C@FXcOnhrGulWcmymWc68KMQcuIDP5SRNkTSLOK4sAFFIC/oMHda4/xIN5ZpTDAvO7uDvzkam2wxCm10KthLR2PwoqSUF8JDZ78wwwnbgTh/9By9t9lllP/x1tO2dAM2B5ta7ta0fSyJH6yrd/StmFvGqV1bcstaVsG2oe2vqVVcNfA3ra2zza18rq0oW1UAMW2ZOja9hYFFBuS@NGz/9a0Stlf1za3JUCF8@uS@JnMarrhb2n6dmlLM1ygUUI620CusgYXpNYVbOjIRwkWICfb8JBOPp6XdaS@te7qklaG5QbY1BoCaptrfqmibYLpwi14RmUDKW6ARGsG/A@I9K30urYt6X6pnCId/1EDRTFyeVItrG0Du0bKbbmkgaFvADEkoFVAUmBAN6oGymjkgoKWdZBfX@/C/OO5sSFtuKB83BQJdFeWynEJr6Uy/pWQeAln0ufF/nEBRheCmRc8JP0tWlHBUaRmjIkqCnyfR2AhX49OLh0cpSL82uR08Inq3PymD9ZcIFkvhUHYCQEgTWfXG1sO47NoPvx2oh9Ooanq6/19Zp58S/YHjoUzjCbUJq3rZrVZs@6t/St93dFJ6tA59uBbP/nMSM53dOJUv7rSnEfTyKMl3gcJGXhYbuZitEFjwbBNICHBIHAIeJ1OkgSQkhMoImANukKR2a/H0Zdjx3rgAxb02mbn22X52iHzsYaxkiPF329uvsy4aSuIeKnLo0R6NGh8wKUL@ulrebHD@l6bl37Sg/stvx2Py5Zer6f1KqJsKeu6jubwp@mhLG3ltpbZWJwZWMHIMiuUyo8tgHNLYsF4Ns5nxyjGGBB@42fgFxvzOahxyoiLtpFbXqbyo178/hF2o3q6z8d6Zl4c@nRgtoM2tx5LYq9NAyo/0MH9t87W6bf3B5sf4pr@0LvpRFG5ftjbxAIuo5kZe87OhIn/3@70fHKUxmb9Q@7zZx6Tp9pQFL0cKsQ41T11aHSfYrkPwoTsXvAkAfqzif3vvNdbxvN7XfD1t3Hjt0c@H3YQs1BY4seZvrJdy4zinLc78XPh6YVIhHtZwmKB/Gm1UO5vb@xX69dH@w9k9zIA0lMOk/4Gfi5KyOLeMVrAauA/V0ElrORK@V1jImYmzU8wV9nPmQvI7gK@JvSRhsNrGDZpGIJ1jC236AffWh8/VWtFuzt4uNnaMm@2Q2Y1w0bZN4P1zruys3A1/40Ous5Ce5k40MFa66GTO5B7UqQVuZ3PG47ZDi/LLUaekyTTZP3yPDlzpFpYamcq9B2yAC6TNvWKouQ4wPsJnYxkfIdB7CFDZsR9mnhdvlDYhne1dTLxmK9H@tX7Wkom9r3W/RStDOjs3fvuAS/Qj0T7W4LmLonJbhX7QqzgN3UN0gz@SSlEvNMOnGhXknV1a1OKOTDCYmW57cShtbMq5p7d/UWWQJOuS8NF6no7qPKvTipH5LaTArOOC9029tXzqw43mnrXLcCmoPdu4GOKRb3u1kvAN@q11POSRgnbex4NcyNx/MB9sFo0gk7eFCWqHvYlfaTx8v5RuzasgepLsffIzbI@m9O1ijXSrja9xxofhpQxiB2IAtYb5bA/SrzE5ylRvxGXPFCe2QigeJA0/lDT@1KjMgRGoW1@bVCdUWfRigw2B4StsRaxXvJ5LTFL65XFdCWtcfE54bUMWY7Ba6M8Uyj0l9ieQjLN@mvctIzZDBzES8DQSwzMJqLCstElR5r33jjtOjNclFJxigour4E02tvWUeVmMXDGeJRuB@jcmvMhKwlCs4Rq0bxuubKRs72pb65vUuvH0I40lpzUjQnLIhXNg72guocPrcvLqfUvQc@QK3I30gYXnfVjd5iRF/JhdZlZYMkJIPG0TKG7w071@9Gw5gc0MQWfVqbaCkznVr@JBj/RXKcd8ySrVSsCy@mn6@1@behQ96EeBZ02M1/XajXLCSLwJNOA5XHge0x6zShzuZ5NlCLKvE5sGoAfhvroRegh2SyMWNN7UWQtd6e1cdlcZCVV0zRDW7XtGh1p746i42vn/wSvKSsv8No83DzyakOchy3qmVCHMN4e1bOSAhsDUXdQ2PyZiAVAmVEkQb0OiWGIR2evVn999Uo6CMKB2GzpssGl7JRPOvOciEYDqdpJGkEUa6@ki0@HN6UzD0JmzEsnQDnxah4oSaqG1G1waIj1V7@uvrrXTpi9dK/1n57uNdeVtxXrXns/P3TKbBhZXoZx6spkm@DgGbMLB35eTYbZUAOFHXWB3pkXJxxke3pa@ihONDXGayDUpygIoccaKNkpomHhSSG1lwzVsRdCysORSkLICZg21WGdJ2aBLqzURyPFSqLBcBF9meA5KVGBf6o6ioowEW/BxrwENnJp4jZkVxlmp50SHcmKBQo7R1WcO3ukx50HL7mMaDt1rqM2IyYoFKaCZDzKcZRMP1uvXmX4uQI83x92WuFR3@WhEIkro1coDND6UNAwcKW6qZqpFihwnTpUrkYRHShDF5jzKfBtQVkmo2aZ7WptCNXA/RLTGAa3yZCCNARqpnWp3wHaHOrcIbOhKrjXvisy1Y5VVIjYJW5T7XDFtfB3xXI0CCbVJIk8qIe5TESNyb97jKhcAZj9W35nM0ucX8/uyt78kOyqTF0yFDNdkCRgqAJgb@pJJlB5rwCsYlLtQPODunyE59Myaf@FrDiKMhr9oH5Roo/MZtActACx9r3Do8EF9zkegctEqzv3BxL@HhJF/fQ84Ou6g1DHLnjFRwZO8gl@hGLvtQFTPzKVuL7nPsD0jzN22ihsPQKfFE/a8Vc7sGl6U7XbHd9P7wN7OErvDsd3zfHdvoAcgfO25dMG7PCJcORpWmBaVKsqud1r1bEt4UsDGGgqAqR569xpvCYry8vZw40DJjVeh0NW9pSTbdinDS2MgiTANws4oB3WpqhT1N1ZIxUUMC/ZxcfJvTbgMlhLrgE6SpHVp5HZqQJu6d3TE82ZmSCx83XnfMrTlKFjO9pvLjgNiJoqFnAsL49vQTYlV4tr65a7U5zSfN6uJw3LXVlRcEuLc7funZzHF6akU6kdM2G7yE5nekeyUJlu6y0VjN2ljLNpyLG4y8vyM3rDxSD309MYVqhSB88RGKkzj3EfTG3KCNK1SoZibAeTZ@rA4hThoLaQxVQK3ADEet4Qr6lOG8B2j4mcA4mGQSw5b/yM38TNFx36Ix17dNL8IY@Om@DRSbPo0XHzJzx6pKT2U8fTE4BfXZXeBgGkdemk7WqvrMmkPbl9egKPnbxOu1eGKFvPa7OgJ8CsVOK/R02AlC6YesnUK6b@wlTKVYerLlcZVzlXa1x9QMf9zKZ2VVgGpIfM8MFr9B1wo4mLiASFLy4ZeAvbcSwGvuHeMrAA@Mld083S7a0w7y9sxisLqCZRRIPe2OVpeISqV@xorEJoyHAWioU8IYoV4NxMCzsxmHwY@gMZRM1Xj9fSbA51rgr/vGBptL1k9uo/3f7eW1m9L92t3Np3Q10tj35Zta7YAt@VKehmysowaM6YXexGXpjcQgPh8juigD@JZeIZwpdWn0q3YlhAXbL0XTBV9qhJiIgh12wupmfBNMwj9BVkfi13AcVCqWzbvoDkJYOQV2js4WR@rJILhlvzddH2Z2@s80Cbv8pesp09x6R76b55cWoKwC2heEdMxyRInSDim0WIkR485XjTZbbtPD1NXpdD2QBYWg6PJu/Oc3tExN@mytVMmEOacFBwTxax6rdZe8ugdBstm8bJCZ72fazJjqrDgl/ABJZX6xbl9uoOXB247sLVhSuBK4PrG7hyuP7e13W4rcHtLd4v7@ySN3eruFX12dwDm@UouPMRh64ADBW8kIh3kUQZj4FbkmU/KQ45OFSfGnJx6HsnmBpkOPi6sl0c42JMhyFLVIBYZ9Z4blfjpG6VjCVgzMv0QJZJbqULeFVmoXfmoCdSzAHvzgFP5JsFfkPezAIXJZ/D/WYOd0Enc9C4X3MLJgpTJi2CyN58oQFfo7cFPSh0DzOXwggwNYB9D@34ybXHewrWzXSmwk5dHtsTMFZv1mwAOsL6/5qC@WDm5VkKbvIFEQlaLjQ9WNoNoGdGe37gc42fL4bOHNH6iZk@ZkIxjU84k/aEhratGaIvbPEFzWJbDOKSEwd/zx3UVTArg0iBotHOi9u0G7edtHrEJTP1I41DCABf8BBqgYNPEK4W0KWFyYM7v2BJnqz4tbAiq2Vc7vnFRQV@z2mSzhcwKFMyzEBkiK0CpymRmh8E0UtUBMDLZAogz9IRRxYv0REAL9MpgCykI8qJCHcq5AuDqwzmME4ymOKOfC5y8P7gktY/0BaXs4@eaFqhni@sCQpYsPhwpzEd4JEy4oKw@twU4L/V79Lo545LQystGQA9tL02m07ZVd9fXmZzeX1vZkime0QjK5ibFRO6aghOKvmViL4aSD49ie4od8vsEd3jO5/p/6EEgZ6GYS/jiIT3q0iu46/CtCS4CkMeHdAYyhugZ4lObZ7puWIEt8EtNG@zS2RnRXaFGC6KIfoiF/E8o@chxspnFO2K1bB1DBvTvETktq7W4K9u1aEkrN1ZNSgQHduuQ35mHBcCl@yWr6zc2XUs3dLUbvPc4NgkDs8Rz00JK4ZfScp9gX7NBurTdOuamzOsknwXCl/laXHoe4kIhhBv0yd59fd4ZVVRXeXHWcV9jmddA7ofQKqOB8XGg7rnPg6EMVe7dPATQzDsY@y/LSLejQAM24OUgPeaG8eXvJ/YsHdCqmxyLCFOgB6yYfzo8hgikGtGXGvQ@GOvPT6LY8reTFaKONTvILKJ9RMU0US8OSUiPaQD4mCIzC1kuAiLf9sdgWdH3B663PfzI1eCD5/SB6LiQwx9ynjmIn2AmQAn2jAa4GCbqLUIRMpOhYl42BcPRM2OdrNPOYjaov10a0wCt2filqgizZp5tsVXvibBX7zvpbTgJqWF@5B@JknUTsxbNDQJXM9pSFT8FrMOwN0qXomaHiATcUmr9C5fGMxyf4bggP2Sc2vcocUuPYALYHnONHzDDhFPQ8IKHvvdQnGlundWOoVWgZ2N/Cb7gPWNimVAtlBRsV5CjBmC4Rg6/bJ2DC1mU@jURYciAlMZukGwawgPCZe4ALOYzUcZHqzdLDTIZuC1ZQgXI6xLEiw2wPdRArBR8TreHlsy23ML9sjM6WYBzG5qOsMsiYAac@EgilXecTJXQ7/sCHoQNsvKpL1ErXcWhdV8ROLygzIUX8RC68fb7KDh@WwBww/oQBGHBgJd6wPEKFhoPigjDCjQ4bp5L4yN7jD9HBb7XSs9Kb9hck34SJXCzfKyvlMTge4SVc5hKM1E1MRSvLagt6ll@EW/kKFJ6dTtBQGrpuG3LhD@xoJMTVgOiPIA8QiQFVePoZThC2jHq0d1e8kY3WtvqVzfw0MCYMqsqRw6Z7Sc3sJKVJhGnnBVrFlf4dDcidw4zVn41h1aePHicbWP8Wql3/KRXapln3CjHjGt2Q4kxbOglyfFQmuf7l6WJOS0qu5Pczg@9LLwcKPmRXEi7MFSaPYWITWPdPFgcaGNaTKkERBBK9krPkwhoYqZn5M@PqMo2GUKxmLY4lwgtRaEry6E3y6C7VFzpt/AM4Vc7Yhkn8@9bpi8RdAtkENODwlcCD07Nrhy2qtONYiYeifyofGPps6Af/TdR7@5WAM3FI0d@FsD78HQgnpvzhyWP6YHNlTV1ZKhImHxI4C7eIjXhAg3wL7ksTknM@6sb@NbDvElFDaD7rQNTVpDkV7jBucJ5Ld77Su2XubUt/X32hV9bsZxYMZ1cEZcoanDB@Vn3mBU5wUA5TFxoLy2oQ5pkpgUE53pqJ3INzHXqgcvLdpcuMiiO87eflOmK4Yq@O2x4suXL3@BAneFiFcw6nBMaL85f7Zx2MzzHAYEmVwcfDn5dIkZA3q5Qdu1l3S4TTMRfmSw2qRdmp6NEZiY@YcbohOG@A9YYTJo@wHFN3RfmFxtqkI2bIvTOfEPGdLJg6nJifDrC4RHmJEiWhiZvDuqHhIs26fSgwsBTj36OTM8yoxQbONxE/g6BguIGeBRjU2wbjwQh/u3TRDOlt@mEMdiFUAoaHD9JoynYUN911RPAO7dNFw5h3uXw71vFns@2FIDMyRszEm2MTTbmLOTD6cE3@RNn0KkxU66NVBYktSNYHtPmuqUQ1iFs4@XzzNe1C0Vr0XkmWNcZDJh6QsaCF1A3thSlPdNOUucOW0MFQYeVuhWen6@4A0x2gxRCwQySOD20mvxoJPI75t47AKcKPL/wqE/WJNAVBSqLgA0BlX28nLhQc5gYc3OauoG2ees899ipdOS0Ct@V1o5v@hfGe2Vr87Xs1O6cdAIqz3bJrtFunmI9/C9TkbX8yJ8BQHSgQpOWrTO44vIlW@9O3UCAU/A1eQZi0PB6RSb2Tdp@GXzoUfBx7KPEYWri08gsDEh4vHeY/f42anXNzOopufFNumEU4vS0PBnOEsR/97xIvzmcQb5@AO7gTSYfLC26gRsABfxD88IIf8N) The input is only a small portion of the entire google page, since the TIO-link would become over 30,000 characters long with the entire page.. :/ To test any google search page with this part of the program, follow these steps: 1. Ctrl+U (Show page source) 2. Copy-paste everything into the second TIO's input-field 3. Surround it with leading and trailing `"""` (for multi-line string inputs) **Explanation:** ``` ’й.ŒŒ/€±?q=ÿ’ # Push dictionary string "google.com/search?q=ÿ" # where the `ÿ` is automatically filled with the (implicit) input žZ # Push builtin string "http://www." ì # Prepend it in front of the string .w # Go to this URL, and get its page as string ”€«” # Push titlecased dictionary string "About" ¡ # Split the google page on that titlecased word 1è # Only leave the second part (0-based 1st) # # Split that on spaces 1è # And index into the second part (0-based 1st) to get the amount # (after which the result is output implicitly) ``` [See this 05AB1E tips (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’й.ŒŒ/€±?q=ÿ’` is `"google.com/search?q=ÿ"` and `”€«”` is `"About"`. ]
[Question] [ ## Summary A new string manipulation language has been made, using only the characters `$+#-!*|@>`! Your task is to implement an interpreter for it in as few bytes as possible. ## Input A string, which is a single line of this language. This can be taken in any reasonable way (stdin, function parameter, command line argument etc.), or as a predefined variable. If the program asks for user input, accept all user input it asks for **from stdin** and nothing more, see below. You may assume it is a valid program. ## Output Whatever the language would output, specifications below. You must output a string, in any reasonable way (stdout, function output, etc.), or a variable value. When the language outputs explicitly, this **must** go to stdout. Standard loopholes are banned. ## Language Specifications ### Processing and Syntax The language has a very simple form of processing as it does only string manipulation: it starts with an empty string (`""`), and changes it with each term. A term is made up of one or two parts: a function (below) followed by possibly a parameter(below), which edits its behaviour. Terms are separated by pipes (`|`). You may assume it will not be an empty program, and no term will be empty. You should output the value at the end of the program. ### Functions The language has just 6 functions, as shown below. Each function either accepts one or zero parameters. * `+` concatenate strings (takes one string parameter, concatenates it to the current value) * `!` reverse the character order of the current value (no parameter) * `*` repeat the string (takes one integer parameter, repeats the current value that many times) * `-` removes all occurrences of a value (takes one string parameter, removes all occurrences of it from the current value) * `$` [pseudo-]randomly shuffles the current value (no parameter) * `<` output the current value to `stdout` (no parameters) ### Values These are the values that may be passed to functions, represented by regex that would match them: * `@[^|]*` a string literal, including any character other than pipes. It may be empty. * `#[0-9]+` an integer literal * `>` the next line of `stdin`. If used with `*`, convert to integer. ## Test Cases ``` ╔════════════════════════╤═════════════╤══════════════╗ ║code │input │output ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+>|!|+@hello|*> │13 │31hello31hello║ ║ │2 │ ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+>|+@abcdefg|$ │hello │hcloeebafdlg ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+@how areyou|-@o|-> │w │h areyu ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+@out|<|*#3 │ │out ║ ║ │ │outoutout ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+> │what ever 345│what ever 345 ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+@$pe<i@l|<|-@$pe<i@l|+>│A|$o $pe<!@| │$pe<i@l ║ ║ │ │A|$o $pe<!@| ║ ╟────────────────────────┼─────────────┼──────────────╢ ║<|+>|!|< │input text | ║ ║ │ │txet tupni ║ ║ │ │txet tupni ║ ╟────────────────────────┼─────────────┼──────────────╢ ║+@># │ |># ║ ╚════════════════════════╧═════════════╧══════════════╝ ``` Note that test case 2 is random, so any permutation of the characters in it is valid. Also, the outputs in the table are seperated by newlines, but your program doesn't have to do the same. The last value in each case the the final output. ## Example (Un-golfed) python interpreter [Try it online!](https://tio.run/##fVLRbqMwEHz3V2zVk0wSGjXXN9RUfbmviPJAYSk@GRsZk/Z06benuzYkhPaOF8R4ZjyzbPvH19Y8nE6qaa3z4HJT2kaIEivIyzIpepfCIdeLTAA9Dn3vDBAKK4Yjsetf/k1cO2x1XmBChylIuYiaptf/MV@CMp4VA5tiMXsgFnXuOtiCVp0PcJSH6Ouu7qtKYxJIi6mxlOvfVpnxJBrjYWLcvSlf1ORMMLoOy4n7tUdkDia29xOT1nH2uZC@hah6U3Dwv3IlM0howClsFmnghUfeMU7znONLxmlmc/wH49Q8hfsr/CbgeJjjj4xTXsY/YvpX9DToxOO7HxqoCvhrd7@H7RbkrczODkMbbhgom2wfa6KeqZ6/qkbFIOjwG9@WZil/GY8ODNEjksG4Nq43dLFrUrgMvKKJhsnu@ITu348tqt1mf7mDWhLzXJeo5/RDBDYi/WUxv086oV39Y3oJIQpbIjGuqvgaaS/sq8ub0IV3nGYkaSWsA0VkYNm6a7Ui0VGOmx54XFrFxkJc1ut0Wj0db46r5xq1tsflk9g8iJ@f "Python 3 – Try It Online") IMO better if you run it through IDLE or whatever you use. (I golfed it down to 424 bytes after, but I'm sure you lot can do better). [Answer] # [R](https://www.r-project.org/), ~~287~~ ~~286~~ ~~273~~ 269 bytes ``` function(C,x='',`[`=gsub,`!`=intToUtf8,`?`=utf8ToInt){for(k in el(strsplit(C,'\\|'))){B=eval(parse(t='^.'['','(?<=.)>$'['readLines(,1)','[@#](.+)'['"\\1"',k],,T]]));x=switch((?substr(k,1,1))%%13-2,strrep(x,B),paste0(x,B),,B['',x,f=T],!rev(?x),print(x),,!sample(?x))};x} ``` [Try it online!](https://tio.run/##jY9fb4IwFMXf/RTgn7TVYoZuyRKtMve0ZI/sSVioWoTIKClFWayfnV1csqc90KfTc3t@51Y1MWviKt/rVOb4ldYMIRptI3Ysqx2N7Iilufblh46fabSOWAXCl2@5JtdYKnyy0twSGS61Koss1UBAQWAQIeS6YeLMM1xwVQqsGfqcoi3AEV4v2ZSshnBTgh/e01yUmLoERltvEOLphMCoHwRuH9FTSKkfhoQsalZeUr1PMF7DalCIT9SFGBmN3Lkzo@AoUeCabggteKnFw6@mm7a1pjHzQ2orccbrGl4o@BcGQe2SfxWZaF1yW9S3Zs81Rs7/J8gR6cUYTVbGNhMvEVkmzXgFpjvvzXodoxOP7/YHER/NELw7pFvUS@TF4kp8y8o4njRO23zpmJWVNkszHszB6LZoC0@4tsRZKGv@@NSxaFiIZeplUOb86TvsxQyl1Tq2ZzqyYinbZPMD "R – Try It Online") * -1 thanks to @Kirill L. * -4 thanks to @Giuseppe Unrolled code and explanation : ``` function(C){ # C is the string manipulation expression x = '' # initialize x = '' tokens = el(strsplit(C,'\\|')) # split C by pipe '|' for(k in tokens){ # for each token k arg2 = k arg2 = gsub('[@#](.+)','"\\1"',k) # replace @X or #X with "X" (in quotes) arg2 = gsub('(?<=.)>$','"readLines(,1)"', arg2,perl=T) # replace > with readLines(,1) arg2 = gsub('^.','',arg2) # remove the first character B = eval(parse(t=arg2)) # evaluate the string : this will be our # second argument B A = substr(k,1,1) # take the first character : # i.e. the main command (+,-,! etc) x = switch(A, # switch on the main command, execute the '+'=paste0(x,B), # corresponding expression and '!'=intToUtf8(rev(utf8ToInt(x))), # store the result into x '*'=strrep(x,B), # Note: in the actual code we switch on '-'=B['',x,f=T], # the utf8 value MOD 13-2 of the command '$'=intToUtf8(sample(utf8ToInt(x))), '<'=print(x) ) } x # return x (and print it implicitly) } ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-palF\|`, ~~146~~ 142 bytes ``` r='';$F.map{|i|x=i[1]!=?>?i[2..-1]:gets.chomp;eval %w[r.reverse! r*=x.to_i 0 $><<r r=r.chars.shuffle*'' r.gsub!x,'' r+=x][i[0].ord*5%11]};$_=r ``` [Try it online!](https://tio.run/##PY5NboMwFIT3PoVRiZCgWCEkm4IJ3eQSFEUmMWDJqdEzBKK@Xr3U6aK7@flGGpiax7oCD4LMP7GbGL5Q4cJVldQePxZHVe0Yi5P6rZOjZZfe3IZM3oWmm7kCBvIuwUqPQsgXNpqzolvqF3kOFDg4XIBltp/aVsswCCiwzk6Nt7w@dcSXulLVtmYGruFhkyT1d@afOax0jQr0MCp7qbXBsCBJSnbEhVEpmstVth365K8kDjIzFSAfZsK4NBgXZHapmUbMMXxJ3YzMvRjp8ytN9wdX@oPMVakdEP9rh72jb@jTeyX@mGFU5tOu8SD06QN/AQ "Ruby – Try It Online") Port of Chas Brown's [Python answer](https://codegolf.stackexchange.com/a/182770/78274). Does not print newlines after output. As usual, Ruby 2.6 version will be 2 bytes shorter with endless range indexing (`i[2..]`). [Answer] # [Python 2](https://docs.python.org/2/), ~~215~~ ~~219~~ ~~209~~ 208 bytes ``` from random import* I=raw_input;o='' for t in I().split('|'):p=t[1:]=='>'and I()or t[2:];exec"o=o[::-1] o*=int(p) 0 print(o) o=''.join(sample(o,len(o))) o=o.replace(p,'') o+=p".split()[ord(t[0])*5%11] print o ``` [Try it online!](https://tio.run/##XZHRjtsgEEWfw1fMuqkA24nipPvCLpH7mG@wrJUb47Urx4MwaXYl/j0FJ/FWfWK498xlAP1pWxy21yPWSpooiq6NwROYaqj90p00GhuTgzTV5a0b9Nm@oKSUNGjAQjfAgfH1qPvOMuooF1raIhOllHRPfUSwA1lsRfmiPtQxQomFEKusBIxlN1imOWxAm1AihxC@/o3dwMbqpHvFMO3V4B0ePFwbpfvqqJhOKfVKInV0P54XaGpmi03J4@fvWVaSKRTw6i9FDmH0g1WnURYlqVUDo7KTyCouyOLSdr2CL0p8lWuNmnGy@EdRH1YNte8kU9T8NowLMMqezQD/9W/uaMO0wfcUJnwMJ9@mvKkRCAHRw533ZDEPWwSwTO7tZBHelIW/8/kNo8nePbkkb1Xfo4v3NIWCZjua0i0t@R1I8urX0c/y7paTP8EPO2/xApVRn3h2qxzd6pZxmX08W/fq4m@7oD8yaeqRtrKg/igDux/PM77U6rXLe9@ymuvklvnTLRGC9pQ7z1//Ag "Python 2 – Try It Online") -4 because `raw_input` is required. 9 bytes thanks to [Embodiment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance); 1 byte from [Ascii-only](https://codegolf.stackexchange.com/users/39244/ascii-only). [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 305 bytes ``` a=>{string s="",d,g;foreach(var c in a.Split('|')){g=$"{c,2}";d=g[1]==62?ReadLine():g.Substring(2);var z=c[0]%14;s=z<1?string.Concat(Enumerable.Repeat(s,int.Parse(d))):z<2?s+d:z<4?s.Replace(d,""):z<5?s:z<6?string.Concat(s.Reverse()):string.Concat(s.OrderBy(_=>Guid.NewGuid()));Write(z==4?s:"");}return s;} ``` [Try it online!](https://tio.run/##XY9BT4MwGIbv@xXYaNYKEsG5w7qC0agXo2Y7eFgW07UfrAl2SwszAvvtWMZtl77p97x9vlTYG2FV91JpMbelUToPhkgy1nGWNMPNswyhQAY5zXYGuNjiAzee8JT2eLjcF6rE43ZMSJOzS9SIID4iKlm@itaMTeN0AVy@KQ2YzPJwWW0GKY4J7TU1E6vb9VU0oZbV8ygdaPi004KX@FlXP2D4poBwAXtwExsoXYaf3FjAkhAyq@dxan3pcpLavlVw4VCAUM/uU@vO6Zm27x2gVzjBOfowEszjH/5myWulZPgOv326KqFfRpWAa8bcrpnbQI8Gyspoz9JjR0cnfPprhpGftBet/7CFoti11wlyz7vobhT/Aw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=shuffle -pF/\|/`, ~~220~~ ~~217~~ ~~210~~ 183 bytes ``` map{$,=s/..//r;$\=reverse$\if/^!/;$,ne""||chomp($,=<>),$\=~s/\Q$,//g if/^-/;say$\if/^</;$\=join"",shuffle$\=~/./g if/^\$/;$\.=$,eq""?<>=~s/\n//r:$,if/^\+/;$\x=$,eq""?<>:$,if/^\*/}@F}{ ``` [Try it online!](https://tio.run/##RY7NTsMwEITveQowPkDjZINQL/nDLRAucODAzUJKitMapbGJAwLq8ugYuy3iMKPV7jejVXzoptaua7XBpNAQxwBDhlkx8Hc@aI6ZaOHpGDJMeo6QMYuVXKtTx@blGXHctwb2gAnA8siTEWS6/tyncvBFL1L0CBG9emvbjvsExAeYYU/EBSb8FaHLvNy19e6DFJMdEHrg4x/4209gS6vtxtqQ1s3imbdLE9LE5AY7hXQ2v7q@qW7dHNG50/4Slv7oLfI2ObkIWimbegia@iuY/Ug1CtlrG93fCT2m6eMouuLwt1tO4@Q8sZGqgBn4BQ "Perl 5 – Try It Online") [Answer] ## Javascript, ~~292~~ 267 bytes ``` f=(p)=>{c='';p.split`|`.map(l=>{v=l.substr(2);v=l[1]=='#'?parseInt(v):l[1]=='>'?prompt():v;c={'+':_=>c+v,'-':_=>c.split(v).join``,'*':_=>c.repeat(v),'$':_=>[...c].sort(_=>.5-Math.random()).join``,'!':_=>[...c].reverse().join``,'<':_=>alert(c)||c}[l[0]]();});return c} ``` [JSFiddle](https://jsfiddle.net/vxsh0tqj/) ]
[Question] [ Inspired by [github.com/JackToaster/Reassuring-Parable-Generator](https://github.com/JackToaster/Reassuring-Parable-Generator), in turn inspired by [xkcd.com/1263](https://xkcd.com/1263). The possible words are derived from the [reassuring.cfg](https://github.com/JackToaster/Reassuring-Parable-Generator/tree/844e2c43041cd2dd057e28a1e5d52aa98ef2d70d/reassuring.cfg) of that repository. Having a look at the reassuring.cfg (use the 12th commit) is suggested to see the grammar the output matches (The output is a list of all strings matching the grammar). **Task:** Your program must output all 7968 case-sensitive lines of the exact text contained in the pastebin [pastebin.com/2SNAJ1VH](https://pastebin.com/2SNAJ1VH). A copy of the pastebin is saved in the [Wayback Machine](https://web.archive.org/web/20170713042447/https://pastebin.com/2SNAJ1VH) Here is a sample of 33 motivating lines from the pastebin: ``` Computers can't enjoy a salad. Computers can't enjoy a cake. Computers can't enjoy a ice cream cone. Computers can't enjoy a meal. Computers can't enjoy a drink. Computers can't enjoy a steak. Computers can't enjoy a chicken dinner. Computers can't enjoy a piece of cake. Computers can't enjoy a piece of pie. Computers can't enjoy a cookie. Computers can't enjoy a sandwich. Computers can't taste a salad. Computers can't taste a cake. Computers can't taste a ice cream cone. Computers can't taste a meal. Computers can't taste a drink. Computers can't taste a steak. Computers can't taste a chicken dinner. Computers can't taste a piece of cake. Computers can't taste a piece of pie. Computers can't taste a cookie. Computers can't taste a sandwich. Computers can't experience eating a salad. Computers can't experience eating a cake. Computers can't experience eating a ice cream cone. Computers can't experience eating a meal. Computers can't experience eating a drink. Computers can't experience eating a steak. Computers can't experience eating a chicken dinner. Computers can't experience eating a piece of cake. Computers can't experience eating a piece of pie. Computers can't experience eating a cookie. Computers can't experience eating a sandwich. ``` ### Challenge rules: * The lines output may be ordered in any way you want, but all 7968 of them must be included. * The output should be as a single flat string, not as a list of strings. * Your program should accept no input or an empty unused input. * Your program may not fetch data from any online source. * A single trailing newline is optional. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [Zsh](https://www.zsh.org/), 765 bytes This may be the first thing I’ve ever written in zsh, but it has the incredibly convenient feature of being able to convert arrays to brace expansions (though it’s [not as convenient as it should be…](https://www.zsh.org/mla/workers/2017/msg01088.html)). Run with `zsh -P` (counted as +1 byte), which turns on `RC_EXPAND_PARAM`. ``` a=able\ to b=" be $a" d=wonderful i=ing\ a o=omputer n="No c$o " r=ever p=capable\ of u=will w=$u\ n$r x=experienc e=(\ {{{enjoy,tast,$x'ing eat'}$i,tast$i\ {delicious,fresh,tasty,refreshing,$d}}\ {salad,cake,'ice cream cone',meal,drink,steak,chicken\ dinner,'piece of '{cake,pie},cookie,sandwich},{understand$i,{enjoy,$x}$i{,\ {beautiful,$d,{inspir,amaz}ing,superb}}}\ {son{net,g},poem,story,play,'piece of music'}}.) f=(${e:s/cing/ce/:s/sting/ste/:s/ding/d/:s/ying/y}) l=($w won\'t$b {$w,n$r\ $u}{$b,' have the ability to'}) v=($l "won't $r$b") k=({ca,wo}n\'t $l is{"n't ",\ un}$a) c=(C$o\s A\ c$o) printf %s\\n $c\ $k$f C$o's '$v$f $n{can,is\ $a,$u\ $r$b,"is $r going to",{can,$u}\ $r}$f{,} $c\ {is{\ in,"n't "}$p,"cannot $x"e}$e $n{{is,$u\ be}\ $p,"can $x"e}$e ``` [Try it online!](https://tio.run/##TVLBrtsgELzzFSuLyom0be6VOFTvXvUDfMF4nVA7YAGO44f49nRxWqm3gZ2ZHZb9jLdXpARff7200v1MHSQvetVATyB1Iwa1eTdQGNdZWGXdtQMtvPL3ZU0UhFPNTw9GemhEUPTgq0UZvbyt/ChWtdl5FpuSawdOBvFU9FwoWHJGkDp1kHMm99vvmHRMKJ8tNwHSqS3SHnfSMmmg2Rrr14hjoHg7CjsGOk6sQDmUwryoZz2g0RNhaw2BCaTvYLyjFu@kZxyCdRPGRHpCc7NmItfBYJ2jgO1iiTV@hDYfFnwuaLyfLGHUbtisuRXMa51ITHzBEf@ml0/Om5Ej9KTXZHlgnAmzdXGxAfVdf5aaM678@r68w3qXHSW8Flw83TmVDzsus97/i3JfozVtKd/OYlQnmel7vBh2uhi6MIypYn5PPQwVDxXtFe3lLGbWbMCf2LVJ9pDlhvwNHci1ZNljCzf9IEg3At3b2aadF6Bl3YN1MzQsbBPIIPvmLCZ14rng5kt1A67bmJtKaPjhqytSn4VRpw/puwg/uroYZ7HwxNMIX2LXOZCGW09yBOa0EVr5YCwd2zq0kWsa66bUhtjYyACuvm5E8g0eLA5e60WOGcvhlzlFB9bhO0qRCzbMdJ4jPhsqkmoHZh3WPVX9m/Kv/nr9AQ "Zsh – Try It Online") [Answer] # JavaScript (ES6), ~~1234~~ 1091 bytes That's a nice byte count to start! Time to golf down that huge string. ``` f= _=>(G=`beautiful|wonderful|inspiring|amazing|superb sonnet|poem|story|play|song${p=`|piece of `}music cake${p}cake${p}pie|salad|ice cream cone|meal|drink|steak|chicken dinner|cookie|sandwich delicious|fresh|tasty|refreshing|wonderful can|is ${a=`able to`}|is ever going to|can ever|will ever${b=` be `+a}|will ever is ${C=`capable of`}|will be ${C}|can${E=` ${e=`experience`} ${w=`will never`}${b}|${w}${h=` have the ability to|never will`}${h}${b}|won't${b}|${w}|won't`} ever${b} isn't ${C}|is in${C}|cannot${E}|can't|isn't ${a}|is un${a}`.split` `.map(l=>l.split`|`),F=S=>[].concat(...S.split`|`.map(s=>eval(s.match(/\d/g).map(n=>`for(f[${n}]of G[${n}])`).join``+`A.push(s.replace(/\\d/g,n=>' '+f[n]));A`,A=[]))),G[9]=F(p=`enjoy a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),G[9]=F(p=`${e=`enjoy`} a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`),G[0]=F(p.replace(/([^g])e? (a|e)/g,'$1ing $2')),F(`C${o=`omputer`}s89.|A c${o}89.|C${o}s69.|No c${o}49.|C${o}s70.|A c${o}70.|No c${o}50.|No c${o}49.`).join` `) document.write('<pre>'+f()) ``` Less golfed: ``` f= _=>( G=`beautiful|wonderful|inspiring|amazing|superb sonnet|poem|story|play|song${p=`|piece of `}music cake${p}cake${p}pie|salad|ice cream cone|meal|drink|steak|chicken dinner|cookie|sandwich delicious|fresh|tasty|refreshing|wonderful can|is ${a=`able to`}|is ever going to|can ever|will ever${b=` be `+a}|will ever is ${C=`capable of`}|will be ${C}|can${E=` ${e=`experience`} ${w=`will never`}${b}|${w}${h=` have the ability to|never will`}${h}${b}|won't${b}|${w}|won't`} ever${b} isn't ${C}|is in${C}|cannot${E}|can't|isn't ${a}|is un${a}`.split` `.map(l=>l.split`|`), F=S=>[].concat(...S.split`|`.map(s=>eval(s.match(/\d/g).map(n=>`for(f[${n}]of G[${n}])`).join``+`A.push(s.replace(/\\d/g,n=>' '+f[n]));A`,A=[]))), G[9]=F(p=`enjoy a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`), G[9]=F(p=`${e=`enjoy`} a2|taste a2|${e} eating a2|taste a32|enjoy a1|${e} a1|enjoy a01|understand a1|${e} a01`), G[0]=F(p.replace(/([^g])e? (a|e)/g,'$1ing $2')), F(`C${o=`omputer`}s89.|A c${o}89.|C${o}s69.|No c${o}49.|C${o}s70.|A c${o}70.|No c${o}50.|No c${o}49.`).join` ` ) document.write('<pre>'+f()) ``` --- ## How? (This is by far one of my most favorite golfs of all time!) The grammar is stored in the array `G`, which evaluates to this: ``` [["beautiful","wonderful","inspiring","amazing","superb"], ["sonnet","poem","story","play","song","piece of music"], ["salad","cake","ice cream cone","meal","drink","steak","chicken dinner","piece of cake","piece of pie","cookie","sandwich"], ["delicious","fresh","tasty","refreshing","wonderful"], ["is capable of","can experience","will be capable of"], ["can","is able to","is ever going to","can ever","will ever be able to","will ever"], ["will never be able to","will never have the ability to","never will have the ability to","never will be able to","won't ever be able to","will never","won't be able to"], ["is incapable of","isn't capable of","cannot experience"], ["can't","won't","will never","won't be able to","will never be able to","will never have the ability to","never will have the ability to","never will be able to","isn't able to","is unable to"]] ``` `F` is a function that splits a string by the delimiter `|` and iterates through it. So far so good. ``` F=S=>[].concat(...S.split`|`.map( ... )), ``` Now what's going on with this inner function? ``` s=>eval( s.match(/\d/g).map(n=>`for(F[${n}]of G[${n}])`).join``+ `A.push(s.replace(/\\d/g,n=>F[n]));A`, A=[] ) ``` First we initialize an array `A`. Then we find all the digits in the passed string `s` and build a sub-program: Using each digit `n`, we generate a `for`-`of` loop that iterates through the entries in `G[n]` (stored as properties of `F`, since functions in JavaScript are also objects). The loops are then appended one after another. For example, the generated sub-program for `s="1 2 3"` starts like this: ``` for(F[1]of G[1])for(F[2]of G[2])for(F[3]of G[3]) ``` On each iteration, the sub-program replaces each digit in `s` with its corresponding replacement, stored in `F[n]`, and the result is pushed to `A`. The sub-program is `eval`ed and `A` is implicitly returned. ``` for(F[1]of G[1])for(F[2]of G[2])for(F[3]of G[3])A.push(s.replace(/\d/g,n=>F[n]));A ``` Using `F`, the rest of the program simply builds the remainder of the grammar from the production rules that already exist; replacements are simply defined by a single-digit index in `G`. [Answer] # PHP, 877 bytes Ah that was fun! ``` for($p="piece of ";$c="AEIMQUY]aeBFJNRVZ^bfQUY]iIMCGKOSWmqunrvoswCGKOSW"[$m++];)foreach([409,T19,"71 eat59",T19delicious,T1916,T19Ty,T19re165,T1914,409,719,40912,40914,409105,409115,40913,understand09,71912,71914,719105,719115,71913]as$i=>$v)foreach($i<8?[salad,cake,"ice cream cone",meal,drink,steak,"chicken dinner",$p.cake,$p.pie,cookie,sandwich]:[sonnet,poem,story,play,song,$p.music]as$u)echo trim(strtr([C17s,"A c17","No c17"][$o=3&$d=ord($c)-65]." ".($o&2?[6,is3,"is 8 go5 to","6 8","2 8 be3","2 8",11=>"is 15","6 7e","2 be 15"]:["6't",$t="won't",$w="2 n8","$t be3","2 n8 be3",$w.$z=" have the ability to","n8 2$z","n8 2 be3","isn't3","is unable to","$t 8 be3","is in15","isn't 15","6not 7e"])[$d/4]." $v",($c>l?[ing,ing]:["",e])+[2=>will," able to",enjoy,ing,can,experienc,ever," a ",inspir,amaz,beautiful,superb,wonderful,"capable of",fresh,omputer,T=>tast]))," $u. "; ``` Feel free to try digging up one more byte if You can. **ungolfed** ``` while($c="AEIMQUY]aeBFJNRVZ^bfQUY]iIMCGKOSWmqunrvoswCGKOSW"[$p++]) foreach(["enjoy0 a","tast1 a","experienc1 eating a","tast1 a delicious","tast1 a fresh","tast1 a tasty","tast1 a refreshing","tast1 a wonderful", "enjoy0 a","experienc1 a","enjoy0 a beautiful","enjoy0 a wonderful","enjoy0 a inspiring","enjoy0 a amazing","enjoy0 a superb", "understand0 a","experienc1 a beautiful","experienc1 a wonderful","experienc1 a inspiring","experienc1 a amazing","experienc1 a superb"]as$i=>$v) foreach($i<8 ?[salad,cake,"ice cream cone",meal,drink,steak,"chicken dinner","piece of cake","piece of pie",cookie,sandwich] :[sonnet,poem,story,play,song,"piece of music"] as$u) echo[Computers,"A computer","No computer"][$o=3&$d=ord($c)-65]," ", ($o&2 ?[can,"is able to","is ever going to","can ever","will ever be able to","will ever",11=>"is capable of","can experience","will be capable of"] :["can't","won't","will never","won't be able to","will never be able to","will never have the ability to","never will have the ability to","never will be able to","isn't able to","is unable to","won't ever be able to","is incapable of","isn't capable of","cannot experience"] )[$d/4]," ", strtr($v,$c>l?[ing,ing]:["",e]), " $u.\n" ; ``` **explanation** The output can be split to 48 chunks of 166 lines each. Within each chunk, each line begins with one of `Computers|A computer|No computer` followed by one of 14 negative (for `Computers` and `A computer`) or 9 positive (for `No computer`) capabilities. I encoded these chunks to 6 bit each, (3 different subjects -> lower 2 bits; the positive and negative caps share keys -> upper 4 bits), and (probably obvious) added 65 to use the values as ASCII codes. Within these chunks, 8 verb/adjective combinations for 11 different foods and 13 different combinations for 6 different arts, always in the same order; so they can simply be looped through, using the verb/adjective key to determine wether I have to list foods or beverages in the next loop. One tricky part remained: Some of the caps require the gerund form of the verb; and some of the verbs lose an `e` in the transformation. The cap index tells wether that is necessary or not. (and thanks to the order of bits in the encoding I can simply use the ASCII character for the comparison). But how? After juggling with regexes for a while, I simply put a `1` where the `e` has to be replaced with `ing` and a `0` where `ing` has to be appended and let `strtr` do the job. That´s the story of the ungolfed version above. (1199 bytes packed) --- The **golfing** consisted mainly in 3 steps: 1. Most used character sequences were stored to variables. 2. `strtr` was extended to everything except the subject in order to move variables to `strtr`. 3. Most of the sequences were moved from variables to `strtr`. The 19th word, `tast`, was replaced with a capital letter to get rid of a couple of quotation marks. --- [Answer] # Retina, ~~1249~~ 1192 bytes ``` CFs 1 5.¶A cF 1 5.¶C O nG beH 5.¶C O nGKtheJto 5.¶C nG OKtheJto 5.¶C nG O beH 5.¶C won't G beH 5.¶C O nG 5.¶C won't beH 5.¶nNo cF 3 5.¶C 2 6.¶A cF 2 6.¶nNo cF 4 6.¶nNo cF 3 5. 1 can't$%'¶$%`won't$%'¶$%`O nG$%'¶$%`won't beH$%'¶$%`O nG beH$%'¶$%`O nGKtheJto$%'¶$%`nG OKtheJto$%'¶$%`nG O beH$%'¶$%`isn'tH$%'¶$%`is unIto 2 is incapIof$%'¶$%`isn't capIof$%'¶$%`cannot De 3 can$%'¶$%`isH$%'¶$%`is G goQ to$%'¶$%`can G$%'¶$%`O G beH$%'¶$%`O G 4 is capIof$%'¶$%`can De$%'¶$%`O be capIof 5 E a 8$%'¶$%`Le a 8$%'¶$%`De eatQ a 8$%'¶$%`Le a 7 8$%'¶$%`E a 9$%'¶$%`De a 9$%'¶$%`E a B 9$%'¶$%`P a 9$%'¶$%`De a B 9 6 EQ a 8$%'¶$%`LQ a 8$%'¶$%`DQ eatQ a 8$%'¶$%`LQ a 7 8$%'¶$%`EQ a 9$%'¶$%`DQ a 9$%'¶$%`EQ a B 9$%'¶$%`PQ a 9$%'¶$%`DQ a B 9 7 delicious$%'¶$%`fresh$%'¶$%`Ly$%'¶$%`refreshQ$%'¶$%`wonderful 8 salad$%'¶$%`cake$%'¶$%`ice cream cone$%'¶$%`meal$%'¶$%`drink$%'¶$%`steak$%'¶$%`chicken dinner$%'¶$%`Mof cake$%'¶$%`Mof pie$%'¶$%`cookie$%'¶$%`sandwich 9 sonnet$%'¶$%`poem$%'¶$%`story$%'¶$%`play$%'¶$%`song$%'¶$%`Mof music B beautiful$%'¶$%`wonderful$%'¶$%`inspirQ$%'¶$%`amazQ$%'¶$%`superb D experienc E enjoy F omputer G ever H Ito I able J ability K have L tast M piece O will P understand Q ing ``` Output exceeds TIO limitations. I wanted to use `%`` stages to avoid all the `$%'¶$%`` but for some reason that doesn't do what I want. Edit: Saved 57 bytes thanks to @fireflame241. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 23353 bytes Yup. Most of it won't fit in an answer so... Both the code and the TIO link are in pastes. [**Code**](https://pastebin.com/Xh9VnJVG) (a hexdump of the code) [**TIO link**](https://pastebin.com/PM42TLBf) (the output exceeds TIO's limitations) ]
[Question] [ # Task Your task is to write a program that will take input, and then output the lyrics to [We Are Number One](https://www.youtube.com/watch?v=PfYnvDL0Qcw), changing specific words. The input will contain both the words to be changed, and the replacement word. ## Input The input will be in the following format: ``` one, two\n net, villain\n ``` (`\n` is a newline, it's not actually visible.) The input is assured to be this format, and the first word will always be a word the lyrics contains. But you can take input in whatever format you prefer the most. ## Output Your output will be the entire We Are Number One lyrics, but with the words that are given in the input swapped. Original lyrics: ``` Hey! We are Number One Hey! We are Number One ``` Now listen closely Here's a little lesson in trickery This is going down in history If you wanna be a Villain Number One You have to chase a superhero on the run Just follow my moves, and sneak around Be careful not to make a sound (Shh) (CRUNCH) (No, don't touch that!) We are Number One Hey! We are Number One We are Number One Ha ha ha Now look at this net, that I just found When I say go, be ready to throw Go! (Throw it on him, not me!) (Ugh, let's try something else) Now watch and learn, here's the deal He'll slip and slide on this banana peel! (Ha ha ha, gasp! what are you doing!?) Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number One Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number One Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number One Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number One Hey! Hey![Source](http://genius.com/Lazy-town-we-are-number-one-lyrics) ## Rules * The first word per input is assured to be in the lyrics. * Your code must be case-insensitve (`one` as input will replace `One`) * Trailing newlines are allowed. * The input may be lower and uppercase, and the resulting output must have the same casing as the provided input. * The input **can** try to replace e.g. `one` with `one`. If you replace it or not, is your choice. * "Words" are sequences of characters seperated by space or commas, not by anything else (e.g. Hyphens), therefore `Ba` is not a valid input, but `Ba-ba-biddly-ba-ba-ba-ba` is. ## Example case Input: ``` one, three net, villain ``` Output: ``` Hey! We are Number three Hey! We are Number three ``` Now listen closely Here's a little lesson in trickery This is going down in history If you wanna be a Villain Number three You have to chase a superhero on the run Just follow my moves, and sneak around Be careful not to make a sound (Shh) (CRUNCH) (No, don't touch that!) We are Number three Hey! We are Number three We are Number three Ha ha ha Now look at this villain, that I just found When I say go, be ready to throw Go! (Throw it on him, not me!) (Ugh, let's try something else) Now watch and learn, here's the deal He'll slip and slide on this banana peel! (Ha ha ha, gasp! what are you doing!?) Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Hey! # Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the author of the shortest code in bytes wins! [Answer] ## PHP, 666 bytes I suppose this is a rather appropriate code size for a song about Villains... ``` <?$s=gzinflate(base64_decode("zVLNitswEL4b/A6TUxLwPkNh99BkDynsT5ceJ9YkUjPWBEle47fvjJVCoWyh0EPRYMme8cz3ox3Nq7Z5I8BEcBiHIyX4Eqltdh8l6jrIBBxyoQg9Syae7ZdE6wyoiVKYgClniRAilBT6CyWtefEhg8ZZQjyDk2nJ68cilt6fYJYRJowR4ajD4WtgRi35FcI3LfH4TlAEeo/Z6vJ4peQpCejI4gnSGNvmccwFTsKscIcZBnmn3AFGBzkSXpScjNG1zT1Br0RPI0OUYn0HvCxta37z7P1Wt4en18PDzk4H6RR+XFvx2HsdiWW1reL8jZwfKLxDZahxU1pEseooUy9S6ZZxsIfvld+C8c2rGXvIOKu6namXCN1sZIpPMrXNZ1EMmxd7gVBMKB+GbmE8kIHfvJ59p74VtbGkWdkPpDPVKeJM2wpmwqJ8TUMmTLEDX3030R0hG9k1M2QO1yo1B0fVFoV/xKgLrkRsaH4S7eCM+bqCyYiZInYPnN2S1aebrPd4d9QIzvG8nG6hXPHut/iDDf+g0f+EpTay5w8="));foreach($argv as$a){@list($a,$b)=explode(",",$a);$s=str_ireplace($a,$b,$s);}echo $s; ``` Usage: `php numberOne.php one,three net,villain` [Answer] # PHP, ~~661~~ 652 bytes ``` for($s=base64_decode(gzuncompress("eJy1ks1u2zAQhO98itXJNqA8Q4DkULsHF2jzgx7X4tpkvSINkorAt+9QaoECyaE9VNoDQa44M99qL7Uzr0KchI7TeJJEX4KY/cfbeI5xJvW5SKBBYxataE6yycTYL0WFVHKOgXygkvxwlVTNk/OZUJfow4VsnJdjbJaI08OZapxo5hCYTlClF6/K6PhD+zs6HL8JlUiD49za8nST5CRFgl5xQmkK5vOUC52jKpyOlcb4JrknDpZyEL4iU5yCNQ9CA+KdJ6UQS7t15Oty6XK8/ebczmwfvz4fH/dYHGMP32HTOqfBQY1LtwOQv4b3Ec49IxNqxRoj3EGgwQpS+kWEDvRjTdRsvTqAP1DmCpZ9g5WEbW32i0txNp9iZ7ZPbUm+NCzOj/2ScBT43T5fXI8JFQyspIqwo0APQxHNslt8zFwQsAFT4RR6cuuAG2ArrAi4UaWs/rZiVW9lnQCMnzjgpZuIwsnvgD1dON86mluihqEN3La/obtvFB/47oTy1mpdVr8KEfnuXZnuXz94D/9/K3bLf/AT6bEYSw"));$t=fgetcsv(STDIN);)$s=preg_replace("#\b$t[0]\b#i",$t[1],$s);echo$s; ``` `gzinflate` is 3 bytes shorter than `gzuncompress`, but `gzcompress` has the shorter output. And: The other PHP answer replaces substrings, not words. I´d save 8 more bytes with that. **breakdown** ``` for($s="text"; // init text $t=fgetcsv(STDIN);) // loop through STDIN lines $s=preg_replace("#\b$t[0]\b#i",$t[1],$s); // replace pairs echo$s; // output ``` [Answer] # Python 2.6, 695 bytes ``` import re import zlib,base64 a=input().split(', ') t = zlib.decompress(base64.b64decode(b'eJzNks+KGzEMxu9+Cs0pCcw+w8LuoUkPKbT7hx6VsRK70VjB9uzgt68000KhWyj0UiKCsYW+7/tp9tQ690qAmeA4jSfK8CmR279/7dxRZuBYKiUYWApx095MmwKo97UyAVMpkiAmqDkOV8rNPYVYQOsiMV3Ay7w862UVfT2cockEM6aEcFJReInMqB2/SH/VjoBvBFVgCFisrUw3yoGygOrVQJCn5D5OpcJZmNXp2GCUNyo9YPJQEuFVI8mUvHsgGDTdeWJIUm3qiNdl6PK8/RLCzm0fPz8fH/d6OEqvvtPGOqchqBrWbqdA/prdezT3qJm0Vqwi6k4FDFai2i8icIBvayKz9RoU/AEKNmXZG6xM6JvZryHL7D5I57ZPdoRYDUuIY78kHEn9bp8vodcNVV1YzU3DjqR6uhTiQrvFx4xVAxowJsyph7Au2AB7QtaAG2YoHG8rVo6e1g2o8RMm/cGNiNXJz4A9XLDcOpgtkWGwhXv7Grp7o/iAdyet6D235fSjNCLe/VZ/gv7PU/4TG8sU+/sO/HItbg==')).decode('utf8') for i in xrange(0,len(a),2): t = t.replace(a[i],a[i+1]) print t ``` **Output** Hey! We are Number three Hey! We are Number three ``` Now listen closely Here's a little lesson in trickery This is going down in history If you wanna be a Villain Number three You have to chase a superhero on the run Just follow my moves, and sneak around Be careful not to make a sound (Shh) (CRUNCH) (No, don't touch that!) We are Number three Hey! We are Number three We are Number three Ha ha ha Now look at this villian, that I just found When I say go, be ready to throw Go! (Throw it on him, not me!) (Ugh, let's try something else) Now watch and learn, here's the deal He'll slip and slide on this banana peel! (Ha ha ha, gasp! what are you doing!?) Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba We are Number three Hey! Hey! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 842 bytes ``` •®_Dzîü!úïæ²|ˆ9¶iˆtˆEC}#©ÿ®cÖ:|®¥÷K*œÒÅ5œ1‚ÂlÊΤNç·’±Ðá×ÍÐý5WÝ㢮ìÖ$hVbPGwηM;9O|‰¶ÉèëøËöç¡QÒµ5‚aC}.*gbJǦ>);&f€ZÛ}íóÉh\„Ú;Ts§ÞT¿QZëDò©®#ÑSHžûd¦Óéó”ó\ê§ø5|PšÍÖcyÐÁ:hŒ02¨ÄùSûíi¯—àR›ÿR{3Í)Ú×E<u¥°¼:—jth€ƒWƪâþ=—vJ†ÀJûy6Áv\TÈÞåšöQë£Âb„ˆ@Ò6^#ˆL*ÁöªAWçàˆÌä£#«ùÁ°è;sq¯¸GšìááЩ–ob¾§m^¹+ò"-Å£‘u·ãÿ?ù÷7Á^)8GÑ<oßÝ7Åjœq–[—'XuDÔÈìïÃ÷áÓ´‚ñ)©™à$ÝS¢¦(ð8M'§›¬§³N(En"H#«Ÿß½µ`Å´½axxq\òÝP@HÓ‘š£m—‹váøÃGàhT™ËUc·€ô~¥CEw6G¥Âã”ú¾&º™e,"AÂy±²ÅÜÚMâ2qtBaaª.^`òÍ–Ú$¦~z¢PÇR²”6â#”½Ì0ÂVêž]oɦs¯Ž½Ç˜ûRG™¸§I?™µ¦½ÀÓþæ8i‚%‘L#]ÒXÓ†A“r*Å;E%c¾0H;ø<½yÎ=^ù_í<ÃòõŽŸq!ùßN÷wP0q1¹‰~Õ¿´zÿgI,¸$ž¬…ÃÊGÖ¢e¸ŒHFMcw,Î()¼ü»T×–r{&h·q²¬5¡ýWÑÈú¬«ñÚRóD›<üŽ‹Nê*¹f¦›þÆYÓ–hýÂ}§l<Ñò<Ýù†ïÓi#‹k€ö#[ûlù_=¡ç·FÜØ]¢n©l›ÜÍ,ɈØrôN5Ô¸¹NGúoÝ][{½ãÚ;S*ÌåÙC€\À=k½;qU,pT$Ÿ5uÕœ¼§/›Kàô™eéù‚.Úæ·vx¾Xugvš–ûî?øc}|/žr¡¶µt…’öà,2;ˆ«=ÆF5£ØÓ¯~À|ýÝÓß]nLÔ<ëïÂåkQ`µ3DxБ!´‚Ù7AÏmi¦nvgã…ñ•121B"012345678"¶" ()!,-'?"«‡¹',¡vyN²',¡è.:} ``` [Try it online!](https://tio.run/nexus/05ab1e#JVRpV1NXFP3eX1ESlKERGRpAEooIGEBIGaI4ADI0EpShARJAhvWIEouK1QQRUyIZ5AVIJBAgAyFhrbPX65f8i/dH6Hmrn@5d7927zz5773OvZCFAh0/xhmI4xEUezhGFSLHFnPMWxUdzzpmcs6lhSU37uKTDYWzWLNIh7SJxr1hyw4VVreQukwUPHGN4iw/03YgQJWThKx3jI/z4gnVeM9oeeBEkLoUINvMtD4Y6DLN8PNGuu/X7oiwcURxr2EMYSbxDnDH8nXDRmZahBxuWSopHhlqZo/hbke76M9kReYx/lvADJ1iz9MrCN3h0pmkK4ZuJLjsfI9yIGO3ToRqfupulLNJ/kAg39nEiC16c9OKAzya1ix2Sn@ltDs8zxZUai@QqLac9vEaqG2n8GKWoLGzA1yUL57jsWqjAehE8@NKkt9EuHdFFDf9@PmNhOv@6euCkAwSQreWP9lZZ8EFoRXq@Eiv2XhP@wjfscrV4J8IUhGOISeect@Gq7FfnnG3FWEGcDup7EIIv58R7fKegmsJIYYWOsKebtlKUkgZGiLCofnykfVlwTw5RlkLj/ZT6BTHVDaxSUBa2bJRAEJd1fDlRhZX@omoDPuknsQNvFVafS24rX33CNAse2hqxwdwi7PkrJBjXTaeKmcdFjP86AF8@vN3smliIo@r2AgqxFBShEJ0YC5smVM1MUUpihzJ0NsDVTykzODdn7UUM3o7bzXAzG8lPwXEuJgspOxdI4pUBPotJQX93f5ij4ojgdJl2G5pmKw0cLAeCiknnlL1O53zKrFHVwzFPxxzQVWzD045AuXXmzuAgHZT0D3CpdW4HnnwSl19SoANvuijGCJUIqHmhDN6XwvEAB1K2bxJrJE5TVMrw5ze5baS7DFyCkhRqqVM2ZyTyH4GzkoVYPcpSXOMW2tR9cD1UuvHVy8L2VDFWdU3Xhilb2qxDUk@ZeXyo7UfqKX7oWccYzqSMlLTmsQE7RiRmO0qtZZTikC/jM13S6UtcjrRoKJkvZSkiCyLfeWvAJgXMlJRczXfbh2c1@FBYRBe4oLQJX7jBqYXrFkpYKUYRLfmR6cEnNk4xI4xjeLpw0sje6HEhZVhpIw6KKfWMRCW6WTgfKeTdFmTgWKLQmJ4vx/Q8kSklp1G4R1mq1AvFirj6CdJj3EstV@FJvsuSb/VRYIL2xxSwbaxrsMYR3ZrCqVGLDRYvZTTgfBLevicLrF6Qh7G7mCO8i68NDNkLofYFZXTW@5o/TflSUmvDZ8lNFxS6yYD34MOpYjNPJ7PxlPCEiZSwz1H2oW3ELvkVc9M4rENyeGnxppSdIj/F6WyGdeNXhp8Kn6Zcl3NSuBbOu1qerS0OcXQZwiJ362Und/om2rCh56clyuHafdE5QGcVjXP4yM7m/R/3r1X1@Ht8lMQJ@4gSPxHH/CyWlZfdUZWWlVf8qq2sqlZRXPVzYVGe5kZBnYrCsuCnVIGG/PZ5I8WUDfZKapauroy28SHzlKbHrHk0adOYLKPTPzVYzOZpM@/N85oWXgZn/gM "05AB1E – TIO Nexus") Simplistic approach, didn't do anything but replace symbols with integers, convert from base-121 to base-214. Then I decompress it, re-replace the characters and perform replacement on the words. For testing I suggest replacing pronouns with other pronouns. [Answer] ## Python 3.4, 666 bytes ``` import zlib,base64,sys,re;s=zlib.decompress(base64.b85decode(b'c%03W&uSwv494$%3e71AOrN399-8!!!fyYtM`f(UZZuY~Jste^D|@=Iuw5whQX+z}g}(3mX|_~4^Fn};U_XrqitrG~Y(Ks>W-l|aPniM?EQz>iZ=_WM)cc&7fGH&j-~;67hcm@u9-U91brK&=U}bL4dYMIEcSk5P!Hgjw98?sZJu_;@U(&y{!{Hl278o3++LopZMMqIU^|B*~Q!w{a%5W5BbvhOp<&9Dg7%Zefc-BZV1#4~y22FRI7=q+Fb;NTU+Md@xo!gl8?T@GZ?N$$a>D6~w)y`>fs)o7SD3H&?`v|AmqNdVXz>26pm8iG^<-W<l4qlf`)!2(u^gBpclxAOXMM7I@fb62o=1w}Zeym6Exq@+i>|4f>)baZ1<a*sv)|KU0H10^Mr)wcjv}rzO%o?#GW5O7EaLbA-VoS)HaK#LX{bd2m-qNxIHGaULKe!OFI{6c@hZCkt2XjqSIn<Tg`aN{ljpGeo9kjf)T-xcqG$UU9Q~$&M<tg99Mw?RqegpM6EsO')).decode('utf8'); for a in sys.argv[1:]:x,y=a.split(', ');s=re.sub(x,y,s,99,2); print(s) ``` Edits: * Used regex replace instead of replace so that it works case insensitive. * Used command line to get the parameters instead of input. ]
[Question] [ # Challenge Write a full program/function to Demolish a given building at the rate **1 floor per second**. # INPUT Input is a **building** through **STDIN**(or whatever is called in your language) or through an **ARGUMENT** of a function. **t=0 s** ``` | |#| {#} |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **input consists of :** * `|` marks start and end of a floor. * `{`,`}` marks the floor with explosives. * `#` is a window which is for decoration . * is space, which is everywhere inside the floors where `#` is not there. * `T` marks ground(cannot be demolished). * `*` marks the detonated floor. **Input rules :** * building starts from top with one `|` and ends on ground(with no(`T`)=no (`char used in ground floor`)). * a window `#` is at every odd place inside every floor. * `T` marks the end of your input. * only **one** floor consists of explosives. * every floor is made of **odd** no. of chars. * as you ascend down the floors, the floors can either be of **equal size** of that of previous floor or can be **2** chars bigger. * Input can be taken as an array of `chars` or `strings`. **Output :** **t=0.5 s** ``` | |#| *** |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=1 s** ``` | |#| |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=1.5 s** ``` | *** |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=2 s** ``` | |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=2.5 s** ``` * |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=3 s** ``` |# #| |# # #| |# # #| |# # #| TTTTTTT ``` **t=3.5 s** ``` ***** |# # #| |# # #| |# # #| TTTTTTT ``` **t=4 s** ``` |# # #| |# # #| |# # #| TTTTTTT ``` **t=4.5 s** ``` ******* |# # #| |# # #| TTTTTTT ``` **t=6.5 s** ``` ******* TTTTTTT ``` **t=7 s** ``` TTTTTTT ``` **Output rules :** * every floor ends with one `newline` character. * ground may/may not have a trailing newline. * output the building(or whats left of it) every 0.5 s. * **Output** is like animation which is modified every 0.5 s and is displayed. (Also feel free to post GIFs with your answer) This is a **Code-Golf** so the code in shortest bytes wins! *last date of submission is exactly 5 days from now* (But you know what ? Winning is not everything, feel free to try this challenge in your favorite language, even after a winner has been declared :] ). **EDIT :** I changed the way you take input (my bad actually). [Answer] # Vim, ~~41~~ 38 bytes ``` qw:sl 500m␍q/{␍qqjk^v$r*@wdd:-␍@w@qq@q ``` Here, `^` is used for a literal caret; ␍ is used for CTRL-M. ## Explanation `qw:sl 500m␍q` sleeps half a second, while recording the half second sleep as macro w. `/{␍` moves to the floor with explosives. `qq` begins recording macro q, which will recursively call itself. `jk` moves down and up; this generates an error if you're on the last line (ground); the error terminates the recursive macro. `^v$r*` replaces everything from the first non-whitespace character to the end of the line with \*'s. `@w` waits half a second, then `dd` deletes the current floor. `:-␍` moves up a floor without terminating the macro if you're on the top line. `@w` then waits another half second, and `@q` calls the q macro (initially empty). `q@q` stops recording the macro q, then calls it, triggering the recursion. ## Animation [![vim demolition](https://i.stack.imgur.com/zAO6Z.gif)](https://i.stack.imgur.com/zAO6Z.gif) [Answer] ## JavaScript (ES6), ~~208~~ 198 bytes ``` f= (t,s=f=>setTimeout(f,500),v=t.value.split(/(\S.*\n)/),i=v.findIndex(s=>/}/.test(s)),c=_=>t.value=v.join``,d=_=>c(v.splice(--i,2),v[3]&&s(e,i?--i:++i)),e=_=>c(v[i]=v[i].replace(/./g,'*'),s(d)))=>s(e) ``` ``` <textarea id=t rows=9> | |#| {#} |# #| |# # #| |# # #| |# # #| TTTTTTT </textarea><input type=button value=Go! onclick=f(t)> ``` [Answer] # Java 7, ~~589~~ ~~477~~ 476 bytes ``` import java.util.*;void x(List<String>b,int x)throws Exception{Thread.sleep(500);int i=0,l=b.size(),z=x;String w;for(;i<l;i++){System.out.println(w=b.get(i));if(w.contains("{"))x=i;}System.out.println();w=b.get(x);i=w.contains("*")?1:0;if(i>0)b.remove(x);else b.set(x,z<0?r(w,'{','}'):r(w,'|','|'));if(l>1)x(b,i>0&x>0?x-1:x);}String r(String s,char y,char z){int a,b;return s.substring(0,a=s.indexOf(y))+s.substring(a,b=s.lastIndexOf(z)+1).replaceAll(".","*")+s.substring(b);} ``` Ok, it's a mess/long, but this challenge has so many annoying things for Java.. Printing multi-line; `Thread.sleep(500)` which requires a `throws Exception`; replacing a substring between two delimiters with an equal amount of `*`; etc. All this causes the program to be pretty big.. It can defintely be golfed some more, maybe even halved with a different approach, but at least there is an answer now. ;) **Ungolfed:** ``` void x(List<String>b, int x) throws Exception{ Thread.sleep(500); int i = 0, l = b.size(), z = x; String w; for(;i<l; i++){ System.out.println(w=b.get(i)); if(w.contains("{")){ x = i; } } System.out.println(); w = b.get(x); i = s.contains("*") ? 1 : 0; if(i>0){ b.remove(x); } else{ b.set(x, z < 0 ? r(s, '{', '}') : r(s, '|', '|')); } if(l>1){ x(b, i > 0 & x > 0 ? x-1 : x); } } String r(String s, chary, char z){ int a, b; return s.substring(0, a=s.indexOf(y)) + s.substring(a, b=s.lastIndexOf(z) + 1).replaceAll(".", "*") + s.substring(b); } ``` **Test code:** ``` import java.util.*; class M{ void x(List<String>b,int x)throws Exception{Thread.sleep(500);int i=0,l=b.size(),z=x;String w;for(;i<l;i++){System.out.println(w=b.get(i));if(w.contains("{"))x=i;}System.out.println();w=b.get(x);i=w.contains("*")?1:0;if(i>0)b.remove(x);else b.set(x,z<0?r(w,'{','}'):r(w,'|','|'));if(l>1)x(b,i>0&x>0?x-1:x);}String r(String s,char y,char z){int a,b;return s.substring(0,a=s.indexOf(y))+s.substring(a,b=s.lastIndexOf(z)+1).replaceAll(".","*")+s.substring(b);} public static void main(String[] a){ try{ List<String> l = new ArrayList(){{ add(" | "); add(" |#| "); add(" |#| "); add(" {# #} "); add("|# # #|"); add("|# # #|"); add("|# # #|"); add("TTTTTTT"); }}; new M().c(l, -1); } catch(Exception e){} } } ``` **[Try it here.](http://ideone.com/8wN33V)** (On ideone it outputs at once and ignores the `sleep`..) [Answer] ## Haskell, ~~245~~ 221 bytes ``` import System.Posix.Unistd r=reverse c#l|(i,j)<-span(<'!')l=i++(c<$j) f[b]=[[b]] f s|(h@(a:b),d:c)<-break(elem '{')s=(h++'*'#d:c):(h++c):f(init h++'{'#last h:c)|1<2=r<$>(f$r s) mapM((usleep 500000>>).mapM putStrLn).init.f ``` Usage example: ``` mapM((usleep 500000>>).mapM putStrLn).init.f $ [" |"," {#}"," |#|","|# #|","|# #|","TTTTT"] ``` How it works: ``` c#l|(i,j)<-span(<'!')l=i++(c<$j) -- helper function that takes a char c and -- a string l and keeps the leading spaces -- of l and replaces the rest with c -- f takes a building (list of strings) and -- makes the sequence of collapsing buildings -- as a list of list of strings f[b]=[[b]] -- base case. Stop when there's only a single -- floor left f s -- if the building has at least two floors |(h@(a:b),d:c)<-break(elem '{')s -- if there is at least one floor above the -- explosion =(h++'*'#d:c) : -- return the current building with the -- floor to explode replaced by * (h++c) : -- followed by the current building with -- the exploded floor removed f(init h++'{'#last h:c) -- followed by a recursive call -- with the next to explode floor marked -- with '{' |1<2=r<$>(f$r s) -- if all top floors have exploded, reverse -- the left over floors, let them explode -- and reverse the floors of each building -- again. f -- let the building collapse init -- f comes with an additional building with -- a single floor of * only -> drop it mapM( ) -- for every building (usleep 500000>>) -- delay 0.5 sec mapM putStrLn -- and print the floors ``` Note: there's also `threadDelay` from `GHC.Conc` instead of `usleep` from `System.Posix.Unistd` which is a little bit shorter, but it only works with the `GHC` compiler, so it wouldn't be a generic `Haskell` answer. [Answer] **C, ~~314~~ ~~287~~ ~~281~~ 271 bytes** ``` s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(*p<33)putchar(*p++);if(!t)e=*p=='{'?i:e,s+=2;do{putchar(e==i&&t%2&&*p>16?'*':*p);}while(*p&&*p++>16);}while(*b[i++]-84);if(t++%2)b[e]=0,*b&&e>0?e--:e++;Sleep(500);}while(t<s-1);} ``` -10 after changing `!=` to `-` and avoiding char literals when it is possible, as well as `isspace` (many thanks to H Walters). But ungolfed code remains unchanged. ``` s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(isspace(*p))putchar(*p++);if(!t)e=*p=='{'?i:e,s+=2;do{putchar(e==i&&t%2&&*p>0xF?'*':*p);}while(*p&&*p++>0xF);}while(*b[i++]!='T');if(t++%2)b[e]=0,*b&&e>0?e--:e++;Sleep(500);}while(t<s-1);} ``` -6 bytes after applying coma and deletion of `{}` after two `if`. ``` s,e,t,i;f(char**b){char*p;do{system("CLS");i=0;do{while(!(p=b[i]))i++;if(!*b&&e==1)e=i;while(isspace(*p))putchar(*p++);if(!t){s+=2;e=*p=='{'?i:e;}do{putchar(e==i&&t%2&&*p>0xF?'*':*p);}while(*p&&*p++>0xF);}while(*b[i++]!='T');if(t++%2){b[e]=0;e=*b&&e>0?e-1:e+1;}Sleep(500);}while(t<s-1);} ``` -26 bytes after little optimization, removal unnecessary parentheses, as well as change local variables to global (with auto 0 initialization) and `b[0]` by `*b`. ``` f(char**b){int s=0,e=0,t=0;char*p;do{system("CLS");int i=0;do{if(!t){s+=2;if(strchr(b[i],'}'))e=i;printf(b[i]);}else{while(!(p=b[i]))i++;if(!b[0]&&e==1)e=i;do{putchar((e==i&&t%2&&!isspace(*p))?'*':*p);}while(*p&&*p++!='\n');}}while(b[i++][0]!='T');if(t%2){b[e]=0;e=(b[0]&&e)?e-1:e+1;}t++;Sleep(500);}while(--s>1);} ``` Test code with ungolfed `f`: ``` #include <stdio.h> #include <windows.h> // to use Sleep and system s, e, t, i; f(char**b) { char*p; do{ system("CLS"); i = 0; do { while (!(p=b[i]))i++; // skip demolished floors if (!*b && e==1) e = i; while (isspace(*p)) putchar(*p++); // print spaces if (!t){ s += 2; e = *p == '{' ? i : e; } // find a bomb and count steps at the first iteration do{ putchar(e == i && t%2 &&*p>0xF ? '*' : *p); // print floor or * for next floor at odd step } while (*p && *p++ >0xF); // >0xF is instead of !='\n' } while (*b[i++] != 'T'); // until the ground if (t++ % 2) { b[e] = 0; // delete the demolished floor e = *b&&e>0 ? e-1 : e+1; // and determine next floor to be demolished } Sleep(500); } while (t<s-1); } int main(void) { char * arr[] = { " |\n", " |#|\n", " {#}\n", " |# #|\n", "|# # #|\n", "|# # #|\n", "|# # #|\n", "TTTTTTT" }; f(arr); } ``` [Answer] ## Perl, 153 bytes ``` for(@a=<>;$a[$i]!~/{/;$i++){}for(;$a[0]!~/^T/;`sleep .5`){if($P=!$P){$a[$i]=~s/(\S.*\S|\S)/"*" x length($1)/e}else{splice(@a,$i,1);if($i){$i--}}print@a} ``` This uses GNU sleep command to wait for 500 milliseconds. Ungolfed version ``` for(@a=<>;$a[$i]!~/{/;$i++){} for(;$a[0]!~/^T/;`sleep .5`){ if($P=!$P){ $a[$i]=~s/(\S.*\S|\S)/"*" x length($1)/e } else { splice(@a,$i,1); if($i){$i--} } print @a } ``` [Answer] # PHP, ~~286~~ ~~282~~ ~~274~~ ~~234~~ 229 bytes ``` <?for($a=$argv,array_shift($a);!strstr($a[+$i++],"{"););while($a[0][0]!=T){$x=&$a[$i-=$i>0];$x=str_pad(substr($x,0,strspn($x," ")),strlen($x),"*");eval($p='echo join("\n",$a),"\n\n";usleep(5e5);');array_splice($a,$i,1);eval($p);} ``` takes input as list of strings from command line arguments (no newline character!) save to file, run with `php <filename> ' |' ' |#|' ' {#}' ' |# #|' '|# # #|' '|# # #|' '|# # #|' 'TTTTTTT'` **breakdown** ``` <? for($a=$argv,array_shift($a); // import input !strstr($a[+$i++],"{");); // find explosives while($a[0][0]!=T) // loop while ground not reached: { $x=&$a[$i-=$i>0]; // move up if possible, reference floor $x=str_pad( substr($x,0,strspn($x," ") // keep leading spaces ),strlen($x),"*"); // replace rest with asterisks // print and wait eval($p='echo join("\n",$a),"\n\n";usleep(5e5);'); array_splice($a,$i,1); // remove current floor eval($p); // print and wait } ``` ]
[Question] [ # Preface There are many "draw x flag" challenges, and upon searching it turns out there are no challenges to draw the union Jack! I feel like this would be a harder flag to draw but it should still be possible. # Challenge Draw the Union Jack. It can be outputted to a file in any freely available graphics file format or drawn onto the screen. * Code Golf rules apply, shortest code in bytes wins. * [Standard loopholes apply.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * No builtins for flag drawing allowed. Dimensions shall be as below. Minimum size 600x300 pixels (or units if your language supports only scalable graphics.) Maximum error 1 pixel. Colours shall be red, white and blue as defined by your language or its documentation, or #CC0000, #FFFFFF and #003399 per [Wikipedia page.](https://en.wikipedia.org/wiki/Union_Jack) [![enter image description here](https://i.stack.imgur.com/lHE1z.png)](https://i.stack.imgur.com/lHE1z.png) [Answer] # BBC BASIC **Rev B, 234 bytes** Instead of drawing one white and one red cross, we draw 100 progressively narrower crosses, switching from white background to red foreground at a coordinate of 60. ``` p=20761m=1049w=600h=300F.i=-1TO1V.29,w;h;18;4,m;134*i;0;m;w*i;-233;p;0;466;m;0;67*i;m;-466;h*i;p;932;0;18;1,m;511*i;h*i;25;89*i;0;29977;0;0;m;w*i;-h*i;28953;0;45*i; N.F.c=-100TO0q=25881-c DIV60*512V.m;-c;-h;q;c;h;m;-w;-c;q;w;c; N. ``` Download interpreter free at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> **Fully golfed, 249 bytes** Single byte VDU codes e.g `25,0` combined into double-byte little endian e.g `25;` and maximum use of constants for common values. Keywords compressed to abbreviated form, e.g. `FOR`=>`F.` (interpreter expands automatically.) ``` p=20761q=26393r=25881m=1049c=100w=600h=300F.i=-1TO1V.29,w;h;18;4,m;134*i;0;m;w*i;-233;p;0;466;m;0;67*i;m;-466;h*i;p;932;0;18;1,m;511*i;h*i;25;89*i;0;29977;0;0;m;w*i;-h*i;28953;0;45*i; N.V.m;-c;-h;q;c;h;2m;-w;-c;q;w;c;m;-60;-h;r;60;h;m;-w;-60;r;w;60; ``` **Semigolfed** Raw VDU codes. In BBC BASIC, characters can be sent to the VDU controller like `VDU65` (prints an A.) There are certain special characters particular to the BBC for graphics. These must be followed by several other bytes to specify coordinates, etc. Here we use `PLOT`=>`VDU25`, `GCOL`=>`VDU18`, `ORIGIN`=>`VDU29`. ``` c=100w=600h=300 :REM constants 100,width,height FORi=-1TO1 :REM loop -1 and 1 (0 draws nothing) VDU29,w;h; :REM set origin (bring inside loop for golfing reasons) VDU18;4 :REM change to blue and draw triangles VDU25,4,134*i;0;25,4,w*i;-233;25,81,0;466;25,4,0;67*i;25,4,-466;h*i;25,81,932;0; VDU18;1 :REM change to red and draw parallelograms VDU25,4,511*i;h*i;25,0,89*i;0;25,117,0;0;25,4,w*i;-h*i;25,113,0;45*i; NEXT VDU25,4,-c;-h;25,103,c;h;25,4,-w;-c;25,103,w;c; :REM draw white background rectangles VDU25,4,-60;-h;25,101,60;h;25,4,-w;-60;25,101,w;60; :REM draw red foreground rectangles ``` First we draw half the diagonal parts: 2 blue triangles and 2 red parallelograms. Then we change the scale from -1 to +1 and draw the other half. Finally we draw the horizontal and vertical parts on top: 2 white rectangles to form a white cross, then 2 red rectangles. The image after the first iteration of the loop is shown below, along with the final image. [![enter image description here](https://i.stack.imgur.com/xiKoT.png)](https://i.stack.imgur.com/xiKoT.png) **Ungolfed code** BBC basic remembers the last 2 locations of the graphics cursor. PLOT81 draws a triangle between the new coordinates specified and these last two locations. PLOT113 and PLOT117 draw a parallelogram in a similar way: three corners of the parallelogram have to be given in the order they are found going round the perimeter. The last three bits of the PLOT code define whether the given coordinates are absolute or relative, and whether foreground or background colour is used. The more significant bits define what type of shape is drawn (point, line, triangle, parallelogram, rectangle, etc.) ``` ORIGIN600,300 :REM move the origin (which will be centre of flag) away from the corner of the screen. FORi=-1TO1 :REM at scales of -1 and 1, plot half each of the diagonal parts (i=0 plots nothing). GCOL0,4 :REM blue foreground colour PLOT4,134*i,0 :REM absolute move to peak of upper/lower triangle PLOT4,600*i,-233 :REM absolute move to left hand corner PLOT81,0,466 :REM relative move to right hand corner, plotting triangle PLOT4,0,67*i :REM absolute move to peak of left/right triangle PLOT4,-466,300*i :REM absolute move to lower corner PLOT81,932,0 :REM relative move to upper corner, plotting triangle GCOL0,1 :REM red foreground colour PLOT4,511*i,300*i :REM absolute move to long edge of flag PLOT0,89*i,0 :REM relative move to corner of flag (top right / bottom left) PLOT117,0,0 :REM absolute move to centre of flag, plotting parallelogram (stripe) PLOT4,600*i,-300*i :REM absolute move to corner of flag (bottom right / top left) PLOT113,0,45*i :REM relative move to short edge of flag, plotting parallelogram (stripe) NEXT :REM diagonal parts completed, now plot vertical/horizontal parts on top. PLOT4,-100,-300 :REM move to bottom left of vertical white stripe PLOT103,100,300 :REM move to top right corner, plot it in background colour (white) PLOT4,-600,-100 :REM move to bottom left corner of horizontal white stripe PLOT103,600,100 :REM move to top right corner, plot it in background colour (white) PLOT4,-60,-300 :REM move to bottom left of vertical red stripe PLOT101,60,300 :REM move to top right corner, plot it in foreground colour (red) PLOT4,-600,-60 :REM move to bottom left corner of horizontal red stripe PLOT101,600,60 :REM move to top right corner, plot it in foreground colour (red) ``` [Answer] # SVG, 298 bytes score excludes 3 unnecessary newlines added for clarity. ``` <svg xmlns="http://www.w3.org/2000/svg"> <path d="M67,0h466L0,267v-234L533,300h-466L600,33v232z" fill="blue"/> <path d="M0,0v22L300,172L45,300h-45L600,0h-45L300,128L600,278v22z" fill="red"/> <path d="M-10,110h270v-120h80v120h270v80h-270v120h-80v-120h-270z" fill="red" stroke="#fff" stroke-width="20"/> ``` Inspired by Siren's deleted answer (and in particular the saving in bytes from omitting `</svg>` at the end of the document), I came up with an SVG that is both dimensionally correct and slightly shorter. It consists of a blue path and a red path (filled, without strokes) for the diagonal parts and a red path (filled, with 20 unit white border) for the final cross. Because of the thickness of the white border, the specified dimensions of the cross must exceed the required dimensions by 10 all around. This works fine for me in Microsoft IE and Edge. Sometimes displays an "extra content at the end of the document" warning in Chrome. Here's how it appears without and with the final cross. 8 points are required to describe the blue path, 10 points to describe the red path, and 12 points for the final cross. The intersections of straight lines within the first two paths do not have to be given. [![enter image description here](https://i.stack.imgur.com/XLlVl.png)](https://i.stack.imgur.com/XLlVl.png) [Answer] # Logo, ~~260~~ 239 bytes ## (XLogo Interpreter) I used the Java-based [XLogo interpreter](http://xlogo.tuxfamily.org/) since it was one of the few Logo implementations I could find which supports setting the output window size. The XLogo editor normally saves files as procedures which are meant to be called. This program is written to be pasted into the immediate window instead. This saves about 9 bytes. ``` window setscreensize[600 300]setsc 4 lt atan 2 repeat 2[repeat 2[setpc 7 setpw 60 fd 400 setpw 20 lt 90 fd 10 lt 90 setpc 1 fd 400 lt 90 fd 10 rt 90]lt asin .8]home wrap setpw 100 setpc 7 repeat 2[repeat 2[fd 600 lt 90]setpw 60 setpc 1] ht ``` Since exact colors weren't required, I regolfed this to use built-in color numbers which saved several bytes. If you want to see a version with exact RGB colors, check the revisions. I also substituted a trigonometric calculation with a shorter equivalent. [![Union Jack flag output](https://i.stack.imgur.com/sxwsp.png)](https://i.stack.imgur.com/sxwsp.png) ## Ungolfed with commentary The only real trickery here is changing colors for the second pass of a loop, and taking advantage of the `wrap` feature which allows us to draw the horizontal stripes with very little effort. Since the flag height and width are both factors of 600, we can go forward 600 for either vertical or horizontal stripes and end up back at the center again. This avoids having separate cases for each, even if it does draw the vertical bar twice as often. We're saving code space, not clock-cycles. ``` to UnionJack #Initialize the screen window #Allow the turtle to overshoot the boundary without reappearing on the opposite side setscreensize[600 300] setsc 4 #blue background lt atan 2 #Turn left, preparing to draw first diagonal repeat 2 [ #Draw 2 sets of main diagonal bars repeat 2 [ #Each main bar is made of 2 spokes setpc 7 setpw 60 #Use a wide white pen fd 400 #Draw past the corner of the window setpw 20 #Make the pen narrow lt 90 fd 10 lt 90 #Do a 10px U-turn setpc 1 #Switch to a red pen fd 400 #Draw back to the center. lt 90 fd 10 rt 90 #Do a 10 px S curve back to center, ready to draw the opposite spoke ] #Finish spoke lt asin .8 #Turn for the next bar. ] #Finish bar home #Return to a sane heading wrap #Makes the turtle wrap to the opposite side if it overshoots the boundary setpw 100 setpc 7 #Wide white pen repeat 2 [ #Draw 2 crosses repeat 2 [ #Each cross has 2 stripes fd 600 #Overshoot the boundary so that we end up where we started at the center, leaving a stripe behind lt 90 #Rotate to draw the next stripe ] #Finish the stripe setpw 60 setpc 1 #Change to a narrow red pen ] #Finish cross ht #Hide the turtle end ``` [Answer] # Processing, 312 bytes This is the type of puzzle where Processing is pretty efficient. ``` int a=300,b=2*a,c=255,d=100;size(b,a);background(0,51,153);stroke(c);strokeWeight(60);line(0,a,b,0);line(0,0,b,a);stroke(c,0,0);strokeWeight(20);line(0,310,a,160);line(-22,0,a,160);line(a,139,b,-12);line(a,139,624,a);noStroke();fill(c);rect(250,0,d,b);rect(0,d,b,d);fill(c,0,0);rect(270,0,60,b);rect(0,120,b,60); ``` Results in: [![enter image description here](https://i.stack.imgur.com/ycziG.png)](https://i.stack.imgur.com/ycziG.png) [Answer] # Postscript (175 bytes) ``` 00000000: 880a 880a 928b 3020 3092 6b30 881e 9263 ......0 0.k0...c 00000010: 883c 3330 9263 883c 3092 6392 1692 142f .<30.c.<0.c..../ 00000020: 727b 2e38 8800 3092 9d7d 9233 2f77 7b31 r{.8..0..}.3/w{1 00000030: 8801 3192 9d7d 9233 924e 3220 3192 8b30 ..1..}.3.N2 1..0 00000040: 202e 3220 2e36 929d 3020 3088 1e33 3092 .2 .6..0 0..30. 00000050: 8088 0f31 3592 ad34 3592 8834 7b77 8800 ...15..45..4{w.. 00000060: 2d32 2e36 3888 1e35 2e33 3792 8072 8800 -2.68..5.37..r.. 00000070: 3088 1e31 2e37 3992 8039 3092 887d 9283 0..1.79..90..}.. 00000080: 924d 881e 3135 92ad 327b 7788 fb88 e288 .M..15..2{w..... 00000090: 0a36 3092 8039 3092 887d 9283 327b 7288 .60..90..}..2{r. 000000a0: fd88 e236 883c 9280 3930 9288 7d92 83 ...6.<..90..}.. ``` Non-tokenized version: ``` 10 10 scale 0 0 moveto 0 30 lineto 60 30 lineto 60 0 lineto closepath clip /r {.8 0 0 setrgbcolor} def /w {1 1 1 setrgbcolor} def gsave 2 1 scale 0 .2 .6 setrgbcolor 0 0 30 30 rectfill 15 15 translate 45 rotate 4 {w 0 -2.68 30 5.37 rectfill r 0 0 30 1.79 rectfill 90 rotate} repeat grestore 30 15 translate 2 { w -5 -30 10 60 rectfill 90 rotate } repeat 2 { r -3 -30 6 60 rectfill 90 rotate } repeat ``` Output: [![Union Jack flag](https://i.stack.imgur.com/kWnat.png)](https://i.stack.imgur.com/kWnat.png) [Answer] # HTML/CSS, 742 bytes A very unclever CSS implementation using three HTML elements. ``` <style>body{margin:0;zoom:10}a,b{position:absolute;width:30px;height:30px;background:#012169;clip-path:inset(0)}a:after,a:before,b:after,b:before{position:absolute;content:'';width:60px;height:2px;background:#c00;border:0 solid #fff;border-width:3px 0 1px 0;transform-origin:0 3px}a:after,b:after{top:-3px;transform:rotate(26.56deg)}a:before,b:before{top:27px;transform:rotate(-26.56deg)}b{left:30px;transform:rotate(180deg)}i{position:absolute;background:#fff;width:60px;height:10px;top:10px}i:before{position:absolute;background:#c00;width:6px;height:30px;top:-10px;left:25px;border:0 solid #fff;border-width:0 2px 0 2px;content:''}i:after{position:absolute;top:2px;width:60px;height:6px;background:#c00;content:''}</style><a></a><b></b><i> ``` See it [unminified on CodePen](https://codepen.io/jrunning/pen/JjpmEXz). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~248~~ ~~229~~ 224 bytes *-24 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` #define p putchar(c?c-1 i=-151,j,I,J;main(c){for(puts("P6 600 300 255 ");++i<150;)for(j=-301;++j<300;p?0:255:204))c=(c=fmin(I=abs(i),J=abs(j)))<30?0:c<50?:(c=i*j>0?J-2*I:2*I-J)>0&c<35?0:c*c<2704?:2,p?51:255:0),p?153:255:0);} ``` [Try it online!](https://tio.run/##Lc3BTsMwDAbgO08RDQnFXSI56TKkJF3O7YlXKGYdidZRrXBCvDrBmzj80m/rk036RFTr49txypejWMTy9Unv41VSIm0ecqeNM6qoXg1hHvNFEnxPH1fJbJWbl73YI4qWY50TGwjbbY7GYYAbKp1u0fCuRCZhSeiZeYs7AOokddPMF/tufF1lBjXcSwEA5mwpOkyeWW7KAdOgbdN7jh7ggE8UW3dDDUX7jLvkrVqSM/cPCNyNa/@H8FPrL03n8bRWfZ7/AA "C (gcc) – Try It Online") Outputs a [PPM](http://netpbm.sourceforge.net/doc/ppm.html) image. [Answer] # Python 2, 265 bytes ``` r="D\0\0" b="\0\x173" w="U"*3 N=20*(270*w+60*r+270*w) L=190*[b]+60*[w]+40*[r]+20*[w]+190*[b] j=''.join F=lambda p:j([j(L[150-p*100+i:150+p*150+i:p])+20*w+60*r+20*w+j(L[345-p*145-i:345+p*105-i:p])for i in range(0,200,2)]) print"P6 600 300 85 "+F(-1)+N+36000*r+N+F(1) ``` Output as binary PPM, usage: ``` python golf_unionjack.py > unionjack.ppm ``` `L` represents a vertical slice of the diagonal parts and `F` uses the (sort of) symmetry to save code and calculate the indices for upper and lower part. ]
[Question] [ In the classic days of Starbucks before these newfangled sticker-printers and wireless drivethrough headset palmtop scanner dealies, in the heady days of 2000-ish, Starbucks had a concise system for describing beverages with a strict syntax and accompanying encoded form. Vertically on the cup there are a series of labelled boxes which may contain certain values.: ``` Decaf [ ] -blank- X 1/2 1/3 2/3 Shots [ ] -blank- 0 1 2 3 ... 20 followed by S T G V Syrup [ ] -blank- V M C H Milk [ ] -blank- Wh % N B Custom [ ] -blank- ((-|x)?(F|WC|M|CR) )+ Drink [ ] E EM ECP A L C CM ``` But we will use a horizontal form for easier manipulation. These are the names of the 6 fields of the input which may be any convenient form. Examples here are simple CSV. The Custom field and Syrup fields each may be a concatenation of several values. You may use any convenient subdelimiter. Examples here use space. The Shots field is also a concatenation of a (possible) number and a designation of the cup size (which is implicit in the physical cup but naturally fits in this place in the encoding). The Decaf field values are translated into words like this ``` -blank- -nothing- X "decaf" 1/2 "half-caf" 1/3 "one-third-caf" 2/3 "two-thirds-caf" ``` Logically, the fractional values are only permissible when the number of shots is divisible by the denominator; but for this challenge it is not necessary to detect or diagnose this error. The Shots field should be broken into its numerical component (if present) and the size identifier. The number should be displayed in latin tuple form: single, double, triple, quadruple, quintuple, *beyond 5 just print the number and the suffix "-tuple" ie. `7-tuple`, `16-tuple`*. The size designations are: ``` S short T tall G grande V venti ``` Eg. ``` 2T double tall 3G triple grande ``` The Syrup field may contain one or more of several optional-number/lettercode tokens. The maximum number of a syrup is 20. Even that is too much. LOL. ``` V vanilla C caramel M mocha H hazelnut ``` Eg. ``` 2V 2C two vanilla two caramel H hazelnut M H 1V mocha hazelnut one vanilla ``` The Milk field may contain **one** of the following. ``` Wh whole-milk % two-percent N skim B breve ``` The Custom field may contain one or more of several modifiers with optional `x` or `-` sign. ``` x extra F foam - no WC whip M mocha drizzle CR caramel drizzle ``` The Drink field contains one drink id. ``` E espresso EM espresso macchiato ECP espresso con panna A americano L latte C cappuccino CM caramel macchiato ``` Any field may be blank except for the size designation and the drink id. Examples. ``` ,3G,V,Wh,,L => triple grande vanilla whole-milk latte X,2T,,N,,L => decaf double tall skim latte 1/2,V,,,,CM => half-caf venti caramel macchiato 2/3,3V,3V,B,WC,L => two-thirds-caf triple venti three vanilla breve whip latte ,G,,,xCR,CM => grande extra caramel drizzle caramel macchiato X,4T,2M 2C,B,xWC -F xM,C => decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino ``` There is no need to diagnose erroneous or illogical concoctions such as a "no foam ... cappuccino\*. ## Additional Complication For only the drinks with the word `espresso`, the number `single` should be replaced by `solo` and `double` should be replaced by `doppio`. And the size may be unspecified and omitted. Also, just for the bare `espresso` drink itself, if the only other specification is one of these two specially-replaced numbers-of-shots, then the word `espresso` itself should be omitted. ``` ,2,1V,B,,EM => doppio one vanilla breve espresso macchiato ,1,,,,E => solo ,2,,,,E => doppio ,3,,,,E => triple espresso ``` ## Additional observations on 'reading a cup' This part is not a requirement for this challenge but may be a useful refinement in applying this sort of verbalized system in other domains. I mentioned *syntax* at the very beginning, and by applying the schema to incoming streams of words, orders could be transmitted verbally by several order takers to the barista making beverages. The rough framework `SIZE .... DRINK` provides demarcation between several orders spoken at once. There is thus a tendency to make all the interior attributes as adjectival phrases so the order also has a valid English noun-phrase structure. So `whip` is often spoken `with whip` or `whipped` and `foam` is often spoken `foamy` or `with foam`. Thus, for some [old-time baristas](https://coffee.stackexchange.com/users/959/), they're not "correcting you" when they repeat the order in the proper format (*well,... sometimes*). They're simply organizing the information for the purpose of remembering all the details exactly. By schematizing the information, an entire beverage order becomes a single unit for the purpose of applying [the magic number 7 plus or minus 2](https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two). So a barista with this skill can *hold 5-9 orders in their head* provided other distractions do not consume too much head room. :) [Answer] # Javascript ES6, ~~902~~ 900 bytes ``` s=>(R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",R(",1,,,,E.solo.,2,,,,E.doppio",s).split`,`.map((e,i)=>(`1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):s.includes`E`&&(e=R("single.solo.double.doppio",e)),e)).join` `).replace(/\s+/g," ").trim()) ``` "Ungolfed": ``` s=>( R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r), // consecutive string replacement function R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip. // replace all symbols with appropriate values Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte. M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent", R(",1,,,,E.solo.,2,,,,E.doppio",s) // if special espresso cases, directly replace entire string .split`,`.map((e,i)=>( // split input at commas `1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))), // substitute duplicate symbols with unique symbols i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))): // if in shots section, expand all numbers i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0. // if in syrup section, expand all numbers 19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)): s.includes`E`&&(e=R("single.solo.double.doppio",e)), // replace single,double with solo,doppio if espresso is in the string e)).join` `).replace(/\s+/g," ").trim()) // join sections, cleanup whitespaces ``` Example runs: ``` f(",3G,V,Wh,,L") -> triple grande vanilla whole-milk latte f("X,2T,,N,,L") -> decaf double tall skim latte f("1/2,V,,,,CM") -> half-caf venti caramel macchiato f("2/3,3V,3V,B,WC,L") -> two-thirds-caf triple venti three vanilla breve whip latte f(",G,,,xCR,CM") -> grande extra caramel drizzle caramel macchiato f("X,4T,2M 2C,B,xWC -F xM,C") -> decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino f(",2,1V,B,,EM") -> doppio one vanilla breve espresso macchiato f(",1,,,,E") -> solo f(",2,,,,E") -> doppio f(",3,,,,E") -> triple espresso ``` [Answer] # Python, ~~824~~ ~~815~~ ~~807~~ 805 bytes ``` f=lambda s,a=0:a==0and" ".join(" ".join(f(" "+s.split(",")[i],(["X,deC,1/2,half-C,1/3,oneT-C,2/3,twoTs-C,C,caf,T,-third","".join(" %i"%i+f(",%i-tupL,"%i,["1","x","2","y"])for i in range(6,21))+"1,solo,2,doppio,"*('E'in s)+"1,singL,2,doubL, 3,tripL, 4,quadrupL, 5,quintupL,x,1,y,2,S,short,T,tall,G,grande,V,Vnti","V, vanilla,H, hazelnut,10,ten,11,eleVn,12,twelV,13,thirT,14,4T,15,fifT,16,6T,17,7T,18,8een,19,9T,20,twenty,1,one,2,two,3,three,4,four,5,fiV,6,six,7,seVn,8,eight,9,nine,T,teen","Wh,whole-milk,%,two-percent,N,skim,B,breV","x,extra ,-,no ,F,foam,WC,whip,M,MR,R, drizzL","CM,xM,E,espresso,M, macchiato,CP, con panna,A,americano,L,latte,C,cappuccino,x,C"][i]+",C, caramel,M, mocha,L,le ,V,ve").split(","))for i in range(6-(s in",1,,,,E,2,,,,E"))).split())or a and f(s.replace(a[0],a[1]),a[2:])or s ``` Slightly more readable: ``` def f(s,a=0): if a==0: a=["X,deC,1/2,half-C,1/3,oneT-C,2/3,twoTs-C,C,caf,T,-third"] a+=["".join(" %i"%i+f(",%i-tupL,"%i,["1","x","2","y"])for i in range(6,21))+"1,solo,2,doppio,"*('E'in s)+"1,singL,2,doubL, 3,tripL, 4,quadrupL, 5,quintupL,x,1,y,2,S,short,T,tall,G,grande,V,Vnti"] a+=["V, vanilla,H, hazelnut,10,ten,11,eleVn,12,twelV,13,thirT,14,4T,15,fifT,16,6T,17,7T,18,8een,19,9T,20,twenty,1,one,2,two,3,three,4,four,5,fiV,6,six,7,seVn,8,eight,9,nine,T,teen"] a+=["Wh,whole-milk,%,two-percent,N,skim,B,breV"] a+=["x,extra ,-,no ,F,foam,WC,whip,M,MR,R, drizzL"] a+=["CM,xM,E,espresso,M, macchiato,CP, con panna,A,americano,L,latte,C,cappuccino,x,C"] return" ".join(" ".join(f(" "+s.split(",")[i],(a[i]+",C, caramel,M, mocha,L,le ,V,ve").split(","))for i in range(6-(s in",1,,,,E,2,,,,E"))).split()) elif a: return f(s.replace(a[0],a[1]),a[2:]) else: return s ``` Demo at <https://repl.it/C8Hz/3> [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 640 bytes Performs a series of substitutions to transform the input into the expected output. ``` - no x extra Wh whole-milk % 2-percent N skim B breve X deJ 1/2 half-J 1/3 1Q-J 2/3 2Qs-J Q -third J caf ^, , ,1(?=\D.*E) ,soloZ ,2(?=\D.*E) ,doppioZ Z,,,,E$ Z ,(\d+) ,$1UleZ ,1U ,sing ,2U ,doub ,3U ,trip \d+(?!\d*U) $&Y U -tup ,4-. ,quadr ,5- ,quin , Z S short T tall G grande ZV venti M(?=[^,]*,\w*$) MR E espresso M$ macchiato CP con panna A americano L latte C$ cappuccino F foam WC whip R drizzle 4Y fourY 6Y sixY 7Y sevenY 9Y nineY 10Y ten 11Y eleven 12Y twelve 13Y thirK 15Y fifK 18Y eighK 20Y twenty 1Y one 2Y two 3Y three 5Y five 8Y eight 1(\w*)Y $1K K teen V vanilla C caramel M mocha H hazelnut - - Z,*| ?,+ ^ |Y ``` [Try it online!](https://tio.run/##TVPvT9swEP3@/gpPKlNbLqxOW9g@TGhkpYgSNH40JV2HZhJDLFInS1LoEP97d64mRNSoz@/du7N9l0o3xqrNTnv8e@PBFgJr6HVTKYFZhuesyLW3NPkjduB7pa4SbRuco340SxzhrtJPGjdI9SnkJx@Zyu89B/uQFwx8Bv5FzegCXpOZKsUpEnUvcEsQ7ifbh18X3/e6ow6oLvJizpz/jkuLsjTMzomfUQtOby/SXZZacprrOUhO2WrsA8ifOsPqDtRn1FSmBIe2Dz8s0u60g9bHWGDKG1mVoIG3B/qzUmkFGnoOGuu2NMcV6qyoGlyjUXmOMR4qZVONeQTxxMc3CHmDP2/pV5cWz91WB@ElRtB1Wem6LhC2IJYqSTKjmgLBD4iksKJU1ip8g1rqyiTKFjhDrppGI2jxlZTlKkkMs8e4L9QSs4Avn/d/CZFW5uUl1xjELK2qGPsxarOOccD/fP82xpcY1lgdQ/ZiNNpCyhg6dyKkz9SzzrlRss@QuzCBHHIyc8/gMweah2wCv7eNs81fsLmwGltjga2p0hpbD6f5b2kg23z@ToyWnGDCdblahCdlTZ4rBHyqik@bI8SySDKFE56PF53bVQPhweOedl/FIe2Cx0G8xthsbkjuR3QQ0SyjYxrhhobRlnpbD3g9fLd2ohy8EdQfUyD8SITixHE0CjnIvyY6JzpzM0qRm6QgdLNJfTbze0SzgFUas7IOLp3Kla5J9kLh9wLW17NAeMdiHQon86SRdDaXnuR2NLnPzDrEzBvocRLOEXD5rZXj@eMg/4oiEYiQdoizejMHOcM/ "Retina 0.8.2 – Try It Online") Most of it is pretty straightforward replacements. A few interesting parts are: ``` ,1(?=\D.*E) ,soloZ ,2(?=\D.*E) ,doppioZ ``` Handles the special cases for drinks containing the word "espresso". It transforms the 1 and 2 into "solo" and "doppio" before we get to the stage where we transform those numbers into latin tuple form. ``` Z,,,,E$ Z ``` Removes the word "espresso" if "solo" or "doppio" is the only other modifier. ``` M(?=[^,]*,\w*$) MR ``` Appends an `R` to any `M` with only one comma between it and the end of the string. This allows us to transform all `R`s into "drizzle" later on. ``` 1(\w*)Y $1K K teen ``` Allows us to transform 14,16,17, and 19 into their word forms all at once, since we replace 4,6,7, and 9 beforehand. [Answer] # [Ruby](https://www.ruby-lang.org/) `-plaF,`, ~~975~~ 870 bytes I got a random upvote on my old, almost-four-year-old answer to this question, and because of my comments on how horribly it went (you can check the post history if you want to see what I wrote before) I was inspired to make it better (aka: rewrite most of it from the ground up) and managed to golf over a hundred bytes off it. Still longer than the Python answer, but I'm much happier with how things turned out now. About 20 bytes were saved by switching from trying to run regex patterns to affect specific parts of the comma structure to using the `-aF,` flag to autosplit a line of input on commas and save it to `$F`, allowing me to modify some elements before stitching it back together and finally modifying the output variable with the last few `sub`/`gsub` commands. Honestly, the number of regex replacements made here means most of this could be a Retina program, but I don't know Retina well enough for that. ``` g=->n,c{n.grep(/^ ?#{c}/i)[0]} n=%w"0 one two three four five six seven eight nine ten eleven twelve thir four fif";n+=n[6,4]<<'twenty' $F[1].sub!(/(\d*)(\w)?/){i=eval$1;"#{i&&(%w"0 sing doub trip quadrup quintup"[i]||$1+"-tup")+"le"} #{g[%w"short tall grande venti",$2]if$2}"} $F[2].gsub!(/(\d*)(\w)/){i=eval$1;"#{i&&n[i]}#{'teen'if(13..19)===i} #{g[%w"vanilla caramel mocha hazelnut",$2]}"} $F[3].sub!(/.+/){%w"skim whole-milk breve two-percent"[$&.sum%26%4]} $F[4].gsub!(/(x|-)?(\w+)/){"#{%w"extra no"[$1.ord%2]if$1} #{g[%w"caramelD mochaD whip foam",$2[0]].sub ?D,' drizzle'}"} $_=$F*' ' sub(/^\S+/){%w"de - half- one-third- two-thirds-"[$&.sum%8]+"caf"} sub'CP',' con pana' sub'CM','caramel'+m=' macchiato' e='espresso' gsub(/[A-Z]/){g[%w"americano latte cappuccino"+[m,e],$&]} gsub(/ +/,' ') $_.strip! sub(/[sd]...le/){g[%w"doppio solo",$&[0]]}if$_[e] sub'o '+e,?o ``` [Try it online!](https://tio.run/##ZZJhb9MwEIa/91ccWVe3xElJOiEQhAo6Bh8oQoAYIgvIS9zGmmMHx2nLuv51yjndhgRRJNt3vnufO59pL3/t98skeKFovlXh0vB6OP4O06NtvhuLUfoo2/VUcrz2HoFWHOxagy0N57DQrYGFWHFoxAYavuIKuFiWFpRwF91Rdla75hKv2VKYu6iF90z5iUof05Ps@XOCN5T9RXr9szTKwqa9fDAcDy@Kh6PhxXo0HY@2IuErJvvRM@9oKwaDYcfTCLWEQreXYI2o4WfLCtO6VSjb1l4qspubfuR7gTuNfE9ybwdH22WK0U2pjQXLpISlYarggKRWeLQfZ2LRj3feztHEWbj8B@d/GoVKu6MtsZwrIhbDaBKG0dNRkiTiXm/FlJCSQc4Mq7iESuclg5Jdc6la28neSk7uGhD6KOVQr0QF61JLHlRCXsGl4avuIYKamxypvbQ/wJjqOH58fJJ1SU7@cm9ugtEUwX1HjsCYkW@sYaA0BkahNsVxV3N0D3sLeXqgPEVxbO9Cs8px4kR0hDA9pQQKI66vJScd/I@kf/aQAOmhG4fo4tNtBdjdAGuVi8DNUOAGoQi6CrptE9xX8CTzUX2ByTAFmX0gKJFrBTVTjBxsc7TdAhK/SghULM9LwawmPZ4Q3tSGNw0elh1F@jL4liFGVxgGGZEzpUEyazm@Rl23eS6wFX5aUZ7R/gAbeIgEf4zqZIR1hY2bsAeHutKmyMIwlPwua6HrWmhotNTYoIFr0A77@SPlWYesgficTvV@Tydv6Bd6XlL6rveVxp8pfe@20ThGM36zeS8eT@jki/tf0fMZOukbdGxmH53zKz35TN9CPIdoMsMLm/MZBGewmYPz92hMIxdHX897NHIJXzvbYZ10629dW6FVsw9qyc7oHw "Ruby – Try It Online") ]
[Question] [ The Gray Code is a sequence of binary numbers of bitwidth `n` where successive numbers differ only in one bit (see example output). [Reference](http://en.wikipedia.org/wiki/Gray_code) Example input: ``` 3 ``` Example output: ``` 000 001 011 010 110 111 101 100 ``` Notes: * This question seems to have a [dupe](https://codegolf.stackexchange.com/questions/4094/write-a-code-the-find-n-th-number-of-gray-code-list) but it's not, for that question is not a code-golf, and it demands different output. It will help to check out it's answers, though. * You may assume a variable `n` which contains the input. [Answer] ## JavaScript (77) ``` for(i=0;i<1<<n;)alert((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n)) ``` More browser-friendly version (console.log and prompt()): ``` n=prompt();for(i=0;i<1<<n;)console.log((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n)) ``` [Answer] # Python 2 (47) ``` for i in range(2**n):print bin(2**n+i/2^i)[3:] ``` The expression `i/2^i` for the `i`'th gray code number is from the [this answer](https://codegolf.stackexchange.com/a/7344/20260). To add leading zeroes that pad to length `n`, I add `2**n` before converting to a binary string, creating a string of length `n+1`. Then, I truncate the leading `1` and number type prefix `0b` with `[3:]`. [Answer] # [K (ngn/k)](https://github.com/ngn/k), 10 bytes ``` +~0=':!n#2 ``` [Try it online!](https://tio.run/##y9bNS8/7n2dl/F@7zsBW3UoxT9no/38A "K (ngn/k) – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 11 bytes ``` 2≠/0,↑,⍳n⍴2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0xTy/hs96lygb6DzqG2izqPezXmPercY/QdK/U9TMAYA "APL (Dyalog Classic) – Try It Online") `n⍴2` is `2 2...2` - a vector of `n` twos `⍳` is the indices of an `n`-dimensional array with shape `2 2...2` - that is, a 2×2×...×2 array of nested vectors. As we use 0-indexing (`⎕IO←0`), those are all binary vectors of length `n`. `,` flatten the 2×2×...×2 shape, so we get a *vector* of 2n nested binary vectors `↑` "mix" - convert the vector of vectors to a solid 2n×n matrix. It looks like this: ``` 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 ``` `0,` prepends zeroes to the left of the matrix `2≠/` computes the pairwise (`2`) xor (`≠`) along the last dimension (`/` as opposed to `⌿`); in other words, every element gets xor-ed with its right neighbour, and the last column disappears ``` 0 0 0 0 0 1 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 1 0 0 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes ``` 2pU Ç^z)¤ùTU ``` Shaved off two bytes thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). [Try it online!](https://tio.run/##y0osKPn/36ggVOFwe1yV5qElh3eGhP7/bwwA) [Answer] ## Python - 54 Based off of an algorithm from the reference given in the challenge: ``` for i in range(2**n):print'{1:0{0}b}'.format(n,i>>1^i) ``` Ungolfed: ``` # For each of the possible 2**n numbers... for num in range(2**n): gray = num>>1 ^ num # Print in binary and pad with n zeros. print '{1:0{0}b}'.format(grey) ``` [Answer] ## PowerShell(168) Amateur PowerShell'r back with another attempt at golF! Hope you don't mind! At the very least these questions are fun, and a learning experience to boot. Assuming n has been inputted, we have: ``` $x=@('0','1');for($a=1;$a-lt$n;$a++){$x+=$x[($x.length-1)..0];$i=[Math]::Floor(($x.length-1)/2);0..$i|%{$x[$_]='0'+$x[$_]};($i+1)..($x.length-1)|%{$x[$_]='1'+$x[$_]}}$x ``` Because the PowerShell I'm working with is only 2.0, I can't use any bit shifting cmdlets which might make for shorter code. So I took advantage of a different method described in the question [source](http://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code), flipping the array and adding it to itself, appending a 0 to the front of the top half, and a 1 to the bottom half. [Answer] ## F# ~~(86)~~ ~~(84)~~ (80) ``` for i in 0..(1<<<n)-1 do printfn"%s"(Convert.ToString(i^^^i/2,2).PadLeft(n,'0')) ``` This could probably be improved further. Also note, if run in FSI, you'd need to `open System;;` first. If you'd like to avoid importing that, (and if you don't care about the order in which the values are printed) you can use this 82-character version: ``` for i in 0..(1<<<n)-1 do(for j in 0..n-1 do printf"%i"((i^^^i/2>>>j)%2));printfn"" ``` [Answer] ### Ruby — ~~42~~ 39 Same algorithm, different language: ``` (2**n).times{|b|puts"%0#{n}b"%(b>>1^b)} ``` Switching from `#map` to `#times` as @voidpigeon suggests saves 3 characters. [Answer] # J, 24 bytes ``` [:#:@(22 b.<.@-:)[:i.2^] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62UrRw0jIwUkvRs9Bx0rTSjrTL1jOJi/2typSZn5CukKRhDGOq6urrqMDETBS4Q@A8A "J – Try It Online") Straightforward implementation of the "XOR with it's own floored half" algorithm. Note that `22 b.` is XOR. [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` W:qt2/kZ~B ``` [Try it online!](https://tio.run/##y00syfn/P9yqsMRIPzuqzun/f2MA "MATL – Try It Online") The good old "XOR n with n>>2" method. `W` - compute 2^(input) (gets input implicitly) `:q` - create range of numbers from 0 to 2^n - 1 `t` - duplicate that range `2/k` - MATL doesn't have bitshift, so divide (each number) by 2 and floor `Z~` - elementwise XOR that result with the original 0 to 2^n - 1 array `B` - convert each number in the result to binary (Implicitly display output.) [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 25 bytes ``` {(x-1){,/0 1,''|:\x}/0 1} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlqjQtdQs1pH30DBUEddvcYqpqIWxK79n6Zg/B8A "K (ngn/k) – Try It Online") --- * `|:\x`is "reverse scan x". applies reverse to x until the output equals the input, and shows each iteration. returns (0 1; 1 0) on first pass. * `0 1,''` is "0 1 join each each". joins a 0 to each value of 1st elem, and 1 to each value of 2nd elem, giving ((0 0; 0 1);(1 1; 1 0)) on first pass * `,/` is "join over", and flattens to list. * `(x-1){...}/0 1`is "apply {func} over `0 1` x-1 times". takes the output of the last iteration as input [Answer] # APL (22) ``` {(0,⍵)⍪1,⊖⍵}⍣(n-1)⍪0 1 ``` This outputs a n-by-2^n matrix containing the bits as its rows: ``` n←3 {(0,⍵)⍪1,⊖⍵}⍣(n-1)⍪0 1 0 0 0 0 0 1 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 1 0 0 ``` Explanation: * `{`...`}⍣(n-1)⍪0 1`: run the function `n-1` times with initial input the matrix `(0 1)T` (which is the 1-bit gray code) + `(0,⍵)`: each row of `⍵` with a `0` prefixed, + `⍪`: on top of, + `1,⊖⍵`: each row of `⍵` with an `1` prefixed, in reversed order [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), ~~105~~ 100 bytes ``` def g(n):if n<2then. else map([0]+.)+(reverse|map([1]+.))|g(n-1)end;[[0],[1]]|g(N)[]|map("\(.)")|add ``` Assumes N provides input. e.g. ``` def N: 3 ; ``` Expanded ``` def g(n): # recursively compute gray code if n < 2 then . else map([0]+.) + (reverse|map([1]+.)) | g(n-1) end; [[0],[1]] # initial state | g(N)[] # for each element in array of gray codes | map("\(.)")|add # covert to a string ``` [Try it online!](https://tio.run/##HY5BDsIgFET3noLUDT8VYnXXeoZeALtowq9i6ocWqhvOLlJ2My9vknkt6cgMuS0cNE6sb69d2sODE7RmYnS7hCeSZDh7ZO/RcXUeagk1X/GDq8dYWLMziHklGkDSncraKeMhsx7UULTqziVUEEetU/pZF4wln4SgbZ5FOZHLOn6F3UIp/g8 "jq – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` ³Ç¤ÅÃf_Ê¥U ``` [Try it online!](https://tio.run/##y0osKPn//9Dmw@2HlhxuPdycFn@469DS0P//jbm4dIMA "Japt – Try It Online") [Answer] ## T-SQL 134 This challenge is asking to return the Cartesian power of {(0),(1)}. This snippet builds the code which would execute the Cartesian product of {(0),(1)} n times. ``` DECLARE @ int=4,@s varchar(max)='SELECT*FROM's:set @s+='(VALUES(0),(1))t'+ltrim(@)+'(b)'if @>1set @s+=','set @-=1if @>0goto s exec(@s) ``` ]
[Question] [ **Task:** Your task is to create a program that, when given a number of strands and number of iterations of a braid, will tell where each strand goes. Rules are as follows: * The number of strands will always be odd, and between 3 and 6000 (inclusive) * When you start, the strands will be divided into 2 (almost) equal bunches, the `left` and the `right`. The `left` will have one more strand when you start. For an input of 7: ``` / / / / \ \ \ 1 2 3 4 5 6 7 ``` * Every iteration, the outermost strand of the side with more strands will be put in the center facing the opposite direction. The center is defined as between opposite facing strands: `////middle\\\`. 1 iteration of input 7 (strand 1 was moved to the center): ``` / / / \ \ \ \ 2 3 4 1 5 6 7 ``` **Example:** Input: ``` 3 4 ``` Computations: ``` 1 2 3 \ 2 1 3 / 2 3 1 \ 3 2 1 / 3 1 2 ``` Output: ``` 3 1 2 ``` **Rules:** * You do not need to display the slashes for strand direction, only the numbers. * You only need to display the numbers after the last iteration. * Your output will be space-deliminated ids of the strands * Input will be in the form: `strands [space] iterations` * The number of strands will always be odd, and 3<=x<=6000 * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] ### GolfScript, 33 characters ``` ~\),(@{:^1$[=]:y-.,2//y*^~}*;' '* ``` The input must be provided on stdin. Examples (you may test [online](http://golfscript.apphb.com/?c=OyIxMSAyIgoKflwpLChAezpeMSRbPV06eS0uLDIvL3kqXn59KjsnICcqCg%3D%3D&run=true)): ``` > 7 1 2 3 4 1 5 6 7 > 3 4 3 1 2 > 11 2 2 3 4 5 6 11 1 7 8 9 10 ``` [Answer] ### Python: 179 240, 152 characters **First, the 179** For `N` strands and `i` iterations, this answer uses `O(1)` space and `O(N)` time. I simply compute the end position of each strand, never iterating over the intermediate positions! **big edit:** golfed this answer by changing conditionals to boolean algebra. I also wrote a [lengthy explanation](https://gist.github.com/wrongu/cd668c49b481bd2ade23) of how it works. TL;DR: formulaic patterns, modulo division. ``` from sys import * N,i=map(int,stdin.readline().split()) h,t=N/2,3*N f=lambda p:(p>N)*(t/2-(p&-2))+p/2+1 for s in xrange(N):print f((2*s+1+(s>h)*(t-4*s-2)+i*(N+1-N*(s!=h)))%(2*N)), ``` **Now the 152** This is more reasonably golfed python. (edit: thanks to Alex Thornton for editing from 165 to 152) ``` from sys import*;l=map;r=range;n,m=l(int,stdin.readline().split());b=r(1,n+1) for k in r(m):v=b.pop((0,n-1)[k%2]);b.insert(n/2,v) print' '.join(l(str,b) ``` [Answer] # Python 2 (109) / Python 3 (121) **Python 2** ``` s,n=map(int,raw_input().split()) b=range(s) for i in range(n):b[s/2:s/2]=[b.pop(0-i%2)] for x in b:print x+1, ``` **Python 3** ``` s,n=map(int,input().split()) b=list(range(s)) for i in range(n):b[s//2:s//2]=[b.pop(0-i%2)] for x in b:print(x+1,end=' ') ``` The code must have been bribed by Python 2 to showcase its golfing advantages over Python 3: ranges being lists, division rounding down to an int, print not starting a newline. The weird `0-i%2` is because `-i%2` evaluates as `(-i)%2`. There's probably a more efficient approach than iterating, namely computing each final result directly. The braiding operation has period 2\*s, so it can't be that complicated. [Answer] ## Ruby, 105 Just a lot of set manipulation. Push, pop, reverse and shift! I tried not converting inputs to integers, but it added about 20 characters. ``` n,i=$*.map(&:to_i) f=l=(1..n).to_a t=r=l.pop(n/2).reverse i.times{f,t=t<<f.shift,f} $><<(l+r.reverse)*' ' ``` `l` and `r` (`left` and `right`) are the "thread" queues. `right` is reversed so we start pulling from the outside. `t` and `f` (`to` and `from`) start off as `right` and `left`, respectively, but as we go we keep swapping them so we can always shift the last "thread" from `from` and push it to `to` (`f,t=t<<f.shift,f`). This saves a LOT of space. Then we just re-reverse `right` at the end. ### Changelog: 2.2 **105** oh yeah, map can take a proc 2.1 **108** And actually, just flip things as part of manipulation. 2.0 **116** don't use that temporary array. Instead use two pointer variables we can manipulate and keep re-pointing. Then only display the end 1.0 **123** initial idea [Answer] ## Java, 270 chars golfed: ``` import java.util.*;class B{public static void main(String[] a){int n=Integer.valueOf(a[0]),t=Integer.valueOf(a[1]),i=0;List<Integer> r=new ArrayList<Integer>();for(;i<n;i++){r.add(i+1);}for(i=0;i<t;i++){int k=i%2==0?0:n-1;r.add(n/2,r.remove(k));}System.out.println(r);}} ``` un-golfed: ``` import java.util.*; public class Braid { public static void main(String[] args) { int num = Integer.valueOf(args[0]); int iterations = Integer.valueOf(args[1]); //populate array List<Integer> arr = new ArrayList<Integer>(); for (int i=0; i < num; i++) { arr.add(i+1); } for (int i=0; i < iterations; i++) { int index = i%2==0?0:num-1; arr.add(num/2, arr.remove(index)); } System.out.println(arr); } } ``` [Run online](http://ideone.com/a7Ohjh) ]
[Question] [ **This question already has answers here**: [Write a polyglot that prints the language's name](/questions/7261/write-a-polyglot-that-prints-the-languages-name) (17 answers) Closed 10 years ago. Make a program which prints `just another #{LANG} hacker` where `#{LANG}` is the name of the language with which the program is being run. For example, if I run your program with Bash, I'd expect `just another Bash hacker` as the output, but when running the same program through C++, I'd expect the output to be `just another C++ hacker`. Your program must run in and produce correct output in at least **two** different languages. --- **This is in no way a duplicate of the other suggested question, [Write a polyglot that prints the language's name](https://codegolf.stackexchange.com/questions/7261/write-a-polyglot-that-prints-the-languages-name);** that question asks for a rather short (and in my opinion) uninteresting output, increasing the easiness of writing and number of languages in an answer, and then it assesses them (these polyglots) based on the source's length! A correct response to this question, however, would produce longer outputs, and thus would have actually been fairly challenging and fun to write and it would be more difficult to add languages to your polyglot. I then assess the polyglots in a natural way; by the number of languages they support! I think that this will lead to very different answers being submitted on either question, but also different uses for these answers; the programs which will be submitted here are the type of programs which would be flaunted around the internet for their ingenuity and creativity, "look! Here's a guy who can pull off a swaggy polyglot in 4 different languages! They're cool!" When I asked [this](https://codegolf.stackexchange.com/questions/50706/the-polyglot-challenge) question, I thought I'd put a twist on the popular and well known [Just Another Perl Hacker](https://en.wikipedia.org/wiki/Just_another_Perl_hacker) competition, but add some creativity and an extra "Wow!" factor; JAPH programs are often sported as signatures in forums etc., and I believe entries here will inspire similar use, unlike entries for the other question. Also, because this isn't a form of code-golf like the other question, but I'm actually assessing answers on the number of languages they support, I believe we can expect some rather incredible entries, making use of language features and loopholes we never knew existed! --- **Rules:** * *Two different versions of the same language only count separately if:* + You print out the version as well as the language name, for each version. + You detect which version is running thraough a less trivial method than running a `ver()` function or similar built-in of your language. + The two have different major version numbers. For example, if you say your program runs in both Python 3.4.1 and 2.7.8, here are the necessary outputs: Python 3.4.1 ``` just another Python 3.4.1 hacker ``` Python 2.7.8 ``` just another Python 2.7.8 hacker ``` If your program doesn't produce the above outputs for each version, then you cannot list the two separate versions as different languages under which your code runs. * You may *not* have any errors on the *maximum* level of warning in any of the languages. * Program must terminate. --- # Winner: * Whoever's (valid) answer supports the most languages. In the case of a tie, the shorter answer (by program byte count) wins. [Answer] # C, C++, Perl, Bash – 230 ``` #include <stdio.h> #define c const char*\ s="just another %s hacker\n" //bin/test;printf "$s" Bash;exit int main(){c;printf(s,sizeof'a'-1?"C":"C++");} /*==;seek DATA,0,0;@a=readline DATA;eval'$'.$a[2];printf $s,"Perl"; __DATA__*/ ``` This was fun! :-) 230 chars including a newline at end of file. To run, save as both `poly.c` *and* `poly.cpp` and do: ``` $ gcc -Wall -Wextra -pedantic poly.c && ./a.out just another C hacker $ g++ -Wall -Wextra -pedantic poly.cpp && ./a.out just another C++ hacker $ perl poly.c just another Perl hacker $ bash poly.c just another Bash hacker ``` [Answer] # ANSI C/C++ ``` #ifdef __cplusplus # include <iostream> # define LANG "C++" # define PRINT(text) { std::cout << text; } #else # include <stdio.h> # define LANG "C" # define PRINT(text) { printf("%s", text); } #endif int main(void) { PRINT("just another "); PRINT(LANG); PRINT(" hacker\n"); return 0; } ``` Compiling and executing: ``` $ gcc -ansi -Wall -Wextra -pedantic -o prog-c prog.c $ ./prog-c just another C hacker $ g++ -ansi -Wall -Wextra -pedantic -o prog-cpp prog.c $ ./prog-cpp just another C++ hacker ``` [Answer] # BASH + BrainF\*ck + PHP, 269 characters ``` #><?="Just another PHP hacker\n";die();?>< echo Just another BASH hacker #++++++++++[>+++++++>++++++++++++>++++++++++>+++++++++++>+++>+<<<<<<-]>++++.>---.--.+.>>>++.<<---.>.+.<<.>+++++++.---.>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++.-------.++.>-------.<++.>+++++++.>>. ``` Running the program: ``` $ php langs.sh #>Just another PHP hacker $ ./2langs.sh Just another BASH hacker $ bf 2langs.sh Just another BF hacker ``` A bit of stretching the rules with that PHP one, but it seems to work. I can fix it if it doesn't count. [Answer] # JavaScript, HTML, BF ``` <!-- // > to fix previous comment delim /* ++++++++++[>+++++++>++++++++++++ >++++++++++>+++++++++++>+++>+<<<<<<-]>++++ .>---.--.+.>>>++.<<---.>.+.<<.>+++++++.--- .>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++. -------.++.>-------.<++.>+++++++.>>. */ alert('Just another JavaScript hacker') // --> Just another HTML hacker ``` Relies on the fact that most JS implementations ignore `<!--`. BF code shamelessly stolen [from @Tyzoid](https://codegolf.stackexchange.com/a/16863/3808), all credit to him :-) Make sure your BF interpreter supports pointer wrapping. [Answer] # Lua 5.3/5.2/5.1/5.0/4.0/3.2 You said as long as I don't use `_VERSION` it is fine ``` print("Just another Lua"..(string and(loadstring"return 0//0"and"5.3"or(_ENV and"5.2"or(string.gmatch and"5.1"or"5.0")))or tremove(next({[{"4.0","3.2"}]=1},nil))).." hacker") ``` ]
[Question] [ Given an ascii musical score, you must be able to output the note and its corresponding length. The score will contain between 5 and 15 notes inclusive, and is transcribed on a stave. A stave is made up of five horizontal lines comprising of - (minus) characters separated by lines of spaces. The bottom line in the stave is equivalent to the note 'E'. The line of spaces immediately above the bottom line indicates an 'F', and is of a higher pitch that the 'E' below it. This continues as below. Note that notes only go up to 'G' before starting again at 'A'. See below: ``` F ---------- E D ---------- C B ---------- A G ---------- F E ---------- ``` Note that the letters aren't included in the input. The notes are superimposed on top of the stave using a o (lowercase ooh) character to indicate the 'note head'. This note head indicates the frequency of the note, and therefore the alphabetic representation of it as above. For example, a note placed on the score as below indicates an 'A' : ``` ---- ---- ---- o ---- ---- ``` A note, like the 'A' above, is called a 'whole note' and would be played for one whole beat. Other durations can be indicated by including a 'stem' rising from the note, and between zero and three 'flags'. A stem is made up of three | (pipe, or vertical bar) characters stacked immediately above the note head . A stem with no flags is considered a 'quarter-note', and plays for quarter of a beat. Flags are \ (backslash) characters, and hand on the right hand side of the stem. Each stem halves the time the note is played for. The length of each note will be one of the following: a whole note, a quarter note, an eighth note, a sixteenth note or a thirty-second note. This how each type of note would look for A : ``` -------------------- ----|---|\--|\--|\-- | | |\ |\ ----|---|---|---|\-- o o o o o -------------------- -------------------- ``` Putting more than one note together gives you a score. Each note can be considered to be four characters wide, with a note being in the first column of each four-character block. For example : ``` |\ ----|\--|\---------- |\ | |\ ----o---|---o---|\-- | o | |---------------o--- | o------------------- -------------------- ``` The example above contains the following notes, in order: a quarter note 'G', a thirty-second note 'D', an eighth note 'C', a whole note 'D' and a sixteenth note 'B'. Each note in your output should be in the format letter/length, where letter is A-G and length is the fraction of the note's length when compared to a whole note. As an exception, the length and / character should not be printed if the note is a whole note. Each note in your output should be separated by a single space. Therefore, for the score above, your code should output the following: ``` G/4 D/32 C/8 D B/16 ``` * The notes will be in the following range: E F G A B C D E F. Note that only the letter needs to be printed, the octave is ignored. * Note that the number of lines of input varies from 9 to 12, since notes with quarter time or less on line D or higher will require more lines to show completely. * There is no half-note in this case. Shortest code wins (whitespace doesn't count). *Edit:* Fixed error in spacing in one input. Some sample inputs: ``` |\ ----|\--|------------------- |\ | | |---|---o---------------o--- | o |\ o---------------|\--|\------ |\ |\ |\ ------------|\--|\--o------- |\ o ------------o--------------- ``` Output: B/8 C/8 D/8 E/32 F/32 G/32 D --- ``` ----------------o------------------- o ------------o----------------------- o --------o--------------------------- o ----o------------------------------- o o----------------------------------- ``` Output: E G B D F F A C E --- ``` |\ |\ |\ ------------o-------|----------- | o | |\ |---|\--------------|---|\------ | | o |\ o---|---|\--------------o---|\-- o |\ |\ --------|\------------------|--- o o -------------------------------- ``` Output: B/4 A/8 F/32 F/32 E C/4 B/32 F/16 [Answer] # Javascript,284,279,278,225,221,220 Characters (including necessary whitespace) One-liner ([test fiddle](http://jsfiddle.net/briguy37/dQ54U/7/)): ``` function a(c){b='',d=c.split('\n');for(e=0;d[0][e++];){f=0;for(i=0;g=d[i++];){h=g[e-1];if(h=='o')b+=(b?' ':'')+String.fromCharCode((d.length+4-i)%7+65);if(h=='|')f=f||4;if(g[e]&&g[e]=='\\')f*=2;}if(f)b+='/'+f;}return b;} ``` Readable ([test fiddle](http://jsfiddle.net/briguy37/dQ54U/)): ``` function getNotes(input){ out='',lines=input.split('\n'); for(col=0;lines[0][col++];){ time=0; for(i=0;line=lines[i++];){ char=line[col-1]; if(char=='o')out+=(out?' ':'')+String.fromCharCode((lines.length+4-i)%7+65); if(char=='|')time=time||4; if(line[col]&&line[col]=='\\')time*=2; } if(time)out+='/'+time; } return out; } ``` [Answer] ## Perl, 103 characters (108 if you count necessary whitespace characters) ``` $i=0,s/\|\\/h /g,map$b[$i++].=$_,/./g for<>;/o/&&print chr 65+(4+length$')%7,/[h|]/&&"/".4*2**y/h//," "for@b ``` With whitespace for presentation: ``` $i=0, s/\|\\/h /g, map $b[$i++]. = $_, /./g for <>; /o/ && print chr 65 + (4 + length $') % 7, /[h|]/ && "/" . 4*2**y/h//, " " for @b ``` Note that I assume that all lines have the same length (as per the revised version of the question). Rearranged version with explanations: ``` #!/usr/bin/env perl # First transpose the list of lines into a list of columns. my @b = (); # @b[$i] will contain the characters in column $i while (<>) { # for each input line, do my $i = 0; # start in column 0 s/\|\\/h /g; # replace '\|' by 'h ', to keep track of part notes in the first column foreach (/./g) { # for each character, do $b[$i++] .= $_; # append the character to the transposed matrix } } # Now process each column. foreach (@b) { # for each column, do if (/o/) { # if it contains a note, then print chr(65 + (4 + length $') % 7); # print the note pitch if (/[h|]/) { # if this is a part note (had |\ or just |) print "/", 4*2**y/h//; # print /n where n = 2^(subdivision) } print " "; } } ``` --- *(old, longer solution, kept because it may be interesting even if it's a little longer)* ## Perl, 147 126 characters (149 131 if you count necessary whitespace) ``` $c=0,map{/o/?$h[$c]=E:/\\/?$d[$c-1]*=2:/\|/?$d[$c]||=4:++$h[$c];++$c}/./g for<>;print grep{s~$~/$d[$i++] ~;s~/ ~ ~;y/E-M/EFGA-F/}@h ``` With whitespace for presentation: ``` $c = 0, map { /o/ ? $h[$c]=E : /\\/ ? $d[$c-1]*=2 : /\|/ ? $d[$c]||=4 : ++$h[$c]; ++$c } /./g for <>; print grep {s~$~/$d[$i++] ~; s~/ ~ ~; y/E-M/EFGA-F/} @h ``` Rearranged a little so as not to abuse the language so much: ``` #!/usr/bin/perl my @h; # $h[$c] will contain the note in column $c, if any my @d; # $d[$c] will contain the note length (e.g. 4), if any while (<>) { # for each input line, do my $c = 0; # column number foreach (split //) { # for each character, do if (/o/) { $h[$c] = "E"; } # o => it's a note; if this is the last line, it's E elsif (/\\/) { $d[$c-1] *= 2; } # \ => halve the duration of the note in the previous column elsif (/\|/) { $d[$c] ||= 4; } # | => if this is the first | in the column, we have a quarter note else { ++$h[$c]; } # anything else => bump the note by 1 ++$c; } } for (my $i = 0; $i < @h; $i++) { # for each column, do $_ = $h[$i]; # look up the potential note (or garbage if there is no note in this column) s~$~/$d[$i++] ~; # append the duration and a space (or "/ " if there is no duration) s~/ ~ ~; # remove the spurious "/" if there is no duration if (y/E-M/EFGA-F/) { # if it's a note (i.e. if it contains a letter E-M), then # fix the letter wraparound and then print $_; # print the note } } ``` Note that I assume that all lines have the same length. If you want to allow shorter lines, an obvious fix is to add `$_.=1x$c,` at the beginning of the program, at a cost of 9 characters. I thought of another approach to avoid long words like `split` and `map` and let spaces do more of the work, but the boilerplate and punctuation took their revenge, and I can only get it down to a whooping 130 (144 with necessary whitespace). ``` sub p{$-[0]} %a=qw(o $h[p]=E \ $d[&p-1]*=2 | $d[p]||=4 - ++$h[p]); y/ /-/,s~.~$a{$&}~gee for<>; print grep{s~$~/$d[$i++] ~;s~/ ~ ~;y/E-M/EFGA-F/}@h ``` The patch to cope with unfinished lines is a little weirder this time (what, you thought it couldn't get weirder?). 139 characters, 155 with necessary whitespace. ``` sub p{$-[0]} %a=qw(o $h[p]=E \ $d[&p-1]*=2 | $d[p]||=4 - ++$h[p]); $_.=" "x p,y/ /-/,s~.~$a{$&}~gee for<>; print grep{s~$~/$d[$i++] ~;s~/ ~ ~;y/E-M/EFGA-F/}@h ``` [Answer] ## Scala(2.9), 352 313 291 294 290 277 274 273 characters If a function is all that's needed: ``` def m(s:String){var(x,y,z,l)=(0,1,s.count(_=='\n'),Array.fill(99)(0)) var n=l.clone for(c<-s){if(c=='\n'){x=0;y+=1} if(c=='\\')l(x-1)+=1 if(c=='|')l(x)+=1 if(c=='o')n(x)="EFGABCDEF"(z-y) x+=1} (n,l).zipped.map((x,y)=>if(x>0)print(x.toChar+(if(y>0)"/"+(4<<y-3)else"")+" "))} ``` If a full program is required: ``` object M extends App{def m(s:String){var(x,y,z,l)=(0,1,s.count(_=='\n'),Array.fill(99)(0)) var n=l.clone for(c<-s){if(c=='\n'){x=0;y+=1} if(c=='\\')l(x-1)+=1 if(c=='|')l(x)+=1 if(c=='o')n(x)="EFGABCDEF"(z-y) x+=1} (n,l).zipped.map((x,y)=>if(x>0)print(x.toChar+(if(y>0)"/"+(4<<y-3)else"")+" "))} m(io.Source.stdin.mkString)} ``` [Answer] ## J - 108 characters ``` exit echo}.,>,&.>/_4<@((a.{~32,65+7|4+i.&'o'),(>&0#('/',0":2^]))@((+/@(=&'\'))+2*'|'&e.))@;\|:|.[;._2]stdin'' ``` Ungolfed: ``` str =: stdin'' lines =: [;._2] str NB. split on the last character, the newline rotated =: |: |. lines NB. lines reversed, then transposed pitch =: 65 + 7 | 4 + i.&'o' NB. ord('A') + ( line.index('o') + 4 ) % 7 has_stem =: '|' & e. NB. '|' in line? backslash_count =: (+/ @ (=&'\') ) NB. sum(char = '\\' for char in line) denom_exp =: backslash_count + 2 * has_stem fraction =: (>&0 # ('/', 0": 2 ^ ])) NB. slash + 2^denom_exp, if denom_exp > 0 suffix =: fraction @ denom_exp note_string =: (a. {~ 32,pitch) , suffix NB. map(chr, (ord(' '), pitch)) + suffix boxed_note_string =: < @ note_string @ ; NB. box the string so it doesn't get padded each_note_of_the =: boxed_note_string NB. compute the note for a block of 4 lines join_to_one_box =: , &. > exit echo }. , > join_to_one_box / _4 each_note_of_the \ rotated ``` [Answer] ## Python golf, 207 chars. ``` import sys a=[x[:-1]+' '*99 for x in sys.stdin] for x in range(0,99,4): b=''.join((y[x:x+4] for y in a))+'o' c=2**(b.count('\\')+('|'in b)*2) print'FEDCBAGFE '[b.index('o')/4-len(a)+9]+('','/'+`c`)[c>1], ``` I've start code golfing with Python for 2 days and I found that things like `import sys`, `sys.stdin.read`, `sys.stdout.write` are expansive. ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- Happy Hanukkah! A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides: נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle. The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules: * נ (nun): Do nothing * ג (gimel): Win all the money in the pot * ה (hei): Win half the money in the pot, rounding up * ש (shin): Add one coin to the pot If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining. --- ## Task Your task is to implement the game of Dreidel. Input: * (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1. * (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once). Output: * (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game. Rules: * Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins! * Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome). * Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering. + All players must be represented in the output, even if they have no money left. * You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round. Notes: * It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.) Examples: (bear in mind that results are random) ``` >>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3) {"Abraham": 3, "Batya": 8, "Claire": 4} >>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15) {"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0} ``` [Answer] # [Python](https://www.python.org), ~~197~~ 195 bytes -2 bytes thanks to @Arnauld using `-~p//2` instead of `p//2+p%2` ``` from random import* def f(n,c,m,i=0,p=0,s=0): l=len(c);v=-~c[x:=i%l]and[-1,0,p,~-p//2][i//l&(s<0)and randrange(4)];c[x]+=v if~-l-c.count(-1)and-~i<m*l:f(n,c,m,i+1,w:=p-v*(c[x]>=0),[s-1,l][w<1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEN3nFFYkkN2OSYL4KY1BwDEsL1o3Bkv-KUlT2OQibLqBi3AKbsM0KixmRqN5b96b-fhK78NrDIfD524w_O7n23TRk24dtlisT7EbFtm2NcTQABo8WFFCwuhFyeqMOOHaQDVbjYJPWr7Vwp45hXTJK0AkTDwVxaWStijcOe2bkuFwFsB4aekVUyvkqaUYM2LNxB3XFzruwkB5dcTyyTZ-4ep_A8sK9rVIfFzQI_EejYDsUc4puW8qxU6nPOhoQ08EkddwA7cqM1Tmj5s2h_wpbjA_r723ba5gBkJVsix1FoXn_rTm7zO_) Takes in the mapping as a list of names `n` and a list of coin counts `c` which are the same length, along with a number of rounds `r`. Modifies the list of coins in place; the values indicate the number of coins, except for if `c[i]` is `-1`, which indicates that person `n[i]` is out of the game. It works recursively, storing the following between calls (in addition to the current number of coins): * `i`: How many players have played so far * `p`: the size of the pot * `s`: If positive, how many players need to contribute to the pot (set to `len(c)` when the pot is empty, otherwise decreased by one every call) [Answer] # [Python 3](https://docs.python.org/3/), ~~317 303 311 318 294~~ 270 bytes ``` def f(p,r): m=len(p) for k in p:p[k]-=1 for _ in range(r): for i in p: if p[i]<0:continue x=randrange(4) if x<1:p[i]+=m;m=0 if x<2:p[i]-=~m//2;m+=~m//2 if x>2:m+=p[i]>0;p[i]-=1 if m<1: for j in p:m+=p[j]>0;p[j]-=1 return p from random import* ``` [Try it online!](https://tio.run/##RY/NbsIwEITveQqLU1yCyE851MFI/X8IhCrT2GWD7VhWQKCqffV0HaftyTsz36zW7tofOlsNQyMVUanLPGUJMVxLmzqaENV5ciRgiWNue9wteBG9t@B5YT9kOjZGEyKIioAibgu7dc7eO9uDPcngXjhWmli7pRN3WRcssHNuasPzP7cc3QX/NstlWZt5HH7jTcnQCsQmryNYTJnBhWEcb2rjTSPbRraNrJf9yWOWKN@Z8JcGHzCu8/3N4DzYPlXp5@x@78VBmBkjq4zMHkR/FdP8qAV4GcRXRipKk//SkzhDg0mF2LMGYUPnDsULyLPUKEoUr2LvQWodwhJ3FCtKhx8 "Python 3 – Try It Online") * Thanks to Neil for spotting a bug (303 -> 311) * Thanks to AAM111 for cutting out the `import math` and spotting a bug (311 -> 318) * Thanks to c-- for some golfing suggestions (318 -> 294 and 294 -> 270) Players that are out are shown as having negative coins. ### Explanation ``` def f(p,r): # Create a function, f, which takes in the player dictionary, p, and the number of rounds, r m=len(p) # Assign the money pot, m, to the number of players for k in p:p[k]-=1 # And subtract one from each of the players (each player gives one coin to the pot) for _ in range(r): # Loop r times (r rounds) for i in p: # Go through each of the players if p[i]<0:continue # If they are out of the game (money = -1), skip their turn x=randrange(4) # Spin the dreidel (0 to 3) if x<1:0 # If it's 0, do nothing elif x<2:p[i]+=m;m=0 # If it's 1, add all the money from m to that player and set m to 0 elif x<3:a=(int(m)+m%2)//2;p[i]+=a;m-=a # If it's 2, add half the money to that player and reduce m else:m+=1;p[i]-=1 # If it's 3, add 1 to m and remove 1 from the player if m<1: # If m is 0 for j in p: # Go through each player if p[j]>0:p[j]-=1;m+=1 # If they're not out of money, reduce by one and add that to m else:p[j]=-1 # Otherwise, set their money to -1 (they are now out) return p # At the end of all the rounds, return the final dictionary from random import* # Import the random library for the dreidel ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 112 bytes ``` ≔Lθζ≧×LθηUMθ⊖ιW∧η⊖LΦ謋κ⁰«≔§Eθλ±ηεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η»UMθ⎇›⁰ι⁰ι⭆¹θ` ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVLLTsMwEJS4ha-wcrIlI5UCEq9LobRCAoRKb1UPpl0Sq45DbLdAUb6ECwcQ_BJ8DesmqdIiRC727uzOzHrz8jmKhRmlQr2-vk_d3db-90beslZGml6AjlxMM8bJnB1tXor7AujJKHa0LxOwnNSK4qLoNE0Socc046QNIwMJaAdjKhnCD7FUQGgL4XgVLnk6UjkwvvcqdZi0lk44abDiI8-bQWmu5c71GB4pCvpqhfpXEAkHNGZ4BxQL7lJD6JKn6sg8uuD0dBVfDy2nCd1FZOJ7q3wfjBbmaWml6Qs4OdeuLWdyDHTOyYl0D9KCV5owtsZQl-XkUurpLysTtqj_zy4jayu4VlO7cOPXE-S1geerw_163K4B4a-qIC4Zgr-3p1gpsbRAa3Cx-3xt-9XTVWINTqSfxB9Yfm2kdvTG4RH5LW5zkmH-zd6ObPkvfgzCrZkKh1_Hg-ewLfC9w0Oyw0l4pqTQAoMDDDoSZqAwaGLQFbdGglIebOacbO8NC64f) Link is to verbose version of code. Explanation: ``` ≔Lθζ ``` Each player puts one coin into the pot. ``` ≧×Lθη ``` The total potential number of plays is the number of players multiplied by the number of rounds. ``` UMθ⊖ι ``` Subtract one coin from each player (which they put into the pot above). ``` W∧η⊖LΦ謋κ⁰« ``` Repeat while there are still plays left and multiple players playing. ``` ≔§Eθλ±ηε ``` Get the current player. ``` F¬‹§θε⁰« ``` If they are not out of the game: ``` ≔‽⁴κ ``` Spin the dreidel, producing a random number from `0` to `3`. ``` ≔⎇‹κ²κ÷ζ~κκ ``` If it is less than `2` then the player loses this amount, otherwise they lose the pot divided by the bitwise not of the random number. Since the latter is negative, they win either the pot or half of the pot rounded up. ``` §≔θε⁻§θεκ ``` Subtract the loss from the player. ``` F¬‹§θε⁰≧⁺κζ ``` If the player is still in the game then add the player's loss to the pot. ``` »F¬ζ« ``` If the pot is now zero: ``` ≔LΦθ›λ⁰ζ ``` Put a coin into the pot for each player that is still in the game. ``` UMθ⊖λ ``` Subtract one coin from each player. ``` »≦⊖η ``` Move on to the next player. ``` »UMθ⎇›⁰ι⁰ι ``` Set the coins of players that are out of the game to `0`. ``` ⭆¹θ ``` Output the final number of coins for each player. I wrote this version before all of the rules had been clarified, so it appears that I might be able to save 16 bytes by considering the players in reverse order, not refreshing the pot if the first player scoops it on their very last spin, and outputting arbitrary negative values for players who are out of the game: ``` ≔⁰ζ≧×LθηW∧η⊖LΦ謋κ⁰«F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η≔§EθληεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»»⭆¹θ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZLPTsJAEMYTb-Upxp62yZIAauK_C4oQEjEEuREOCwx0w3ZrdxdQCE_ihYNGX0mfxt22EJSDvbQz83Xm983u6-cwZGoYM7HZvM_MuHj-fXRc1ZpPJClRWAZXhRZ7yhIdPgkN6fIINYV7lBMTkiSgEFrRIuQCgVTliIQUajhUGKE0OCK5sM6FQUUSCg-xsUmtyZRCKcgeWBW8cayAuOIyi70c46BBQyFznyL7P6P0PMt5G0cRswjJbwQROMG64O2skL1yZmA7rWqacoTPxEpdG5H6o4BOsiNM8bfKxFVTlH3qjuWII3JqK9MUL893UUmmXnYbqDgBhaY0NT7nIyRLCjfcLLhGN2maGtzvsD-WQovL2QHKNPX7L24Af462LWY6pVlm-1oX2opLQx6NfU3cRsoUEtv8TQ-GOr8vHz2_OBd-_-u6t_JrzHrwL-GEgn8nOJPMBhc2qHOco7BBxQYNNlAchXDFyppC-ayf9foB) Link is to verbose version of code. [Answer] # JavaScript, ~~167~~ ~~165~~ 164 bytes Been a long, long time since I tried golfing anything this complex in JS. So much so that I made a complete *mess* of things in my initial solution! This version seems to work properly, although it's pretty hideous. --- Takes the player data as a 2D-array. Call with `f(rounds)(players)`. Mutates the original input array. Remove the `&&--n` to ignore the rounds and allow the game to play through to the last player standing. ``` (n,p=o=0)=>g=a=>a.map(x=>x.o||(p||a.map(x=>x[1]?--x[++p,1]:x.o||=++o),x.o||(r=[0,p,p+1>>1,-1][Math.random()*4|0],r+1||x[1]?x[p-=r,1]+=r:x.o=++o),x))[o+1]&&--n&&g(a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hY_PSgMxEIfvfYqyhyUxydJYCypkxf8gqAePIYep3d0G0iSka9lC3sRLkfoevoZv4zYtevQ0fMNvvpl531o3qzYftfh8a2t2-r1FlnrhxAiLshEgSigW4FEnyq5wMSIf419HcnXBWCcJ8ZSr85QQhDhM9-Eg5Ih66gkvS04ZV_IR2nkRwM7cAuGjkzhSNBAeY1J10jMRehMRYSc7qDCWjnCV54zZPG8Q4MOtXzWyYowRCCmzy2mAOSwyOpwoOpTZFbRr-KVrAzpUCRUevDq7dKYqjGvQw8vzU7Fsg7aNrte9HA8GOy-fHMQ3sNKzfnKcRLdGg915zxLe6WpVmR6PE97DNOjKGEidfzft_9hs9vUH) Saved 2 bytes thanks to l4m2 ## Explanation ``` (n, // Take the number of rounds as n p=o=0)=> // Initialise p (the pot) and o (players out of the game) as 0 g=a=> // Named function taking the array of players as a a.map(x=> // Map each x in a x.o||( // Return property o of x (initially undefined) OR p||a.map(x=> // If p is 0 then map each x in a x[1]? // If the 2nd element (coins) of x is not 0 --x[++p,1] // Decrement it and increment p :x.o||=++o // Else get the OR of x.o and o incremented, eliminating the current player ),x.o||( // Return x.o OR r= // Assign to r [0,p,p+1>>1,-1] // Array of all possible results [Math.random()*4|0], // Get a random element r+1||x[1]? // If r is not -1 or the player has coins x[p-=r,1]+=r // Increment their coins by r and decrement p by r :x.o=++o // Else increment o and assign it to x.o, eliminating the current player ) // ,x) // Return x )[o+1] // If there are at least 2 players left in the game &&--n // And we have rounds left to play &&g(a) // Then call g again ``` [Answer] # C `-m32`, ~~233~~ 220 bytes + 4 bytes = 224 bytes -9 bytes thanks to ceilingcat (linebreaks for "readability") ``` m;k;i;j;l;f(p,r)int*p;{ for(l=wcslen(p);k<l;k+=2)p[k]--; for(srand(p);r--;m=l/2) for(i=0;i<l;k=rand(i+=2)%4) if(~p[i])if(k?k<2?p[i]+=m,m=0:k<3?p[i]+=j=m-m/2,m-=j:++m,p[i]--:0,!m) for(j=0;j<l;j+=2)p[j]>0?p[j]--,m++:(p[j]=-1);} ``` [Try it online!](https://tio.run/##bVDbTsMgGL73KbDJEhgQa6dejOGiPoKXW7Mga5W2sAZqPCz10a0/3aY39oL@h@8Emj9rPQxW1MKISjSixC3zxLhu2op9ufO4kW86NIXDLRH1ohE1lRlpV3XOuYj74JXbxqWHgZXNRUbi2MhUGIAbgLNajiAyuSKmxF/tyuRkXy/rRbaMNZWWWZnO68VsWUl7kVE7ydhhUzHLZTWn1I4DzuegW@JzO7pU4FKBS3UIVeW36TL@OGeW0jmOteSXLCWi7we4FbLKOEzQ/gzBt3nsVGf0RoVQ@A4H81nsSgwwgqREx1a/KI@mhKEkIWKkRR3l/SpHEu2vYXH35NWLsglDsbtX3Yc61g@NMr6AJu0P3BIDk6HZUWp8KpAz23cQS8VYLNCNOEU8@emdcQEg0RcwlObid693LgACck6RU7YAGP6bQfZ/Wa0H3RInk7Du1t1ku3YQM9LZweyYsB9PX3Sv3kHAs3741mWjnsPA7Sz7AQ "C (gcc) – Try It Online") This is basically a port of [The Thonnu's python answer](https://codegolf.stackexchange.com/a/255706/). The input is an `int[]` of the form `{5, "Abraham", 5, "Batya", 5, "Claire", 0};`, which is why the loops count by 2. This array will be modified by the function. We can get the length of that with `wcslen`. Ungolfed old version: ``` f(int *ptr, int rounds) { int length = wcslen(ptr); int money = length / 2; // one for each player srand(ptr); for (int i = 0; i < length; i += 2) ptr[i]--; // Decrement each by one for (; rounds--; ) { for (int i = 0; i < length; i += 2) { int k = rand() % 4; int half_pot = money / 2 + money % 2; if (ptr[i] >= 0) { k ? k < 2 ? ptr[i] += money, money = 0 : k < 3 ? ptr[i] += half_pot, money -= half_pot : ++money, ptr[i]-- : 0; if (!money) { for (int j = 0; j < length; j += 2) { if (ptr[j] > 0) { ptr[j]--; money++; } else { ptr[j] = -1; } } } } } } } ``` ]
[Question] [ [Curry is the Language of the Month](https://codegolf.meta.stackexchange.com/questions/24640/language-of-the-month-for-april-2022-curry) this month and some users are starting to get into it, so let's get some [tips](/questions/tagged/tips "show questions tagged 'tips'") together. Haskell and Curry are similar in a lot of ways and a lot of tips for Haskell work well in Curry and vice versa. So I'd like in this question to gather tips for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") in Curry, that would be useful to someone who has read up on our [Haskell tips](https://codegolf.stackexchange.com/q/19255/56656) extensively. This would cover cool things you can do in Curry that you can't do in Haskell, as well as tips for getting around the cool things you *can't* do in Curry that you might be used to from Haskell. Please post only one tip per answer. [Answer] # Use `++` in patterns In Haskell we are used to handling lists with `:` as our pattern. Curry1 can do this but it can also use `++` in patterns. This can be used to pattern match longer prefixes for strings, e.g. this Haskell pattern: ``` f('a':'b':'c':x) = ... ``` works in Curry, but can be shorter as: ``` f("abc"++x)=... ``` However it can also match much more exotic things. ``` f(x++"abc"++y)=... ``` This pattern matches all strings that have `abc` as a substring somewhere. This can't even be written as a pattern in Haskell and requires a guard at the minimum. ``` f(a++[b])=... ``` This pattern matches lists ending with the element `b`. It's the sort of pattern that Haskell programmers can attest would certainly be useful for many things. This can be combined with other tricks to get *even more powerful* patterns, for example: ``` f(a++a)=... ``` This matches strings which are made up two copies of the same string concatenated. `++` patterns aren't just a way to write certain patterns more efficiently. They allow us to represent much more complex patterns on lists than were even possible before. --- 1: `++` can be used as a pattern in PAKCS, KiCS, and MCC Curry, but does not work in Sloth, so this tip is not applicable there. [Answer] # Use `?` as or-patterns In languages like [Mathematica](https://reference.wolfram.com/language/ref/Alternatives.html) or [Rust](https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#multiple-patterns) or [Python 3.10](https://peps.python.org/pep-0636/#or-patterns), there are some kind of "or-patterns", usually written in the form `a|b`, that could match either `a` or `b`. Haskell doesn't have such thing. But in Curry, you can write `a?b`. For example, instead of ``` f a=someExpr a f b=someExpr b ``` You can write: ``` f c@(a?b)=someExpr c ``` Unlike other languages, `?` isn't a special symbol for patterns. It is just a built-in function that returns either of the two values. Using `a?b` in patterns is just another example of functional patterns, just like [`a++b` in Wheat Wizard's answer](https://codegolf.stackexchange.com/a/245962/9288). ]
[Question] [ You are an evil wizard, doing evil wizard business, when suddenly your crystal ball alerts you of a hero on their way to defeat you. To crush their hopes and dreams, you decide to trap the hero in a maze. You could just make a big maze but where would be the fun in that? Instead, you decide you want to make the maze as small as possible for a truly humiliating defeat. Thanks to your wizard skills, you know in advance how the hero will navigate the maze. The hero's moves are represented by a list where each element can be one of "LR", "LS", "RL", "RS", "SL" or "SR". Inside the maze the hero moves forwards until they reach an intersection. Then the corresponding element in the list tells which direction the hero should continue. The hero first tries to move in the direction represented by the first letter, and next in the direction represented by the second letter. So for example, if the hero's moves are `["LS", "SR", "RS"]`, at the first intersection the hero will turn left. If that is not possible, they will go straight. Similarly in the second intersection, the hero will try to go straight, but if that's not possible, they will go right instead. If the hero reaches a dead end or the beginning of the maze, they will just turn around. If there is a corner (the path just turns), then the hero will just follow the path. These interactions don't require any decisions, and therefore don't consume the decision list. The hero gives up when they reach an intersection, but the decision list is consumed. # Rules You are given the hero's move list as input and you have to output the maze as output. The maze begins at the upper left corner and ends at the lower right corner. The maze must be possible to traverse. You can use different values for "LR", etc, but please don't encode any extra information in the values, such as code. Output the maze as ascii art like this: ``` █ ████████ █ █ █ ██ █ █ ███ ██ ███ █ █ █ █ ████████ █ ``` You can also use different (distinct) characters for the wall and air. You can also return a two dimensional or flattened two dimensional list with two distinct values for wall and air (if you use a flattened list, please also return at least one of the dimensions to remove ambiguity). Since the outer border of a maze is always the same, you can return just the inner portion (also applies to ascii art output). The maze cannot contain any areas accessible to the hero where the hallway is wider than one block. So for example: Not Ok: ``` █ ███ █ █ █ █ ███ █ ``` Ok: ``` █ █ █ ████ █ █ ████ █ ``` The size of a maze is the area of it's rectangle bounding box. For example, the preceding maze has size 24. You must output the smallest maze, where the hero gives up. In case of ties, any minimal solution is fine. The input list has at least one element. # Test cases ``` ["LR"] -> █ ██ █ █ ██ █ █ █ ██ █ or █ ██ █ █ █ ██ █ █ ██ █ or █ ███ █ █ █ █ █ ███ █ ["RL","RL","RS","LS","LR","RS","RS","SR","LR","RL"] -> █ ███ █ ██ █ █ █ █ █ ███ █ ["LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS"] -> █ █████ █ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █████ █ ["LR","RL","LS","LR","LS","LR","SR","SR","LR","SL","RL","SL","RS","RL","SR","LS","RS","SR","LS","SL","RS","SL","SR","SR","RS","RS","RS","RS","RL","LS","RS","RL","RL","SR","RL","RS","SL","RS","LS","RS","SR","SR","SR","RL","RL","SL","LR","LR","RS","RL","SR","SL","SR","RS","SR","RS","RS","RL","RL","RS"] -> █ █████ █ █ █ █ █ █ █ █ █ █ ██ █ █████ █ ["LR","RS","LR","RS","SR","RS","RS","LR","RS","SR","SR","SL","RS","LS","SR","SR","RL","RS","LS","LR","RS","RL","RL","RL","SL","SL","RL","RS","RS","RS","SL","SL","SR","RS","RS","LR","RS","RL","LR","RL","RS","SL","LR","RL","LR","SR","RS","LR","LR","RL","RS","SR","SR","LR","SR","SR","SL","RL","RS","LR","RS","RS","RS","LS","LS","RL","RL","SL","LS","LS","SL","RS","LS","RS","SL","LS","LS","RS","LS","LS","SL","SR","LS","RL","SL","LR","RS","RS","RS","RS","SL","LR","RL","RL","RS","SL","SR","RS","LR","RS","RS","LS","RS","LR","RS","SL","RS","LS","RS","SR","RL","RL","RL","LS","RS","RS","RS","LS","LS","SR"] -> █ ████ █ █ █ █ ██ █ █ ██ ███ █ █ ██ █ █ ████ █ ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~1206 1095 1052~~ 866 bytes ``` H=range R=input().split() s=0 while s:=s+1: B=[[*map(int,bin(2**s|k)[3:])]for k in H(2**s)] for a in H(2,s): for c in((b:=s//a)*a==s)*B: m=[[1,0,*[1]*a],*[[1,*c[a*n:a*-~n],1]for n in H(b)],[*[1]*a,0,1]];I=0;P=[0,1];D=[1,0] while[b,a]>=(P:=[P[0]+D[0],P[1]+D[1]])>[0for T in B if 1>T[-1]==T[0]and all(W or len([w for w in[i%a>a-2 or T[i+1],1>i%a or T[i-1],i+a>=len(T)or T[i+a],i<a or T[i-a]]if 1>w])==1+(len(T)-1>i>0)and 1>c[i]for i,W in enumerate(T))]>[1for c in H(a)for r in H(b)if 1>m[r+1][c+1]+m[r][c+1]+m[r][c]+m[r+1][c]]: A=[l for l in[[0,1],[1,0],[0,-1],[-1,0]]if 2+b>P[0]+l[0]>-1<P[1]+l[1]<a+2>1>m[P[0]+l[0]][P[1]+l[1]]!=[-l[0],-l[1]]!=D] if A[1:]:R[I:]or exit([print(*r,sep="")for r in m][0]);F,S=R[I];f=lambda Q:[D,[D[::-1],[-D[1],0]][D[1]],[[0,-D[0]],D[::-1]][D[1]]][ord(Q)%5%3];D=[f(S),Z:=f(F)][Z in A];I+=1 else:D,*_=*A,[-D[0],-D[1]] ``` [Try it online!](https://tio.run/##VVJta9swEP6eX6EVCpIsr1HKYCg9Q0ooHfRDagcKPY6hpM4q6rjGTskGY389Oylpx0BI9/rcPafrfu2eX9vLr11/ONxC79sf9aiE0HZvO6k@D10T@B0NMB7tn0NTi8HBkFk3EteAqLe@k6HdmVVo5UTr4feLwktHijavvXgRoRW3ya5oJKLJn0xmUAyRTGs2Sbli2IsLr7QHGJS@jl6x5RLWjI1GS9oTv6zqNXrdOq/zPy0Zmyq1R9iVIoPHYM6yRNNvMJ4uAKMynUMEowicqODKeCpALhzgAseUzfkyC05niZNVgeMIvozg1yJshC2WmFsCWHKkb5@Ebxr5IDimqVuJ@8Rnz@EYzn3h80l0LTFklhst2HbSGcOEzBcQ05bqFMQEw9VHiCdKFfekAGwmj6E5wxRjFWvbYo0hsQ/mIbZYt2/buve7muMUFWjfp8uT8Soq/fuYEvIWe24M13xlLP8npTd5idJXiBlgk/g1kV@aqEnzNCxHQjwZ1mLTk2xVpIE2fBW5vUozbfi68tmkiJU/3IQfTvoEmEebyU/qPH1WnPwMrSNX4jdH3EL9k5cSu543T@reDHUHZ2f/GG6JQdT0xlTAGTTdQOO3qycv7h3ODc7RuWPD8Ztjz5j@20RWeVwCMqeYk4fwtX@S9@r8y/ll2qONrJR5dLCRN4rwMRad8bJlYFPDdTPUbm70d9CzVCZySkiHw10pykpUpbirRHknqnTKdKLrKFR/AQ "Python 3.8 (pre-release) – Try It Online") This version brute-forces every possible maze. The results don't match the test cases, but then again, the other answers don't match the test cases either. Takes way too long to solve the third one, however. ## More explanation The code creates a variable called `s` which holds the size of the inner maze. At each iteration, we generate all binary strings of length `s` (where a 1 is wall and a 0 is air) using a trick to avoid having to use lengthy padding methods, and ensuring that it doesn't start with a 1 in order not to have to check for impossible entry into the maze. We go through each width from 2 to `s`. If this width does not divide `s`, dismiss it. Otherwise, we generate the mazes with the wall/air determined by the binary string, and the width/height determined by this divisor. We dismiss the maze if it is not traversable (a maze is traversable if, out of the binary strings, you can find one in which the zeroes form a linear path from the beginning of the maze to the exit) or if there is a 2x2 block of zeroes within the maze (disallowed by the OP). Then, we run a simulation of the maze. We initialize the directions, decision number, and position, and update the position accordingly at each iteration. If the exit is reached, we break out of the current loop and move on to the next binary string. Otherwise, we calculate the number of possible directions to go at an intersection (excluding the way we came, of course), and: * if there is no direction left (i.e. the hero hits a dead end), turn around, i.e. negate the direction; * if there is one direction left, simply go that way; * if there are two or more directions, we take the current decision. If there is no such decision, meaning we have consumed all decisions, that is victory and hence we break out of all loops. Otherwise, we try following the first choice of that decision, and if impossible, we follow the second choice (one or the other is guaranteed to work, as some simple mathematical reasoning will reveal). We then increment the decision number. We increment the size of the maze once all factorizations and binary strings have been exhausted for that particular size. Once we have found a good maze, we output it with a nice output format. *I insist on the nice input/output format.* ## Acknowledgements Thanks to @AnttiP, the OP of this challenge, for golfing off an astonishing 186 bytes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 314 bytes ``` f=(x,n=8)=>(g=(s,i=n)=>s[n]?i>2?(h=x=>~n%i|M.some((_,b)=>(s[b+1]&s[b+i]&s[b-~i]|-~b%i<2|b<i^b>n-i^b==1^b==n-1)&s[b]|[...E.filter(j=>+s[j+P])[2]?x[R++]||[]:_].some(g=>+s[p=P+E[+g+W&3]]&&(P=p,W+=+g))&P>n-3,P=W=R=0,E=[1,i,-1,-i]))(M=[...(x+1).repeat(n)].fill('3012'))>h(x)?[s,i]:g(s,i-1):0:g(s+1)||g(s+0))``||f(x,n+1) ``` [Try it online!](https://tio.run/##JVBNi8IwFPw1W98jHzT1soivPXkUihcPIavWbWukmxYjSw/Bv95N3MvM8BiYeXO//F789WGnp3Djd7ssHcHMHX0ildATeG7JRe21M5UtiwpuNFP5ch827KUff1qAE2@S2@uGKZMlsm8SL2uCeDUfdluEZmu/mtKJiEQqgRMKk80ELaXcyc4Oz/YBdyqZ13dWG9SFqWZ9YMyEoM3mZP4D@7djoprtNOvZMVsbk2VQ08SPjFiPmNUxac1rOtKBcr4jrbjlQnFhDSLsKSXCzGaUj3ZqL09waFKBAVbrXBUrxPIGM1Y6/m82fZohtt3kSTKFISTOEc/nELo0WDwu19H5cWjlMPbQgY5Jyx8 "JavaScript (Node.js) – Try It Online") EDIT: Fixed a bug(not enough steps for `LS RS RS ... RS LS LS`), making it MORE slower ``` 01000 01110 01010 01110 00010 ``` Slow even for smallest input `[]`, returning (same as 1st case) ``` 0100 0110 0100 0110 0010 ``` For the 2nd case f(['13','13','10','30','31','10','10','01','31','13']), output is ``` 01000 01100 01010 01110 00010 ``` not further tested ``` f=(x,n=8)=>( // start from size=9, though startting from 10 also work g=(s,i=n)=> // recurse s[n]? // otherwise g(s+1)||g(s+0) i>2?( // width>=3 h=(s,i,x)=> // runable checker ~n%i| // rectangle (n+1 is the size) [...s].some( (t,j)=>( // no 2*2 road, border is correct. 1 if don't satisfy s[j+1]&s[j+i]&s[j-~i]|-~j%i<2|j<i^j>n-i^j==1^j==n-1 )&t )|| M.some(_=> // walk for enough time [...E.filter(j=>+s[j+P])[2]?x[R++]||[]:'0132'] // if branch then take instruction, otherwise try 3 forward then one back .some(g=>+s[p=P+E[+g+W&3]]&&(P=p,W+=+g)) // try walk &P>n-3,P=W=R=0,E=[1,i,-1,-i] // if at aim ) // it starts at (0,0) and go right, but can never go back to (0,0) since it's a wall )(s,i,M=[...s+s].fill('30')) // Using fact that '30'(LS)*inf always go for a possible maze to share code &&!h(s,i,x)?[s,i]:g(s,i-1) :0:g(s+1)||g(s+0))``||f(x,n+1) ``` [Answer] # Python3, 1651 bytes: ``` import copy,time M=[(0,1),(0,-1),(1,0),(-1,0)] R=range E=enumerate def v(m,n): for j,k in M: if(q:=n[0]+j)<0 or(w:=n[1]+k)<0:return 0 try: m[q][w] except:return 0 for q,l in E(m): for w,s in E(l): if not s: try: if not any([s,m[q][w+1],m[q+1][w],m[q+1][w+1]]):return 0 except:1 return 1 class H: def __init__(self):self.s={} def g(self,m,e,s): if e in s: yield(m,s);return for x,y in s: for j,k in M: if 0<(q:=x+j)<len(m)and 0<(w:=y+k)<len(m[0])and m[q][w]: B=copy.deepcopy(m) B[q][w]=0 if (q,w)==e or v(B,(q,w)): if (q,w)not in self.s.get(tuple(sorted(s)),[]): self.s[tuple(sorted(s))]=self.s.get(tuple(sorted(s)),[])+[(q,w)] yield from self.g(B,e,s+[(q,w)]) T={0:{'L':((0,1),1),'R':((0,-1),2),'S':((1,0),0)},1:{'L':((-1,0),3),'R':((1,0),0),'S':((0,1),1)},2:{'L':((1,0),0),'R':((-1,0),3),'S':((0,-1),2)},3:{'L':((0,-1),2),'R':((0,1),1),'S':((-1,0),3)}} U={0:3,3:0,1:2,2:1} def r(d,c,w,e,s): if c==(0,1):d=0 if c==e:return 0 if not(m:=[(a,(x,y),D)for a,(q,D)in T[d].items()if(x:=q[0]+c[0],y:=q[1]+c[1])in w]):return r(U[d],c,w,e,s) if len(m)==1:return r(m[0][-1],m[0][1],w,e,s) if not s:return 1 W={a:(c,b)for a,b,c in m} return r(*W.get(s[0][0],W.get(s[0][1])),w,e,s[1:]) def S(s): L=set() P=max(4,len(set(s))) k=P+1 while k: for i in R(P,k): for j in R(P,k): if (i,j)not in L: L.add((i,j)) b=[[1 for _ in R(j)]for _ in R(i)] b[0][1]=0 t=time.time() for G,W in H().g(b,(i-1,j-2),[(0,1)]): if time.time()-t>5:break yield(G,W,(i-1,j-2)) k+=1 def f(s): for G,W,e in S(s): if r(0,(0,1),W,e,s):return G ``` [Try it online!](https://tio.run/##pVRLj6NGEL7zK1pzcXfctsxMIkVkO4fVrnYPvdIIdjUHhCxs2rPYBtvAxLZG/u2Tqm5ezZDkEMkqU0U9v/qK47X6ecgffj8Wb29pdjwUFVkfjldepZlyvomQLrjLOMgZ/rl8AXKGf5HjiyLOn5XzWaj8JVNFXCknURvyF814zjyHbA4F2fIdSXPyDVSSbujJE3m4iKZb9mFBDgU9o@5G0x3oXqGqlyInC3CtiitGkCw8ReE5gkd1Watj1fPB7Ce@x@yfaYb1tOnMS2PaaxMUJfmhIqVW2rytPc6vNCy5qTN1I3yCP6jZPoGIWL@5thnXIbXZddb7uCzJV8iOGCyXaZ5WyyUt1X7DPJTzUrzezNtnbeYZV7xkBhmisGvT5TVV@wRALNkfJn092oVfO6chuDrJ4gMifEF49yoHVOI8QSPAfEWMtRHw1/Ya2xqPjwL3Pk@UOuIDxNZ24yUWLWz0xM9MCAX7g11/5FpndZrWAcHFZvXk82dV0erluFe0BIqphJaM8TBqo2q/cOgTif9IMA11tajJo7Ejm@KQmZTP0CCg3Lgx57t4XXivEznxqOE2/Ca@0ZDj96AGqGquL9iNu4275j1/aPxrh9q9znXj9417@963g4N@sRt/6Lpp6vtWc0E//HZzfuAEDxAHHt491HNv@u4KmvA1PzekgkWshdBpvATXZwyqx2RzAzTz4M5jToFfjH9iyKwYt/qJwQK/h0k0TyuVlZTBAV88ccIDXoPgV1RcVNwIfc/dnRT0BwS2/ehahpJCuJ0TkjGc6bODB/jvuZuzbQ@MPInX2KNrvqo7XPE1Miy7tVdY0F@eNFNKzAYN9jTokJnsoesBDxCxgGqkJJCsolD0UWTxhf7KsVE0AcfAuhOPUyh//pnuFdk135kUa/v0ke9Yd48Dmz6GlG@bY5AN3eU8ThKqXzFQa@tKhKGrEy1Noi2LelrasnxlBmpuklQCP9dzFLQ@W53mC3/C0K@UwR2sOE2BRdsZMMx81nvnB432UsyqP3/zVoWKd9ZZUcjXJcFCu6lwNZIbg2RdlOuPWY0u5i6gniH0k6FnvbAvb8cizSu6oeFE@hNYkdMa7nx5x2sRgJBa@I2qReC3NnlnR6M7@b9ykNJvGup66Z4C32ooaLsP2hGM2ob1Rggsv0Ba@bp5e0JaWTqsAt9CLbDx60r20tudSt/GuetFWg0NW@tvaww3e32D6MGLrl7X@rDhMU7I9@MENot63JHvZ/JH8skRQHtMsLck/ZGIATEGA8qRuoE9YDCypeA9baQ9m7Rtg4geDe3Vj7FtMLQ/wtSxEeTYfv@JkIPlyeDf0IAI4Njb3w) Produces the correct mazes for all the test cases in under 60 seconds. [Answer] # [Python 3](https://docs.python.org/3/), 2̶9̶3̶1̶ 1765 bytes It's long, it's ugly, but it works (and for an infinite maze size). Brute force method, and it takes quite a while to run all test cases (took me ~15 minutes). Big thanks to @ThisFieldIsRequired and @12944qwerty for helping me shave it down. ``` def f(a): from pathfinding.core.grid import Grid from pathfinding.finder.a_star import AStarFinder as A c=[] r=None x,y=4,4 while 1: z=x-2 v=y-2 e=(x-2)*(y-2) if c and x*y>=r:pass else: for i in range(2**e, int(''.join([t for u in [['1']+['0']*(v-1) for t in range(z)] for t in u]),2),-1): o=list(a) p=list(map(int, format(i,'b').rjust(e,'0'))) b=[p[(i*z-z):i*z] for i in range(1,v+1)] if 0 in [b[0][0],b[-1][-1]]:continue g=Grid(matrix=b) s=g.node(0,0) d=g.node(z-1,v-1) h=A(diagonal_movement=2) P,R=h.find_path(s,d,g) if len(P)==0:continue B=0 for k in range(v-1): for l in range(z-1): q = [b[k][l],b[k+1][l],b[k][l+1],b[k+1][l+1]] if 0 not in q:B=1;break if B:break if B:continue b=[[0]+l+[0] for l in b] b.insert(0, [0 for f in range(x)]) b.append([0 for f in range(x)]) b[0][1],b[-1][-2]=1,1 L=[[1,1],[0,1]] d=[y-1,z] o.reverse() while 1: if [L[0][0], L[0][1]]==d:break U=[L[0][0]-1,L[0][1]] U.append(b[U[0]][U[1]]) D=[L[0][0]+1,L[0][1]] D.append(b[D[0]][D[1]]) S=[L[0][0],L[0][1]-1] S.append(b[S[0]][S[1]]) R=[L[0][0],L[0][1]+1] R.append(b[R[0]][R[1]]) Q=[U, D, S, R] O=sum([U[2],D[2],S[2],R[2]]) if O==1:L[0],L[1]=L[1],L[0];continue elif O==2: for C in Q: if [C[0],C[1]] == L[1]:continue elif C[2] == 1:L=[[C[0],C[1]],L[0]];break continue else: try: I=o.pop() except IndexError: c=b r=x*y B=1 break Y=[q-w for q,w in zip(L[0],L[1])] for m in I: if m=="L":T=[-Y[1],Y[0]] elif m=="R":T=[Y[1],-Y[0]] else:T=Y N=[[q+w for q,w in zip(L[0],T)],L[0]] if b[N[0][0]][N[0][1]]:L=N;break if B:break if x!=y and x<y:x,y=y,x elif x!=y and x>y:x,y=y,x;continue if x==y:x+=1;y=4 else:y+=1 if c and r<=x*4:break return c ``` [Try it online!](https://tio.run/##pVfNbuM2EL7nKVhfLNm0Ybk5KcsASdwWCwjZXSk5BFoikGza0caWFEpObBe99wn6gH2RdEjZov6zQIWEJjkzH@fnE0nF@/QpCn99T1mSIoLcM7dn2T2Ks1@MerYjWkf2Ldm3LTlTaO1Ce7QqzjhHPEdh/I82903Cy7lsqHpO3mRD66Sc9Zx8mJvJOTVUeo5VwrOdhsYqodhWCd4uQ8leZckCfNlTKw@h4rPySqHYDR7YTq@QLqeEVjGqCNQyyuOqn04p6dWl8ygcq2ShGiVt9cXO01DJY4EA5eIUcmbVI6rQo@Ka1VBiSxWsUhynzharHJtVnqtYFNhXrngTySpB2w0EbQrBaqpvGw8rxbOcrmw4cpeg7wu2REvN080zBM@SRxsUe@nTMggXQbgazyPOxiseLFCwiSOeoj@g36wqfhkfe49J6vGT@pUDg9@lBHkJupKmc@JS2eHkNgqZ7O7wnpzjc9l/ewrWDBmZS@I5kN1omo9eyb4wYkQDoT7QYFLPZ4MlmiMvXKDdYH9JuBl7SaJM1glT4DKYCDxGQYi4F66YNh0MGIZhqvX74x9REGpuKnW2Qsd1@0afDt3@pE8H2uvI0KUsVfYHnaqpLdXxVMegVl5TPBFZB0kK6a9J4kyy8WIN/MACbuOlWoD7fl8f8x9bEDIMLuh63dgnbuxqweAwOugm/NBqgAZ@HRo6rRlC2iYyRN@dUPjDvjsyqPin5jwK0yDcsprRighSgKspD3bEr7uTkNU4jBZMm@BJXbo4SQ8jcAvSVNN4IlfaIvBWUeitHzfRK9uwMCXTuuJXbJMnScRHwUwtwQu80puiXLNQ@6oTMmkP65pManMijc8qja@NRT0prguEaFUUz4s4uX33mbprkfHnoXHqwS8M8jloaCuKrF0YSc69mNfEuPA5857PWnSvzWaxFLUmBZgFtBiuh9CqIP26V/44CBPGU6g5cidSdanysdNpA2vHXhyzcKH9rL7gqJFzdEqJgY2algUewzzF7gQ3pW9B3D0Q71CXRGPOXhlPmFZfu7ZFVVLoWscXCFmZl5SQhdlekHtysgBfTibNmqcs@e496FFoQVVv1J3lqMMPUGcKdSZRZ@2oTo56woT8N2sqVEeiOu2odg112IJqK1RbotrtqN@Ie4/RDCMHI7sZ7gtJthsN0jileCYaRzQ2NC2YUN4vhBimlflqUCIa6fVF64uTnTuZ6bR9KxC8vxG8/9auc6LYjVj/RsSOCEHCB7Nz@ZIbNxCfMIMw4AVRUDIM2rF1yAO8O8rq6Vp8Ur7vjuwzicZxFGt6qxbbzVmcos9wqdj9xnnEuwHnxO@UcwJ3hE4N2Es75d3JeiDuy@hNVvYFv4naHoJYy8mj004ybITB5w/JsCGkZ/XMO@KOHgQZH0QVP2aBMLOlmbQa/YwZVPeOPHQq3QKlXobNMd/pR459FJLv3mb7Ac064g5ikduLjmOrLIKp3S9kn10DP@1NccXc491ZKQNK4zLXqL/FQpEQUBjCsQoX1fJVcj8sECS/efJPQKzzgk@cpVseovm7vIzJ25j4bM9qG3Nx3QwC3Pseji6/h/ClDFsc6fez92DjHRjcEpagkU3IszcImUARQsUQIUni7B4gNMrcAfeEsE6ozIEeqizc/VYfjf795@8Gs6OwFks2v@w54uMCBYmJ/hTXMRGFPjj1oOL6X2Cqnx1hZvCl0NPf/wM "Python 3 – Try It Online") Outputs: ``` ['LR'] -> █ ███ █ █ █ █ █ ███ █ Score is: 20 ['LR', 'RS', 'SR', 'LS', 'RL', 'SL', 'SL', 'RL', 'RL', 'LR', 'RL', 'RL', 'LS'] -> █ ██ █ █ █ ██ █ █ █ ██ █ █ ██ █ Score is: 28 ['LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS'] -> █ █████ █ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █████ █ Score is: 49 ['LR', 'RL', 'LS', 'LR', 'LS', 'LR', 'SR', 'SR', 'LR', 'SL', 'RL', 'SL', 'RS', 'RL', 'SR', 'LS', 'RS', 'SR', 'LS', 'SL', 'RS', 'SL', 'SR', 'SR', 'RS', 'RS', 'RS', 'RS', 'RL', 'LS', 'RS', 'RL', 'RL', 'SR', 'RL', 'RS', 'SL', 'RS', 'LS', 'RS', 'SR', 'SR', 'SR', 'RL', 'RL', 'SL', 'LR', 'LR', 'RS', 'RL', 'SR', 'SL', 'SR', 'RS', 'SR', 'RS', 'RS', 'RL', 'RL', 'RS'] -> █ █████ █ █ █ █ █ █ █ █ █ █ ██ █ █████ █ Score is: 42 ['LR', 'RS', 'LR', 'RS', 'SR', 'RS', 'RS', 'LR', 'RS', 'SR', 'SR', 'SL', 'RS', 'LS', 'SR', 'SR', 'RL', 'RS', 'LS', 'LR', 'RS', 'RL', 'RL', 'RL', 'SL', 'SL', 'RL', 'RS', 'RS', 'RS', 'SL', 'SL', 'SR', 'RS', 'RS', 'LR', 'RS', 'RL', 'LR', 'RL', 'RS', 'SL', 'LR', 'RL', 'LR', 'SR', 'RS', 'LR', 'LR', 'RL', 'RS', 'SR', 'SR', 'LR', 'SR', 'SR', 'SL', 'RL', 'RS', 'LR', 'RS', 'RS', 'RS', 'LS', 'LS', 'RL', 'RL', 'SL', 'LS', 'LS', 'SL', 'RS', 'LS', 'RS', 'SL', 'LS', 'LS', 'RS', 'LS', 'LS', 'SL', 'SR', 'LS', 'RL', 'SL', 'LR', 'RS', 'RS', 'RS', 'RS', 'SL', 'LR', 'RL', 'RL', 'RS', 'SL', 'SR', 'RS', 'LR', 'RS', 'RS', 'LS', 'RS', 'LR', 'RS', 'SL', 'RS', 'LS', 'RS', 'SR', 'RL', 'RL', 'RL', 'LS', 'RS', 'RS', 'RS', 'LS', 'LS', 'SR'] -> █ ████ █ █ █ █ ██ █ █ ██ ███ █ █ ██ █ █ ████ █ Score is: 48 ``` ]
[Question] [ > > In response to [here](https://codegolf.stackexchange.com/questions/224852/drawing-the-stack-overflow-logo#comment520524_224852). > > > Unlike [the previous one](https://codegolf.stackexchange.com/questions/4561/generate-the-stack-overflow-logo), this focuses on [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and a new logo, no longer consisting of 6 sticks and the graying-effect as the position of the sticks go deeper. > > > Make the Stack Overflow logo using the following criteria: [![Stack Overflow logo](https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png)](https://stackoverflow.com) **The tray:** * Make a gray tray shaped like a bracket facing upwards using the following RGB values: 188, 187, 187 (#bcbbbb) * The dimensions of the tray by pixels: ![dimensions](https://i.stack.imgur.com/JSl3y.png) **The sticks:** * Make 5 orange sticks using the following RGB values: 244, 128, 36 (#f48024) * Each stick has a dimension of 44 by 9 pixels. * The gap between the tray and the bottom stick is 8 pixels: ![8 pixels](https://i.stack.imgur.com/J81vc.png) **The sticks' angles:** *These angles are relative to the horizontal position which is zero degrees.* * 1st stick (bottom): 0° * 2nd stick (second-to-bottom): 10° * 3rd stick (middle): 25° * 4th stick (second-to-top): 40° * 5th stick (top): 50° **The entire image:** * The image should look like the image given. * The entire dimensions of the whole image is 82 by 97 pixels. **Stick positions (`x, y`):** *These coordinates refer to the top-left points of each stick. The system used is the top-left point of the entire surface being (0, 0), and the numbers increasing as we go down and to the right. We also assume that the left part of the tray is at the leftmost possible point, i.e. at the far bottom left. Feel free to transcribe this into your system.* * 1st stick: 17, 71 * 2nd stick: 19, 51 * 3rd stick: 27, 31 * 4th stick: 40, 13 * 5th stick: 55, 0 **Rules:** * The image should apply all descriptions from above. * Standard loopholes are forbidden. * Shortest code in bytes wins. [Answer] # HTML+CSS, 550 bytes ``` div {position: absolute;} .z1 {background:#bcbbbb;top:80px;width:78px;height:34px;} .z2 {background:#ffffff;left:9px;width:60px;height:25px;} .s {background: #f48024;top:-15px;width:44px;height:9px;} .a {top:8px;left:8px;} .b {transform:rotate(10deg) translate(1px,1px);} .c {transform:rotate(15deg) translate(2px,-1px);} .d {transform:rotate(15deg) translate(2px,-1px);} .e {transform:rotate(10deg) translate(1px,1px);} ``` ``` <div class='z1'/> <div class='z2'/> <div class='s a'/> <div class='s b'/> <div class='s c'/> <div class='s d'/> <div class='s e'/> ``` [Answer] # Python + Pygame, ~~319~~ ~~303~~ ~~273~~ ~~260~~ 252 bytes Many bytes shaved off thanks to @ovs and p1131. ``` from pygame import* e=display s=e.set_mode((82,97)) s.fill(T:=8**8-1) R=draw.rect R(s,0xbcbbbb,b'\0?N"') R(s,T,b' ?<') for*i,x in b'GH',b'3F',b'C',b'(\r@',b'7\0>':A=Surface(b', ',4**8);A.fill("#f48024");s.blit(transform.rotate(A,x*5),i) e.update() ``` [Answer] # JavaScript (Canvas API), ~~379~~ ~~341~~ ~~339~~ ~~328~~ 292 bytes I tweaked the angles a bit to get it closer to the actual logo, but you could change them back to the original suggestions easily (via the `s()` function). 292 bytes == the minified JS code in the snippet at the bottom plus the HTML line (not including `<script>` tags which don't appear in the snippet). **Ungolfed:** ``` <canvas> <script> c = document.body.children[0].getContext`2d`; s = (x, y, d, p = "#f48024", w = 44, h = 9) => ( c.translate(x, y), c.rotate(d), c.translate(-x, -y), (c.fillStyle = p), c.fillRect(x, y, w, h), c.setTransform() ); s(0, 63, 0, "#BCBBBB", 78, 34); s(9, 63, 0, "#fff", 60, 25); s(17, 71); s(20, 51, 0.22); s(27, 32, 0.43); s(40, 13, 0.7); s(55, 0, 0.93); </script> ``` **Minified:** ``` c=document.body.children[0].getContext`2d`,s=(a,b,e,d="#f48024",f=44,g=9)=>(c.translate(a,b),c.rotate(e),c.translate(-a,-b),c.fillStyle=d,c.fillRect(a,b,f,g),c.setTransform()),s(0,63,0,"#BCBBBB",78,34),s(9,63,0,"#fff",60,25),s(17,71),s(20,51,.22),s(27,32,.43),s(40,13,.7),s(55,0,.93); ``` ``` <canvas> ``` Edits: * @ophact's suggestion to remove quotes from the `canvas` ID field saves two bytes * @ovs's byte-save * remove all unnecessary html / API characters and elements [Answer] # HTML + CSS, 21 + 232 = 243 bytes ### HTML ``` <a><b><c><d><e><e><d> ``` ### CSS ``` a,a *{height:100vh;margin:auto;display:grid;transform:rotate(var(--))}b{border:9px solid#bcbbbb;border-top:0;width:60px;height:25px}b *{background:#f48024;width:44px;height:9px}d{--:10deg;margin:-15px 1px}e{--:15deg;margin:-17px 1px ``` ### Try it: ``` // (Remove <script>s inserted into Stack Overflow snippet) while(document.scripts.length) document.scripts[0].remove() ``` ``` a,a *{height:100vh;margin:auto;display:grid;transform:rotate(var(--))}b{border:9px solid#bcbbbb;border-top:0;width:60px;height:25px}b *{background:#f48024;width:44px;height:9px}d{--:10deg;margin:-15px 1px}e{--:15deg;margin:-17px 1px ``` ``` <a><b><c><d><e><e><d> ``` --- # HTML + CSS, 21 + 195 = 216 bytes This can be simplified considerably if we space the five stack items equally at 12.5 degrees: ``` a,b,s{height:100vh;margin:auto;display:grid}b{border:9px solid#bcbbbb;border-top:0;width:60px;height:25px}s{background:#f48024;width:44px;height:9px}s s{transform:rotate(12.5deg);margin:-16px 1px ``` ``` <a><b><s><s><s><s><s> ``` [Answer] # [PostScript](https://en.wikipedia.org/wiki/PostScript), 209 bytes Code (compressed version): ``` <</c{setrgbcolor}/r{rectfill}/s{gsave translate rotate 0 0 44 -9 r grestore}>>begin .74 .73 .73 c 0 0 78 34 r 1 1 1 c 9 9 60 25 r .96 .5 .14 c 0 17 26 s -10 19 46 s -25 27 66 s -40 40 84 s -50 55 97 s showpage ``` Code (uncompressed version): ``` % define some short-named procedures for later use << /c { setrgbcolor } /r { rectfill } /s { % operands on stack: angle x y gsave translate rotate 0 0 44 -9 r grestore } >> begin .74 .73 .73 c % gray 0 0 78 34 r 1 1 1 c % white 9 9 60 25 r .96 .5 .14 c % orange 0 17 26 s -10 19 46 s -25 27 66 s -40 40 84 s -50 55 97 s showpage ``` Result: [![screenshot](https://i.stack.imgur.com/3LJ9a.png)](https://i.stack.imgur.com/3LJ9a.png) [Answer] # [C (gcc)](https://gcc.gnu.org), ~~280~~ ~~278~~ ~~277~~ ~~275~~ ~~268~~ 265 bytes (Non-printables are in `hex`) ``` #define r(s...)printf(R"X(<rect x="%d" y="%d" transform="rotate(%d,%1$d,%2$d)" width="%d" height="9" fill="#%x"/>)X",s,63,90,34,c) c=0xbcbbbb,*p=L"`b4`P=\n3`13``19``1f``1b`(\r(2`00`7";main(){r(!r(9),88,!puts("<svg>"),78,c);for(r(78);*p;)r(*p++,*p++,*p++,44,0xf48024);puts("</svg>");} ``` [Try it online!](https://tio.run/##RY69TsNAEISpaakQBc4mlvaSxTG2hW1dLk9AgahSpHHOfycljrU@wAjxVjxBXsxYMhJTfNPMjEY/VFoPwzwvStMUDmPneZ5o2TS2xFfY4YYLbZ1egZuD8zmZ5azpyjOfFPDZZrZANyf3cTEiWOQCnA@T23rK1oWpaqsgBac0x6OCudvDeit2QB09hZT6FEakxbVWfn/Qh1G0bNUzXH5e1L4Jb27v73DPGFzFIE@ZaVB8Mc4YU0FJQrP2zXYIm@692oKgOBmn5HgNGeNEyGUrBeOyXa3oH1FEfl9GiR9EQv7119OA/B6GXw) * -2 bytes by using 180 degree rotation, using `*p++`, and reordering the LUT for GCC's reverse ordering. * -1 byte for blatant `for` loop optimization 🤦 * -2 bytes for abusing the return value of `printf` and `puts` for `0` * -7 bytes using C++-style raw literals thanks to p1131 * -3 bytes abusing vararg macros thanks again to p1131 ~~I beat Python, I feel somewhat accomplished.~~ Edit: said words now taste salty. With macros expanded and commented ``` // LUT is encoded as a raw wide string literal // expanded LUT[] = // Rot, y, x 180, 80, 61, // first is upside down to avoid an inconvenient null byte 10, 51, 19, 25, 31, 27, 40, 13, 40, 50, 0, 55, 0 // implicit null terminator }; c = 0xbcbbbb, *p = L"..."; main() { // Note that GCC evaluates function parameters // from right to left, so these are bottom line up 😖 printf( // GCC supports raw string literals in C mode // We use this to avoid \" R"X(<rect x="%d" y="%d" transform="rotate(%d,%1$d,%2$d)" width="%d" height="9" fill="#%x"/>)X", // !printf == 0 for non-empty strings // x = 0 // Called second !printf( "<rect ...>", 9, // x 63, // y 90, // rot 34, // width c // color ), 88, // y // Called first // rot = 0 !puts("<svg>"), 78, // width c, // Color // garbage arguments left in that printf doesn't use 63, 90, 34, c ); // Loop through our LUT for the 5 orange bars for ( // Typical printf optimization printf("<rect ...>", 78, 63, 90, 34, c); // loop until null terminator *p; ) // More eval order abuse printf( "<rect ...>", *p++, // x = p[2] *p++, // y = p[1] *p++, // rot = p[0] 44, // width 0xf48024, // color 63, 90, 34, c // garbage ); // Closing tag puts("</svg>"); } ``` **Ungolfed:** (different order, but clean) ``` #include <stdio.h> // Note that macro compression is used to save a few bytes. // Color constants static const int GRAY = 0xbcbbbb; static const int ORANGE = 0xf48024; // encoded raw as a string in the golfed code static const int LUT[] = { // x, y, rotation 17, 71, 0, 19, 51, 10, 27, 31, 25, 40, 13, 40, 55, 0, 50, 0 // null terminate }; // golfed version uses a macro static void rect( int x, int y, int width, int color, int rotation ) { // This could definitely be golfed better if I figure out the arithmetic for positioning printf("<rect " "x=\"%d\" " "y=\"%d\" " "width=\"%d\" " "height=\"9\" " "fill=\"#%x\" " // rotate at top left corner "transform=\"rotate(%d,%1$d,%2$d)\"" "/>", x, y, width, color, rotation); } int main(void) { // Print SVG header puts("<svg>"); // Loop through all 5 lines for (const int *ptr = LUT; *ptr != 0; ptr += 3) { rect(/*x*/ ptr[0], /*y*/ ptr[1], /*width*/ 44, /*color*/ ORANGE, /*rotation*/ ptr[2]); } // Output the box rect(/*x*/ 9, /*y*/ 63, /*width*/ 34, /*color*/ GRAY, /*rotation*/ 90); rect(/*x*/ 0, /*y*/ 88, /*width*/ 78, /*color*/ GRAY, /*rotation*/ 0); rect(/*x*/ 78, /*y*/ 63, /*width*/ 34, /*color*/ GRAY, /*rotation*/ 90); // Output closing SVG tag puts("</svg>"); } ``` This outputs the following SVG file to standard output when run (whitespace added to make it readable): ``` <svg> <rect x="9" y="63" transform="rotate(90,9,63)" width="34" height="9" fill="#bcbbbb"/> <rect x="0" y="88" transform="rotate(0,0,88)" width="78" height="9" fill="#bcbbbb"/> <rect x="78" y="63" transform="rotate(90,78,63)" width="34" height="9" fill="#bcbbbb"/> <rect x="61" y="80" transform="rotate(180,61,80)" width="44" height="9" fill="#f48024"/> <rect x="19" y="51" transform="rotate(10,19,51)" width="44" height="9" fill="#f48024"/> <rect x="27" y="31" transform="rotate(25,27,31)" width="44" height="9" fill="#f48024"/> <rect x="40" y="13" transform="rotate(40,40,13)" width="44" height="9" fill="#f48024"/> <rect x="55" y="0" transform="rotate(50,55,0)" width="44" height="9" fill="#f48024"/> </svg> ``` Stack snippet containing raw output: ``` <svg> <rect x="9" y="63" transform="rotate(90,9,63)" width="34" height="9" fill="#bcbbbb"/><rect x="0" y="88" transform="rotate(0,0,88)" width="78" height="9" fill="#bcbbbb"/><rect x="78" y="63" transform="rotate(90,78,63)" width="34" height="9" fill="#bcbbbb"/><rect x="61" y="80" transform="rotate(180,61,80)" width="44" height="9" fill="#f48024"/><rect x="19" y="51" transform="rotate(10,19,51)" width="44" height="9" fill="#f48024"/><rect x="27" y="31" transform="rotate(25,27,31)" width="44" height="9" fill="#f48024"/><rect x="40" y="13" transform="rotate(40,40,13)" width="44" height="9" fill="#f48024"/><rect x="55" y="0" transform="rotate(50,55,0)" width="44" height="9" fill="#f48024"/></svg> ``` --- # [C (gcc)](https://gcc.gnu.org), boring semi-cheating version, ~~236~~ 231 bytes ``` main(){puts(R"(<svg><path fill="#bcbbbb" d="M9 63v25H0V63zM0 88h78v9H0zm78-25v25h-9V63z"/><path fill="#f48024" d="M61 80H17v-9h44zM19 51l43 8-1 9-44-8zm8-20l40 19-4 8-40-19zm13-18l34 28-6 7-34-28zM55 0l28 34-7 5L48 6z"/></svg>)");} ``` [Try it online!](https://tio.run/##VY8xb8IwEIX/ysldkuHEnX22zwI6ZyBLh@6QCoLkICQgg6v@9tTQqbe990mf3g14GoZlmfbnS9N@Xx/3W/Nhms1tPr1vrvv7CMdzzlvzdhgO9Qx8bU2fILjZ@o4@gys9geoYdU4dlSkqWl/ZiOkJzeq/5ShKVv4sgUGp4zhjGkVKzwk8Z3GgyJBQBLVMVUdZCLgWFQghpzKxQ9bsBKxigIhO0GrpvQfKVqHGCH4nCuG1YPX8pjXt@mdZfgE "C (gcc) – Try It Online") -5 bytes for using raw string literals as well. This is literally just [SVGOMG](https://jakearchibald.github.io/svgomg/) on the lowest setting, so I don't take credit for it. I can't even tell what it is doing. It does have much lower precision, though. ``` <svg> <path fill="#bcbbbb" d="M9 63v25H0V63zM0 88h78v9H0zm78-25v25h-9V63z"/> <path fill="#f48024" d="M61 80H17v-9h44zM19 51l43 8-1 9-44-8zm8-20l40 19-4 8-40-19zm13-18l34 28-6 7-34-28zM55 0l28 34-7 5L48 6z"/> </svg> ``` ``` <svg><path fill="#bcbbbb" d="M9 63v25H0V63zM0 88h78v9H0zm78-25v25h-9V63z"/><path fill="#f48024" d="M61 80H17v-9h44zM19 51l43 8-1 9-44-8zm8-20l40 19-4 8-40-19zm13-18l34 28-6 7-34-28zM55 0l28 34-7 5L48 6z"/></svg> ``` [Answer] # HTML + JavaScript, 13 + 226 bytes = 239 bytes ``` with(c.getContext`2d`)(F=(x,y,r,f='#f48024',w=44,h=9)=>setTransform(translate(x,y),rotate(r),fillStyle=f,fillRect(0,0,w,h))||F)(0,63,0,'#bcbbbb',78,34)(9,63,0,'#fff',60,25)(17,71)(19,51,.175)(27,31,.436)(40,13,.698)(55,0,.873) ``` ``` <canvas id=c> ``` [Answer] # SVG, ~~240~~ 238 bytes Path data from the [official spritesheet](https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27), with some minor edits for golfing. ``` <svg><path fill=#BCBBBB d=M26,41v-9h4v13H0V32h4v9h22z /><path fill=#F48024 d=M23,34l.8-3-16.1-3.3L7,31l16,3zM9.2,23.2l15,7,1.4-3-15-7-1.4,3zm4.2-7.4L26,26.4l2.1-2.5-12.7-10.6-2.1,2.5zM21.5,8l-2.7,2,9.9,13.3,2.7-2L21.5,8zM7,38h16v-3H7v3z > ``` ]
[Question] [ The goal of this challenge is to extend the OEIS sequence [A334581](https://oeis.org/history/view?seq=A334581&v=5). > > Number of ways to choose \$3\$ points that form an equilateral triangle from the \$\binom{n+2}{3}\$ points in a regular tetrahedral grid of side length \$n\$. > > > The sequence begins `0, 0, 4, 24, 84, 224, 516, 1068, ...` # Example For example, if we take side lengths of \$n=4\$, as in the example below, there are \$\binom{4+2}{3} = 20\$ vertices and \$\binom{20}{3} = 1140\$ ways to choose three of them. Of these, there are \$84\$ ways to choose \$3\$ vertices that form an equilateral triangle: [![Animation showing the 84 triangles that live in a tetrahedron with four vertices.](https://i.stack.imgur.com/dhf87.gif)](https://i.stack.imgur.com/dhf87.gif) # Challenge This [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge will have you compute as many terms of the sequence `[A334581(0), A334581(1), ...]` that you can in ten minutes, as measured on my machine. [Answer] # [Rust](https://www.rust-lang.org/), \$A(1), \dotsc, A(1375)\$ in 10 minutes Unofficial score on Ryzen 7 1800X (8 cores/16 threads). Build with `cargo build --release` and run with `time target/release/tetrahedron n` to compute \$A(1), \dotsc, A(n)\$. This runs in \$O(n^4)\$ time. (So to estimate a good value of \$n\$ for your CPU, first time it for some smaller \$n\$, then multiply that \$n\$ by a factor of \$\left(\frac{600\,\mathrm{s}}{t}\right)^{1/4}\$.) ### How it works Any triangle that fits inside a tetrahedron of minimal side \$k \le n\$ may be translated inside a tetrahedron of side \$n\$ in exactly \$\binom{n - k + 3}{3}\$ ways. This means we only need to find it in one position, leaving six free parameters. Two of these parameters may be computed from the other four (up to a sign choice) if the triangle is to be equilateral, so we only need to loop over an \$O(n^4)\$ space. ### `src/main.rs` ``` use rayon::prelude::*; fn get_counts(n: i64, a0: i64) -> Vec<i64> { let mut c = vec![0; n as usize]; let a0a0 = a0 * a0; for a1 in if a0 == 0 { 1 } else { -n + 1 }..n { let d = a0a0 + a1 * a1; let m = n - a0.abs() - a1.abs(); for a2 in if m > 0 { -n + 2 - (m & 1)..n } else { -n - m + 2..n + m } .step_by(2) { let d = d + a2 * a2; let r = 2 * (a0a0 - d); if r == 0 { continue; } for b0 in a0..n { let pp = d * (3 * d - 4 * (a0a0 + b0 * (b0 - a0))); if pp < 0 { break; } let p = (pp as f64).sqrt() as i64; if p * p != pp { continue; } let q = 2 * a0 * b0 - d; let mut check = |p: i64| { let b1r = p * a2 + q * a1; if b1r % r != 0 { return; } let b1 = b1r / r; let b2r = -p * a1 + q * a2; if b2r % r != 0 { return; } let b2 = b2r / r; if (b0, b1, b2) <= (a0, a1, a2) || b0 + b1 + b2 & 1 != 0 { return; } let t = 0.max(a0 + a1 + a2).max(b0 + b1 + b2) + 0.max(-a0 - a1 + a2).max(-b0 - b1 + b2) + 0.max(-a0 + a1 - a2).max(-b0 + b1 - b2) + 0.max(a0 - a1 - a2).max(b0 - b1 - b2); if t >= 2 * n { return; } c[t as usize / 2] += 1; }; check(p); if p != 0 { check(-p); } } } } c } fn add_vec(c0: Vec<i64>, c1: Vec<i64>) -> Vec<i64> { c0.into_iter().zip(c1).map(|(x0, x1)| x0 + x1).collect() } fn main() { let n = std::env::args().skip(1).next().expect("missing argument"); let n = n.parse().expect("not an integer"); let counts = (0..n) .into_par_iter() .map(|a0| get_counts(n, a0)) .reduce(|| vec![0; n as usize], add_vec); let (mut d0, mut d1, mut d2, mut d3) = (0, 0, 0, 0); for (i, x) in (1..).zip(counts) { d3 += x; d2 += d3; d1 += d2; d0 += d1; println!("{} {}", i, d0); } } ``` ### `Cargo.toml` ``` [package] name = "tetrahedron" version = "0.1.0" authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"] edition = "2018" [dependencies] rayon = "1.3.0" ``` [Try it online!](https://tio.run/##tVZtb5swEP7eX3GttMleAgNS7UPS5GfsS1VVBJwMNTgUnCprw2/PnnOAQArVJq1WAvb57vzci@/Id4U5Hlea1so8RtudNoXQU0p@3I4p9OxEkrOgnyq6w3xBb1eEsVGG0p2hiOb0oqLre29GmsKCdkXyqh5mDVPohR548PiGx4m@2uYU@pRoSla8M5@TR2/kU0lqUyhMHU0jXruurg6s9cVWGYRGrAI6/VlnP8W@Jgc8brgshOSpf5qeGS2AoAKQ0oKPbzZ52PMDyIqUvpIvgaPZr0FeCjjQBCGGPKL0zN7M3MKo7HH5WwSyoXW11AbGbF3A1gWzdww5GHhPWDc4FMsuD0zKK5d26DyirTaJ3qmuRNlZsXOWHjsHPuz4v40iyyxOwJjgEQPHbYNpxPJYLD0bCCkvEFYooeKuFyWPZa7Cp/diZT8YYBFQh/xbIV/d4jk3CD2WSNn@s4Evo@s5g@gH0O@qYQzPVVhsplvL41kvo702v1T0BIFDZm/YYQADsy99DnhmkwGefb7I@Qu7mPsL4n89H/Qsj1yZXa77tZQfQAESPuE75bNhroABOxaxXyMOhhEHn4k4YMTBB4iBAHk6hln4B5Lu5pzEqH1Yh1gfDhzMEds@YnWoBp8D1QCp56bhXtTFjWuAtJQ2Ajl47qiSd2xZ6ChwbEL@kwYLwelosBicv9JQQ3DaNjiN/GAsDC1O10j/VwdH96ZpTsiF4IFGc@q5ReV7kr2qIhsoYR/lwknS6RMtB@rvaXZ6Rlfl1RUacxjHj2ixIkI3rrvwmCL/vOpr0JHnJtpsHxOjciHd1yQTkc@RyMRB7JHge18eaM9BxcyNtpuNilA0q0PTMNGooOdmr5GehYmnU6VfptMwX6OhusUT1EJaqz1EXbXPWMdNmhRFotcErl2qtLmRs44e7WZhXqiWhN4iPujG2qi1ytv8p08Sru/cjM6Jd7Ik9A6dD5exbTdnptV2E4ue75Nx7dXWSYILcwzP2LdfvYPqPZEWw5iqnzx/yogE3pTcMIXvupWvLSDZyox4wjm3P@dCHDAhnrQovqW0amXsWUorU7McTtroa3HzVtJbeTMmnB7XcEqE73g8@p73Bw "Rust – Try It Online") (Parallelism removed for TIO.) [Answer] # C++, all up to 40 in ten minutes Runs in \$O(n^9)\$ time complexity (fortunately, it seems to be divided by at least 36 and it's also multi-threaded). I tested on Ubuntu 19.10 on AMD Ryzen 5 2600 (12 threads), tested with `clang++ -Ofast -march=native -flto -no-pie -fopenmp` and ran with `timeout 600 ./a.out`. Code: ``` //#define _GLIBCXX_DEBUG #include <iostream> #include <cstring> #include <complex> #include <streambuf> #include <bitset> #include <cstdio> #include <vector> #include <algorithm> #include <cmath> #include <climits> #include <random> #include <set> #include <list> #include <map> #include <deque> #include <stack> #include <queue> #include <string> #include <iomanip> #include <unordered_set> #include <thread> struct pt3 { short x, y, z; bool operator < (const pt3& rhs) const { return std::tie(x, y, z) < std::tie(rhs.x, rhs.y, rhs.z); } pt3 operator - (const pt3& rhs) const { return {short(x - rhs.x), short(y - rhs.y), short(z - rhs.z)}; } int sqdist() const { return int(x)*int(x) + int(y)*int(y) + int(z)*int(z); } }; int solve(int n) { //the several lines below took a lot of tinkering-until-it-works std::set<pt3> pt3s; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) { if(i+j+k >= n) continue; pt3 pt { short(i+j), short(j+k), short(i+k) }; pt3s.insert(pt); } std::vector<pt3> points; //copy into a vector, they're much faster for this for(pt3 el : pt3s) points.push_back(el); //printf("n=%d, ps=%d\n", n, points.size()); int64_t ans = 0; #pragma omp parallel for schedule(guided) reduction(+:ans) for(int i = 0; i < points.size(); i++) for(int j = i + 1; j < points.size(); j++) for(int k = j + 1; k < points.size(); k++) { pt3 a = points[i], b = points[j], c = points[k]; //consider pairwise distances pt3 p1 = a-b, p2 = a-c, p3 = b-c; //33% of all time int d1 = p1.sqdist(), d2 = p2.sqdist(), d3 = p3.sqdist(); //another 33% of all time if(d1 != d2 || d1 != d3) continue; ans++; //printf("%d %d %d; %d %d %d; %d %d %d\n", p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z); } return ans; } int main() { for(int i = 1;; i++) { int ans = solve(i); printf("n=%d: %d\n", i, ans); } } ``` Output: ``` n=1: 0 n=2: 4 n=3: 24 n=4: 84 n=5: 224 n=6: 516 n=7: 1068 n=8: 2016 n=9: 3528 n=10: 5832 n=11: 9256 n=12: 14208 n=13: 21180 n=14: 30728 n=15: 43488 n=16: 60192 n=17: 81660 n=18: 108828 n=19: 142764 n=20: 184708 n=21: 236088 n=22: 298476 n=23: 373652 n=24: 463524 n=25: 570228 n=26: 696012 n=27: 843312 n=28: 1014720 n=29: 1213096 n=30: 1441512 n=31: 1703352 n=32: 2002196 n=33: 2341848 n=34: 2726400 n=35: 3160272 n=36: 3648180 n=37: 4195164 n=38: 4806496 n=39: 5487792 n=40: 6244992 ``` [Answer] # JavaScript (ES7), a(30) in ~50 seconds1 *1: when run locally on my laptop* A very simple algorithm. ``` function count(n) { const r0 = (8 / 3) ** 0.5, r1 = 2 / 3, r2 = 3 ** 0.5; let cnt = 0; for(let z1 = 0; z1 < n; z1++) for(let Z1 = z1 * r0, y1 = 0; y1 <= z1; y1++) for(let Y1 = (y1 - z1 * r1) * r2, x1 = 0; x1 <= y1; x1++) for(let X1 = 2 * x1 - y1, z2 = z1; z2 < n; z2++) for(let Z2 = z2 * r0, y2 = z2 > z1 ? 0 : y1; y2 <= z2; y2++) for(let Y2 = (y2 - z2 * r1) * r2, x2 = z2 > z1 || y2 > y1 ? 0 : x1 + 1; x2 <= y2; x2++) for(let X2 = 2 * x2 - y2, S1 = (X1 - X2) ** 2 + (Y1 - Y2) ** 2 + (Z1 - Z2) ** 2, z3 = z2; z3 < n; z3++) for(let Z3 = z3 * r0, y3 = z3 > z2 ? 0 : y2; y3 <= z3; y3++) for(let Y3 = (y3 - z3 * r1) * r2, x3 = z3 > z2 || y3 > y2 ? 0 : x2 + 1; x3 <= y3; x3++) { let X3 = 2 * x3 - y3, S2 = (X1 - X3) ** 2 + (Y1 - Y3) ** 2 + (Z1 - Z3) ** 2; if(Math.abs(S1 - S2) < 1e-9) { let S3 = (X2 - X3) ** 2 + (Y2 - Y3) ** 2 + (Z2 - Z3) ** 2; if(Math.abs(S1 - S3) < 1e-9) { cnt++; } } } return cnt; } ``` [Try it online!](https://tio.run/##dVTBbptAEL37K@YQKYuJXTOrSGlx3S/oiQv2KYTi1pW1VLCuTBx/uztv2VUwbiyZHd7MvjfzYPld/C3astn9sTNT/6gu94e2otY2u9Lep5ftwZR2Vxsq64OxykR0mpDcmNZSs6CvpJ7oE@mIplNazB8fqEkEZGASs8Tap1LZt68slcYKukgncr@tGwXsNXEQ1iUZrHEcDfIb5CU5Fc0HwcOv8/tkXaIA0fXONSqU5Gd@fxLhykOWo2c5OpYuQXTNkvdDTVEyk4rh7lemXlqCvnkeNe8K@LZ5j6/Q2Tda0BenLTBmYUSjWdjNwpiFP5plSPr2BrYV7On5pf2YMJ/T6BjRaFIOk0Kmu@LOnJc5LMjZPXEWOrUGsB4AGwAbD1xZpamfTILeKj2yyhXoW6s8vsJo3ioYpJ1VGtHIKu2s0rBKf2TVkBRWIewC/5G9VU6j04hEw73@/Yuc62AVZDr9zp3xu1F6bJQeG@UBdyCIdlv1vbC/5sVLqzLkMzFySUk1@xzEe/nMjZjzWITHInwr8j8ZfStDOKxxnPrb8yRc8W8qe2gMKtLJ@RKMN9KUuGZgGsuZMsEzfDLqfTXf1z/Vc6HuTuYcSe3dKXxYzs@R8PwD "JavaScript (Node.js) – Try It Online") ]
[Question] [ The (slightly harder, but still easy) sequel of [Generate input for this hardware](https://codegolf.stackexchange.com/q/195009/78410). ## Background I have a hardware that has a 32-bit input register. The register has the following characteristics: * The 32-bit register consists of eight 4-bit fields. * Each 4-bit field holds a value in **signed-magnitude**; it can hold an integer between -7 and +7 inclusive, including -0 and +0 (signed zeroes). For example, the hexadecimal value `0xABCD1234` represents the field values `[-2, -3, -4, -5, +1, +2, +3, +4]`. In fact, one hex digit represents one 4-bit value with the following mapping: ``` Hex | Input value --------------------- 0 ~ 7 | +0 ~ +7 8 ~ F | -0 ~ -7 ``` In order to correctly operate this hardware, the 8 field values must be strictly increasing from left (most significant) to right (least significant). For signed zeros, `-0` is considered to be less than `+0`. The following are the examples of valid inputs: ``` field values for 8 fields => 32-bit register value [-7, -6, -5, -4, -3, -2, -1, -0] => 0xFEDCBA98 [+0, +1, +2, +3, +4, +5, +6, +7] => 0x01234567 [-7, -4, -3, -2, -0, +1, +3, +4] => 0xFCBA8134 [-2, -1, -0, +0, +3, +4, +5, +7] => 0xA9803457 ``` The following are the examples of invalid ones: ``` field values for 8 fields => 32-bit register value [+7, +6, +5, +4, +3, +2, +1, +0] => 0x76543210 // not increasing [-2, -1, -0, -0, +1, +2, +3, +4] => 0xA9881234 // not strictly increasing, due to duplicates [-3, -2, -1, +0, -0, +1, +2, +3] => 0xBA908123 // +0 is greater than -0 ``` ## Task Given the **register value**, determine if it is a valid input to the hardware. ## Input and output The input (the register value) is an unsigned 32-bit integer. You can take it as an integer, a string, or a list of digits. A string or list of digits can be in base 2, 8, 10 or 16, least-significant-digit-first or most-significant-digit-first, with or without leading zeros or base prefixes. For example, if an input value is `0x01234567`, possible representations in base 16 include `"0x01234567"`, `"01234567"`, `"1234567"`, `"76543210"` (reversed order of digits), `[0, 1, 2, 3, 4, 5, 6, 7]`, `[7, 6, 5, 4, 3, 2, 1, 0]`. The output is a boolean, indicating whether the given input is valid or not. You can choose to output either: * Any of the truthy/falsy values as defined by the language of your choice + The actual result values may differ between inputs (e.g. output 1 for a truthy input and 2 for another truthy one). + Swapping truthy and falsy values is not allowed. * Any two distinct constant values for true/false respectively + In this case, the result values should exactly be one of the two constant values. ## Scoring The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ### Expected output: Valid ``` 0xFEDCBA98 0xEDCBA980 0x80123456 0x01234567 0xFCB98037 0xEDB12345 ``` ### Expected output: Invalid ``` 0x76543210 0x1A2B3C4D 0x12345678 0xBA988123 0xBA908123 0x00123456 0xB9882347 0xDC914556 ``` [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` lambda s:eval("'EDCBA9801234567'.find(%r)<"*8%s+'s') ``` [Try it online!](https://tio.run/##RY1bC4IwGIbv/RVDELeC2KbzRF54yD9REYaKgpk4Tfv1tnmgu@c7vM/bfvvy3dC58G9znb6eWQq4l3/SGqr6JY7CwHUwoYbJLFs/FVWTQa1DZ/XgaPyocx3NY1nVOSCeArjfD22dwy4dH1XTDj1EV@rdkQLarmp6UECOZjwlm1bB014gcG8RuPcJTKJQnA17@Q2XvUDbYqZBiYyRgIZGZMYS15T0Sqkj5hXxhvhfIayOYOmNI5eYjFk/ "Python 2 – Try It Online") Takes input as a tuple like `('F', 'E', 'D', 'C', 'B', 'A', '9', '8')`. The idea is to produce out and evaluate a long chain of inequalities like: ``` 'EDCBA9801234567'.find('F')<'EDCBA9801234567'.find('E')<'EDCBA9801234567'.find('D')<'EDCBA9801234567'.find('C')<'EDCBA9801234567'.find('B')<'EDCBA9801234567'.find('A')<'EDCBA9801234567'.find('9')<'EDCBA9801234567'.find('8')<s ``` The `s` at the end of the chain takes care of the extra trailing `<` symbol by giving an always-true comparison of "number < string" in Python 2 logic. [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, 36 bytes Outputs `1` if valid, `nil` if not. ``` p~/xF?E?D?C?B?A?9?8?#{[*0..7]*??}?$/ ``` [Try it online!](https://tio.run/##Rc25DoJAEAbg3tfQikSYvZdqsge8hLGxswGCmmCMPrrrLGxi9831z/y4PFOaPs3SY4cRA3p02KLF/etUQV2bc4X4xkOTEix9F4N3rd3BUgREC4wLqTSxyBD74GkszLrr1z7RaCUFZ/mMOe5FkDFzu8q5OdRSvREK4f@CUi0558bQMqmU/o7T/ToOt3Qcfg "Ruby – Try It Online") [Answer] # [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 91 bytes ``` [for i:char in n->"EDCBA9801234567".IndexOf(i)]|>List.pairwise|>List.forall(fun(x,y)->x<y) ``` [Try it online!](https://tio.run/##pZLPa4MwFMfv/hXBk8IUf1Y7qlC1hUFhZTvsUHoI7bML2KQk6aaw/92ltu5U2MhyCXnJ533fe9/UwtkxDj07AUWvnZBwNIwGJDogmvVoUzOOyOPuHauNIurk5qIqi/k09fwgjOJJYrpPdA/tc20Re/uVr4iQ7gkT/kkE3I4qB24aqz5Tq33obCdvZ53db2YLKnm3ZoTKfDtoHrHSwPzwgTIDqXWJcRDnRqJMFWQub9rmcFsyKlgD7hsnElaEgnV9a99lx7J12LFZHfZnThrssixUxWGi128xKP/G3oWTSRyFga81LH8eFGEZVVrsdVZaBl/cTVUCTdbTZb1/fA5lb6pgLYOrcupH8d90x9sXwHvrGvL6bw "F# (.NET Core) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` N>¡€7I>0Ạ ``` [Try it online!](https://tio.run/##y0rNyan8/9/P7tDCR01rzD3tDB7uWvD/6KSHO2dYP2qYo6Brp/CoYa714Xauw@1ABZH//0dzRRua6igYmgCxMRAbAbEhEBvoKFjqKFjE6gDlccjpKBiApEE0UFBHASgNVAVUDDTPDCSDRVhHwRxspCnCOKhRYFXmKPYZoukHSZqDDTEFCxiDJQ2h7oC6DGoq1L1go6Cy6A6BeQ/FSxZwO9HkDNDlDHD6G@ErCyRZiN@g7rIE64ToAWvjigUA "Jelly – Try It Online") A monadic link taking a list of bass 16 digits and returning 1 for true and 0 for false. ## Explanation ``` ¡€ | For each digit, if: > 7 | - Greater than 7 | Then: N | - Negate I | Increments between each digit >0 | Greater than 0 Ạ | All ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~25~~ 24 bytes ``` {[>] ((8 X>$_)X*7)Z+^$_} ``` [Try it online!](https://tio.run/##NYzRCoIwFIbvz1PsImIrks3pNqEGbuYzSFGioVeJolcSPfuaYlf/d/7z8w3N@Baum9G@RRf3uesHwlihQu9KUhwkuR2fu/LrpmpGLQ5efVdrHQzVODWnupoazAQhqO1HdIb8mlmTJgq2pKAoC3kUC9hSQm6Nf3DpN2btQIo44iGjwNLQcBtlsG0VLBLlrwXoCvQv9BblSUJmExbFvtHuBw "Perl 6 – Try It Online") Takes a list of integers. ### Explanation ``` { } # Anonymous block ( )Z+^$_ # XOR input values with (8 X>$_)X*7 # 7 if value < 8, reversing sort order # 0 otherwise, keeping value unchanged [>] # All values strictly decreasing? ``` [Answer] # [PHP](https://php.net/) (7.4), 54 bytes ``` fn($a)=>preg_match(_.join('.*',$a)._,FEDCBA9801234567) ``` [Try it online!](https://tio.run/##TY7djoIwEIXv@xQTQ9J2Qwi/glE0AvoSuiGEwNaNQkN7Z3x2bItNnKtvZs45M5zxeXfgjCPk9PncD8RpaL7nU/dXPxrZMlJ7/@NtINj7wa7aebV7PlVlcdxkfhBGcbJO6bxVbtkJKSCHC8JWgF2ErVazdWi2Zs3nslCKKF30hdloTtdJHIWB8QbHsIjKuDK8WE2@Ds/U4MO@Zf/rlkrPVGPyq3ITxImZ/6q3@3HqmpYB@fzfCDBE4YlAVdeyEZyeCDnVgt9vchFSCh6srsNqi17zGw "PHP – Try It Online") Input is array of digits in base 16 (example: `['F','E','D','C','B','A','9','8']`); [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` Σ•_ćúθœιu0•hSk}ÙQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3OJHDYvij7Qf3nVux9HJ53aWGgD5GcHZtYdnBv7/H61kqKSjoOQIIoxAhBOIMAYRziDCBES4KMUCAA "05AB1E – Try It Online") Explanation: ``` Σ } # Sort by k # the index of each char of the input in... •_ćúθœιu0•hS # [7...0,9,8,A...F] Ù # remove duplicates Q # and check that it's not changed ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` H8(вÆü‹P ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fw0LjwqbDbYf3PGrYGfD/f7SSm5KOgpIriHABEc4gwglEOIIISxBhoRQLAA) or [validate all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkXxn838NC48Kmw22H9zxq2BnwX@e/m6uLs5OjpQUXlDbgsjAwNDI2MTXjgtLmXG7OTkAJY3OgGiewGJe5mamJsZGhAZeho5GTsbOJCxdUrQUXyBALIA/EMAAzDGAGAk2xALLMuVycLQ1NTE3NAA "05AB1E – Try It Online"). Input is a list of hex digits. Output is 1 for truthy, 0 for falsy. ``` H # convert from hex 8(в # convert to base -8 Æ # reduce by subtraction ü‹ # pairwise less-than P # product ``` ]
[Question] [ At a party, I was introduced to the game LCR. Now it's not a great game as there's no skill but only random chance. But it got me thinking, I could code this, and I made a quick program in R to model the game. Rules of the game modified from Wikipedia to match how we played: > > Each player receives at least 3 chips. Players take it in turn to roll > three six-sided dice, each of which is marked with "L", "C", "R" on > one side, and a single dot on the three remaining sides. For each "L" > or "R" thrown, the player must pass one chip to the player to their > left or right, respectively. A "C" indicates a chip to the center > (pot). A dot has no effect. > > > If a player has fewer than three chips left, they are still in the > game but their number of chips is the number of dice they roll on > their turn, rather than rolling all three. When a player has zero > chips, they pass the dice on their turn, but may receive chips from > others and take their next turn accordingly. The winner is the last > player to put chips into the center. > > > Contest: write a program in your language of choice that takes input for the number of players and the number of starting chips and simulates a game of LCR, showing the state of the game after each player has rolled. For example, a game might be output as: ``` [[[3,3,3,3],0],[[1,4,3,4],0],[[1,4,3,4],0],[[1,4,1,4],2],[[1,4,1,2],4], [[0,4,1,3],4],[[0,3,2,3],4],[[0,3,0,3],6],[[0,3,1,1],7],[[0,3,1,1],7], [[2,0,1,1],8],[[2,0,0,1],9],[[2,0,0,0],10],[[0,1,0,0],11], [[1,0,0,0],11],[[1,0,0,0],11],[[1,0,0,0],11],[[0,0,0,0],12]] ``` ht: JonathanAllan The output doesn't have to look exactly like this, but it should be easy to discern the dice roll, how many chips each player has, and how many chips the centre has for each turn. It's code golf so the shortest code wins. [Answer] # [Emacs Lisp](https://www.gnu.org/software/emacs/), 279 bytes ``` (defmacro n(i)`(incf(nth ,i c))) (defun f(p s)(g(let((a'(0)))(dotimes(i p)(push s a))(princ a))0 p)) (defun g(c v p)(dotimes(i(min(nth v c)3))(decf(nth v c))(case(random 6)(0(n(mod(1- v)p)))(1(n(mod(1+ v)p)))(2(n p))(t(n v))))(princ c)(or(eq(-sum c)(nth p c))(g c(mod(1+ v)p)p))) ``` Use this function as `(f 4 3)`. Better readable version: ``` (defmacro n (i) `(incf (nth ,i c))) (defun f(p s) (g (let ((a '(0))) (dotimes (i p) (push s a)) (princ a)) 0 p)) (defun g (c v p) (dotimes (i (min (nth v c) 3)) (decf (nth v c)) (case (random 6) (0 (n (mod (1- v) p))) (1 (n (mod (1+ v) p))) (2 (n p)) (t (n v)))) (princ c) (or (eq (-sum c) (nth p c)) (g c (mod (1+ v) p) p))) ``` Output example: ``` (3 3 3 3 0)(1 4 3 4 0)(2 2 4 4 0)(2 2 2 5 1)(4 2 2 3 1)(2 2 2 4 2)(2 1 3 4 2)(2 2 0 4 4)(2 2 0 4 4)(1 2 0 4 5)(2 1 0 4 5)(2 1 0 4 5)(2 1 1 3 5)(0 1 1 3 7)(1 0 1 3 7)(1 0 1 3 7)(1 0 3 1 7)(1 0 3 1 7)(1 0 3 1 7)(1 1 2 1 7)(1 1 3 0 7)(0 1 3 0 8)(1 0 3 0 8)(1 1 1 1 8)(1 1 2 0 8)(0 1 2 1 8)(0 1 2 1 8)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 0 10)(0 1 1 0 10)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 0 0 12) ``` [Answer] # Java 8, ~~281~~ ~~277~~ ~~275~~ ~~274~~ 253 bytes **Version which outputs the same state when a turn player has 0 chips left:** ``` p->n->{java.util.Arrays A=null;int c[]=new int[p],i=0,t,r,s=1,u,f=9;for(A.fill(c,n);s>0;f=0,System.out.print(A.toString(c)))for(t=c[++i%p],t=t>3?3:t;t-->f;r*=Math.random(),c[i%p]-=1-r/3,s=c[u=(i+r-1+p)%p]+=1-r&1-r/4,c[u]=s<0?0:s,s=A.stream(c).sum())r=6;} ``` Starts with the third player in the array. [Try it online.](https://tio.run/##bZBBS8MwGIbv@xW5KIlNY8eG4LJ0FEHwsJPH0kPM2pnZpiX5Mhlj/vX6FSdevL3wPm@@8Bz0UaeH3cdoWh0C2WrrzjNCAmiwhhywFRFsK5roDNjeiedrWL84qPe15/9BT70Lsav9L5TnpCFqHNLcpfn5b1B4r0@BFMrFtpXWATFlpVz9STCXQ8Wtyjhwz4Oa88gb9Sib3tNCNLZtqeGOyZBnskHq9RSg7kQfQQwe1whB/woY99QwxqYdKFMmib3Bh0FBvtgsViAhTfNG@ju11fAuvHa7vqOMm3LiUjVP/f0C75syKmoTn86TgWGTqC9/O5VLRGOlwjrbZKuAZCEC@Fp3eFagBcqYVw/yMsoZih3iW4tir36Pvd2RDp3Tn5@WFdFs8k9II/QwtCe6ZEIbUw9AF0xic5ldxm8) **Version which skips players with 0 chips left (274 bytes):** ``` p->n->{java.util.Arrays A=null;int c[]=new int[p],i=p,t,r,s=1,u,f=9;for(A.fill(c,n);s>0;f=0,System.out.print(A.toString(c))){for(t=c[i%p],t=t>3?3:t;t-->f;r*=Math.random(),c[i%p]-=1-r/3,s=c[u=(i+r-1+p)%p]+=1-r&1-r/4,c[u]=s<0?0:s)r=6;for(s=A.stream(c).sum();s>0&c[++i%p]<1;);}} ``` Starts at the first player in the array. [Try it online.](https://tio.run/##bVHBagIxFLz7FblUkm42dVEKNWZFCoUePHlc9pDGjY3dzYbkxSJif91mq6WX3gZm5r1hZi8PMt9vPy6qlSGgtTT2NEIogASj0D6xLIJpmY5Wgekte7mBxauFZtd4@p/oubchdo3/FZUl0khcXF7avDz9GVbey2NAK2Fj23JjAamqFrb5RAlXrqZGOArU0yAKGqkWT1z3Hq@YNm2LFbWEh3LCtZjQzTFA07E@AnM@uZMI@g0kuMOKEHIajCBUZe7SXRBQTpfTOXDI81Jzfy/WEt6Zl3bbd5jQqy4XRe4fpum9qqLAJvN5kTmSmEx8@fFAzpI01iIsJsvJPBAvHn8iBrFiAXwju/SdpTLwT9SxqrJsuLwoOOHn84WPUtsuvrWp7Vvph95sUZeGwNf4VY0kGUZBSDPpXHvEM8KkUo0DPCU8MefR@fIN) -7 bytes thanks to *@OlivierGrégoire*. **Explanation (of the second version):** ``` p->n->{ // Method with two integer parameters and no return-type java.util.Arrays A=null; // Create a static Arrays-object to save bytes int c[]=new int[p], // Integer-array with chips of each player (0 by default) i=p, // Index integer, starting at the amount of players t, // Temp integer to roll 3 dice r, // Temp integer for the dice-result s=1,u, // Temp integers (and `s` is also the total-sum integer) f=9; // Flag integer, starting at a single digit above 3 for(A.fill(c,n); // Give each player in the array the chips s>0 // Loop as long as the total-sum is not 0 yet ; // After every iteration: f=0, // Set the flag to 0 System.out.print(A.toString(c))){ // Print the current state for(t=c[i%p], // Set `t` to the current player's chips t=t>3?3:t; // If this is larger than 3: set it to 3 instead t-->f // Loop that many times (1, 2, or 3) // (the flag is used to skip this loop the first iteration, // so we can print the initial state) ; // After every iteration: r*=Math.random(), // Roll the dice in the range [0,5] c[i%p]-=r<3? // If the dice-roll is 0, 1 or 2: 1 // Remove a chip from this player :0, // Else: Leave the chip-amount the same s=c[u=(i+r-1+p)%p] // If the dice-roll is 0, go to the player left // If the dice-roll is 2, go to the player right +=1-r&1-r/4, // And add a chip to this player c[u]=s<0?0:s) // Change negative amount of chips to 0 r=6; // Reset the dice-roll to 6 so we can roll again for(s=A.stream(c).sum(); // Calculate the total sum of the chips of the players s>0& // If this sum is larger than 0: c[++i%p]<1;);}} // Determine the next player in line with at least 1 chip ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~159~~ 148 bytes ``` from random import* n,c=input() g=[c]*n;i=0 while sum(g):exec"r=randrange(6);g[i]-=1;g[i-[0,1,~-n][max(0,r-3)]]+=r>0;"*min(3,g[i]);i=(i+1)%n;print g ``` [Try it online!](https://tio.run/##FYzBCoMwEAXvfoUIhUQTiLX00JD@SMhBbBoXmjVsI7WX/nqqh2Eu81765nnBcylPWmJNIz52QUwL5bZCMRnAtGbGq2Ds5FrUYFT1meHl6/caWeA3v/mpIXNMd4JnV66DBSdNf1haJXrxk@hsHDemBMmBO9cZuivdtBGQDeLo@X7NoOv5CXUiwFyHUi5i@AM "Python 2 – Try It Online") Prints all players chips after every roll [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) +2 to fix repetition behaviour (`¡` must be preceded by a nilad so `«3Ḣ$` -> `⁸FḢ«3`) If we can define the output lists to be rotated to have the chips belonging to the player who acted previously at the left we can do away with the right-most 6 bytes for **33 bytes** (however, in my opinion, it is somewhat awkward to read that). ``` ẋµ’1¦‘.,2ŻX¤¦$¹Ø.X¤?⁸FḢ«3¤¡ṙ1µSпṙ"JC$$ ``` A dyadic Link accepting chips-per-player on the left and number-of-players on the right which yields a list of players chip counts as at the start of the game and after each turn (including turns where 0 chips forces a pass). **[Try it online!](https://tio.run/##y0rNyan8///hru5DWx81zDQ8tOxRwww9HaOjuyMOLTm0TOXQzsMz9IBM@0eNO9we7lh0aLUxUHzhw51ApVuDD084tB/IVPJyVlH5//@/8X8TAA "Jelly – Try It Online")** ### How? Each player in turn, up to three times, depending on their chip count, flips a coin. When a player flips heads they do nothing but if they flip tails they then roll a three sided die losing a chip to L, C or R. (Note that 0 flips when a player has 0 chips is equivalent to passing.) This is repeated until the sum of the players chips is 0. The implementation rotates the players left by one place each turn and then rotates the resulting states back to all be aligned as if they were not. ``` ẋµ’1¦‘.,2ŻX¤¦$¹Ø.X¤?⁸«3Ḣ¤¡ṙ1µSпṙ"JC$$ - Link: chipsPerPlayer, C; numberOfPlayers, P ẋ - repeat C P times (making a list of P Cs) п - collect up results in a list while... S - ...п condition: sum (while players have chips) µ µ - ...п do: the monadic chain: ¡ - repeat... ¤ - ...¡ number of times: nilad and link(s) as a nilad: ⁸ - chain's left argument (the chip list) «3 - minimum with three (vectorises) Ḣ - head -- i.e. min(left-most player's chips, 3) ? - ...¡ action: if... ¤ - ...? clause: nilad and link(s) as a nilad: Ø. - the list [0,1] X - random choice (0 is falsey while 1 is truthy) $ - ...? then: last two links as a monad: ¦ - sparsely apply... 1 - ...¦ to indices: one (the left-most) ’ - ...¦ action: decrement (player lost a chip) ¦ - sparsely apply... ¤ - ...¦ to indices: nilad and link(s) as a nilad: .,2 - literal pair of literals .5 and two = [.5,2] Ż - prepend a zero = [0,0.5,2] X - random choice - -- Note application to index .5 is a no-op - index 0 is the right-most entry (L) - index 2 is the second entry (R) ṙ1 - rotate the list left by one for the next п loop $ - last two links as a monad: $ - last two links as a monad: J - range of length -- i.e. [1,2,3,...,turns+1] C - complement = 1-x [0,-1,-2,...,-turns] " - zipped-appliction of: ṙ - rotate left by - -- i.e. rotate 1st left by 0, 2nd left by -1, ...) ``` [Answer] # C#, 356?+13? Bytes Requires `using System;` for a total of +13 bytes to the code shown below, if I'm required to count that. Otherwise just plonk it in any class and call `L(players, starting chips);`. ``` static int i,j,k,l;public static void L(int p,int s){var r=new Random();var x=new int[p];for(i=0;i<p;i++)x[i]=s; for(i=0;i<s*p;){for(j=0;j<p;j++){for(l=0;l<x[j]&l<3;l++){k=r.Next(-1,5);if(k<2){if(k==0){x[j]--;i++;}else{x[(p+j+k)%p]++;x[j]--;}}}Console.Write(a(x)+i);}}}public static string a(int[] x){var n="|";for(l=0;l<x.Length;)n+=x[l++]+" "; return n;} ``` Sample output for a 2,2 game: ``` |1 3 0|2 2 0|1 3 0|1 3 0|0 4 0|0 3 1|0 3 1|2 1 1|1 2 1|1 2 1|0 3 1|0 3 1|0 3 1|1 1 2|1 1 2|1 1 2|0 2 2|1 1 2|0 1 3|1 0 3|0 1 3|0 1 3|0 1 3|1 0 3|1 0 3|1 0 3|0 1 3|1 0 3|0 1 3|0 0 4 ``` Less golfed version: ``` using System; //class omitted. static int i,j,k,l; public static void LCR(int pl, int sc){ var r=new Random(); var state = new int[pl]; for(i=0;i<pl;i++)state[i]=sc; for(i=0;i<sc*pl;){ for(j=0;j<pl;j++){ for(l=0;l<state[j] && l<3;l++){ k=r.Next(-1,5); if(k<2){ if(k==0){state[j]--;i++;}else{state[(pl+j+k)%pl]++;state[j]--;} } } Console.Write(a(state)+i); } } } public static string a(int[] x){ var n="|"; for(l=0;l<x.Length;)n+=x[l++]+" "; return n; } ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~201~~ 199 bytes ``` n=>m=>{var r=new Random();var j=Enumerable.Repeat(n,m).ToList();for(int i=0;j.Any(c=>c>0);i++,Print(j))for(int k=0,x=r.Next(6);k++<Math.Min(j[i%m],3);j[((x<1?-1:1)+i+m)%m]+=x<2?1:0,j[i%m]-=x<3?1:0);} ``` [Try it online!](https://tio.run/##VY4xT8MwEIX3/oouqHeyayUUMdRxqgxlalFV2CoG416Ek9ipHBeCEL89JEIMbO@79@n0TLc0nR0ert5k1kdemGhbP8U8L9XgVe5U/vWuwzwoTx/zo/bn1gHK6VSprb86Cvq1IXGkC@kInjsUz@3OdnG0yjbA@GtuVSIrUfhPMCo3eYLSMsYPYeygQvzTapXwXgXxSH2Ee5Q1Y9lexzextx6qk71xL3yFsjoB9Fm6WabrFJllDseCqT673aTrhP@Ky5FXE6P8HuRs2lurI@nzznoCFE@XxkZY8MUYqSETpwXioENHKGcl1GLbkCMfiwgJ4j9OEeWw4nc/ "C# (Visual C# Interactive Compiler) – Try It Online") ``` startingChips=>playerNum=>{ //Instantiate a new random number generator var rng = new Random(); //Create a list of chips var players = Enumerable.Repeat(startingChips, playerNum ).ToList(); //Loop as long any player still has chips for(int turnNum = 0;players.Any(c=>c>0); //And print the result every iteration i++,Print(j)) //Get a random number within the range of 0-5 and loop for... for(int k = 0,randomNum = rng.Next(6); //either 3 or the amount of chips we have, whichever is smaller k++<Math.Min(players[turnNum % playerNum ],3); //Increment either the right player if the random number is 1, else increment the right player if it is 0 players[((randomNum<1?-1:1)+ turnNum + playerNum ) % playerNum ]+=x<2?1:0, //Decrement current player if the die roll is under 3 players[ turnNum % playerNum ]-=x<3?1:0);} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes ``` ≔⁰ηWΣθ«≔Eθ⭆⌊⟦κ׳⁼λη⟧‽⁶ιUMθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5LΦ§ιλ›μ2≔﹪⊕ηLθη⟦⪫θ, ``` [Try it online!](https://tio.run/##ZZBLS8QwEIDP7a8IPU0gglj00tOyPlhxYXG9lR5CG5pgHjYPFcTfHieLsgUTSJjJly@ZGSX3o@M6500IarZwyYikXf0hlRYEjsnAQin5qqvf8z1/g4WRY/TKziXYK6sMYv0rIy/KiAAtI3dL4jqALjI6UEaeuZ2cgRtKMVD4QIV3t84YzBcfWlKAg/5bULZ1yUbYxJ2dxCcoRnZ29MIIG8UEuniatinbP/BWrEHkrk/ck7BzlHCvdBR@zRfmwQte0gbxK8RxdOei3ZS0g/UH5Fm4FHlpWnXApkToH52ypaiGNVh8V3/n3PctO81hyBfv@gc "Charcoal – Try It Online") Link is to verbose version of code. Alternates between outputting the dice rolls and chips left (neither the initial number of chips nor the number of chips in the centre are included in the output). Explanation: ``` ≔⁰η ``` Start with the first player. ``` WΣθ« ``` Repeat until nobody has any chips left. ``` ≔Eθ⭆⌊⟦κ׳⁼λη⟧‽⁶ι ``` Roll up to three dice for the current player. These dice are labelled 0-5, where 0-2 represent the dot, 3 is pass to left, 4 is to centre, 5 is to right. ``` UMθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5LΦ§ιλ›μ2 ``` Add the number of chips the player on the right passed left and the number of chips the player on the left passed right, but subtract the number of chips the player themselves passed on. ``` ≔﹪⊕ηLθη ``` Advance to the next player. ``` ⟦⪫θ, ``` Output the the new numbers of chips held by the players. It's actually simpler for everyone to roll their dice simultaneously, which can be done in 50 bytes, including printing the dice rolls as well as the chips left: ``` WΣθ«≔Eθ⭆⌊⟦κ³⟧‽⁶ιUMθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5LΦ§ιλ›μ2⟦⪫ι,⪫θ, ``` [Try it online!](https://tio.run/##Zc/BSsQwEAbg8@5ThJ4mEC8WvXhaVpQVFxb3WHoI7dAOJhObpiqIzx4nFWHBBBL@4Zsh6UYbu2Bdzh8jOVRwXjxMWquv7WY3zzQwHO0bTEadUyQeSjgSkxfWvBpVt9qoF8t98HCrtQTSd9uNsH3wXuqlVRqWGU7u75C@fVg4wS4duMdPIKMO3EX0yAl7cGVOVVfl@gfv8RKKu1ndM/KQRngglzBe@mIeI9pS9sKvhcuSR57kQwmap0BcYGUqoWuaflMr6jvnpqnNuts2X727Hw "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~58~~ ~~50~~ ~~49~~ ~~52~~ 49 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) **Version which outputs the same state when a turn player has 0 chips left (~~50~~ ~~49~~ ~~52~~ 49 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` и[=ÐO_#¾è3‚Ws\F5ÝΩ©3‹iε¾¹%NQ-}®≠iε®<¾+¹%NQ+}}}}D0›*¼ ``` [Try it online.](https://tio.run/##yy9OTMpM/f//wo5o28MT/OOVD@07vML4UcOsw/PdTA/PPbfy0Eogb2fmua2H9h3aqeoXqFt7aN2jzgUggXU2h/ZpgwW1a4HAJUXr0J7//024jP/r6ubl6@YkVlUCAA) **Version which skips players with 0 chips left (~~58~~ ~~57~~ ~~60~~ 57 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):** ``` и[=DO_#[D¾èDĀ#\¼}3‚Ws\F5ÝΩ©3‹iε¾¹%NQ-}®≠iε®<¾+¹%NQ+}}}}D0›*¼ ``` [Try it online.](https://tio.run/##yy9OTMpM/f//wo5oWxf/eOVol0P7Dq9wOdKgHHNoT63xo4ZZh@e7mR6ee27loZVA3s7Mc1sP7Tu0U9UvULf20LpHnQtAAutsDu3TBgtq1wKBS4rWoT3//5twGf/X1c3L181JrKoEAA) The first input is the amount of players, second input the amount of chips per player. **Explanation (of the second version):** ``` и # Create a list with a size of the (first) implicit input, # filled with the second (implicit) input [ # Start an infinite loop: = # Print the list with trailing newline, without popping the list DO_# # If the total amount of chips is 0: stop the infinite loop [ # Start an inner infinite loop: D¾è # Get the chips of the I'th player (I is 0 by default) D # Duplicate this Ā# # If it is NOT 0: stop the inner infinite loop \ # Remove the duplicated chips for the next iteration ¼ # And increase I by 1 } # After the inner infinite loop: 3‚ß # If the amount of chips is larger than 3: use 3 instead F # Loop that many times: 5ÝΩ # Roll a random dice in the range [0,5] ©3‹i # If the dice-roll is 0, 1, or 2: ε¾¹%NQ-} # Remove a chip from the I'th player ®≠i # If the dice-roll is NOT 1: ε®<¾+ # Go to the player left if 0; or right if 2 ¹%NQ+} # And increase that player's chips by 1 }}} # Close both if-statements and the loop Dd* # Make any negative amount of chips 0 ¼ # Increase I by 1 ``` ]
[Question] [ [Topically related.](https://codegolf.stackexchange.com/q/168683/31957) **Objective:** Given a matrix of positive integers \$M\$, output the smallest [centrosymmetric matrix](https://en.wikipedia.org/wiki/Centrosymmetric_matrix) which contains \$M\$ (this matrix may contain non-positive integers as well). A centrosymmetric matrix is a square matrix with rotational symmetry of order 2—i.e. it remains the same matrix after rotating it twice. For example, a centrosymmetric matrix has the top-left element the same as the bottom-right, and the element above the center the same as the one below the center. A useful visualization can be found [here](https://upload.wikimedia.org/wikipedia/commons/c/ce/Matrix_symmetry_qtl4.svg). **More formally,** given a matrix \$M\$, produce a square matrix \$N\$ such that \$N\$ is centrosymmetric and \$M\subseteq N\$, and there is no other square matrix \$K\$ such that \$\dim K<\dim N\$. \$A\$ is a subset of \$B\$ (notation: \$A\subseteq B\$) if and only if each value \$A\_{i,j}\$ appears at index \$B\_{i+i^\prime,j+j^\prime}\$ for some pair of integers \$(i^\prime, j^\prime)\$. *Note*: some matrices have multiple solutions (e.g. `[[3,3],[1,2]]` being solved as `[[2,1,0],[3,3,3],[0,1,2]]` or `[[3,3,3],[1,2,1],[3,3,3]]`); you must output at least one of the valid solutions. ## Test cases ``` input example output [[1, 2, 3], [4, 5, 6]] [[1, 2, 3, 0], [4, 5, 6, 0], [0, 6, 5, 4], [0, 3, 2, 1]] [[9]] [[9]] [[9, 10]] [[9, 10], [10, 9]] [[100, 200, 300]] [[100, 200, 300], [ 0, 0, 0], [300, 200, 100]] [[1, 2, 3], [4, 5, 4]] [[1, 2, 3], [4, 5, 4] [3, 2, 1]] [[1, 2, 3], [5, 6, 5], [3, 2, 1]] [[1, 2, 3], [5, 6, 5], [3, 2, 1]] [[4, 5, 4], [1, 2, 3]] [[3, 2, 1], [4, 5, 4], [1, 2, 3]] [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 9, 9, 9, 9, 9, 9, 9], [1, 1, 1, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 1]] [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9], [1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9], [1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1], [9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1], [9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` ṁ↔ᵐ↔?aaᵐ.&≜∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HOxkdtUx5unQAk7RMTgQw9tUedcx51LP//P@p/dLSJjqmOSaxOtKGOkY5xbCwA "Brachylog – Try It Online") Contrary to most Brachylog answers, this takes the input through the Output variable `.`, and outputs the result through the Input variable `?` (confusing, I know). ### Explanation ``` ṁ We expect a square matrix ↔ᵐ↔? When we reverse the rows and then the matrix, we get the initial matrix back ?a Take an adfix (prefix or suffix) of that square matrix aᵐ Take an adfix of each row of that adfix matrix . It must be the input matrix &≜ Assign values to cells which are still variables (will assign 0) ∧ (disable implicit unification between the input and the output) ``` ### 8 bytes, gives all valid matrices Technically, this program also works: [`ṁ↔ᵐ↔?aaᵐ`](https://tio.run/##SypKTM6ozMlPN/r//@HOxkdtUx5unQAk7RMTgYz//6P@R0cb6hjpGMdGm@iY6pjFxgIA) But this will leave as variables the cells which can take any value (they show as `_XXXXX`, which is an internal Prolog variable name). So technically this is even better than what is asked, but I guess it's not what the challenge asks for. [Answer] # JavaScript (ES6), ~~192~~ ~~180~~ 177 bytes ``` f=(m,v=[w=0],S=c=>v.some(c))=>S(Y=>S(X=>!m[w+1-Y]&!m[0][w+1-X]&!S(y=>S(x=>(k=(m[y-Y]||0)[x-X],g=y=>((r=a[y]=a[y]||[])[x]=r[x]||k|0)-k)(y)|g(w-y,x=w-x)),a=[])))?a:f(m,[...v,++w]) ``` [Try it online!](https://tio.run/##3ZHdaoQwEIXvfYr0piQ4SqzbgoWxD@HNLiEXwaq0rmvR4g/k3e2otBR2XfZ6YTjkcL75gXyazrRp8/H17Z3q92yacuQVdKh6lBoSTDHu/LauMp4KgXHCD7PsMX6oVO8G3kE/0kvqxezJJHyciQFjXtIoNRJirRRqoBgKpJTzBo0a9SLWKk2hxobE2pJQrxR8FLbgvTfCgL03CAEGiRPizbzmdKDyfb8D1@21mNL61NbHzD/WBc@5chhTAbAnYKGG2eyAPQN70Q71OxfgaDsBFsjNNJCS1swSyivU@Sm72@D5aOJXEy5JsNn5Oxn@j7myZrP@JqwVndetRHQxuzti/ZPpBw "JavaScript (Node.js) – Try It Online") ### Algorithm Starting with \$w=0\$: * We consider a square container matrix \$M\$ of width \$w+1\$. * We consider each pair \$(X,Y)\$ such that the input matrix \$m\$ can fit within the container matrix when it's inserted at these coordinates. Example: $$\begin{align}w=2,&&(X,Y)=(0,1),&&m = \pmatrix{4,5,4\\1,2,3}\end{align}\\ M=\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\4,5,4\\1,2,3}$$ * We test whether we can complete the matrix such that it's centrosymmetric. Example: $$M^\prime=\pmatrix{\color{blue}3,\color{blue}2,\color{blue}1\\4,5,4\\1,2,3}$$ * We increment \$w\$ until we find such a valid configuration. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` oZ0ṁz0o⁸ṚUŻ€Z$2¡LСo⁸ṚU$ƑƇḢ ``` [Try it online!](https://tio.run/##y0rNyan8/z8/yuDhzsYqg/xHjTse7pwVenT3o6Y1USpGhxb6HJ5waCFMWOXYxGPtD3cs@n@4/eikhztnHJ38cOfiRw1zYnUUoh81zM0CMw9tU4j@/z862lBHASeK1eFSQCiwxETEKbDEKjWMFBjGxgIA "Jelly – Try It Online") Newlines added to actual output over TIO for clarity. [Answer] # [Python 2](https://docs.python.org/2/), ~~242~~ ~~227~~ 226 bytes ``` r=range def f(m): w,h=len(m),len(m[0]);W=max(w,h) while 1: for x in r(1+W-w): for y in r(1+W-h): n=n=eval(`[W*[0]]*W`);exec"for i in r(w):n[i+x][y:y+h]=m[i]\nN=n;n=[l[::-1]for l in n[::-1]]\n"*2 if n==N:return n W+=1 ``` [Try it online!](https://tio.run/##3ZDPaoQwEMbP5imGPfknC0a3BZW8wl49pIGVNtaAzi7BdvXpbaLIgral58KQZL75zTdJbmPfXDGZJsNNhe@KvKkaar8LcgJ32vBWoU3ovIlYBkXJu2rwbSmwQKNbBSwnXn01MIBGMD6LyuPdtnvgxPEhNk70kCNXn1XrX0QZWkcZlpegUIN6PTheL7w1QKGjQYoxH6NG8k5o@YJnjgVy0Yo8PzLp@NbxuOQWOISJnaFrQM7PuVH9h7Fl4pURZ9PNaOzt44RgFBIKqaQExInCE4VnKQNCHkS2zSmweKOxOLY@bknjXW034fQL4S5gofmczjrb0KuHI9bOnd@PsbYtke3jb0D2bekfAe7Xpy8 "Python 2 – Try It Online") --- Saved: * -1 byte, thanks to Jonathan Frech [Answer] # Clojure 254 bytes ``` (defn e[l m](let[a map v reverse r repeat t concat c count f #(v(a v %))h(fn[x](t(a #(t %(r(- l(c(first x)))0))x)(r(- l(c m))(r l 0))))k(fn[x](a(fn[v w](a #(if(= %2 0)%1 %2)v w))x(f x)))n(k(h m))o(k(h(f m)))z #(= %(f %))](if(z n)n(if(z o)o(e(inc l)m))))) ``` Jinkies, Scoob [Try it online!](https://tio.run/##5VXBbtswDL37Kx4QBCMBF5CbbkAOO@0D@gGGDoYjo14dObDlLOjPZ5RsJW7TBcm1EwSL5HukZZGmyqb9PXTmeKSNqSxM3mCrqTEuL7AtdtijM3vT9QadSDtTODiUrS1FKEUYrEOFBe2pEO6S@YUqmx80OTEsyGFJHT2goZKquusdDsysmA8c7diyyGggVubXyb3w6x5/dAhTV/QTy0ehLDNZWQAJQVWIZumVXnyU1gtiFJHfxEtcRJM9aR/gDVaoQWiFaqi2JRr2ZOZjkvgDQG2Tb5QkeZ6leEyx0mmC/CnF9xQ/tPbAelpSZGoUM6WE7B8rFU0X3k@XgI8pWJBXwZ6NpOjhgegQvf85I3uc68t5G2H9KfSFCOGMmad8m8POlM5sngf3PvEp1Dz3UVVjzmJ2VGCeM/euOMJ5K7@lT8rEg4Ao8TGWwYmTXSuljwVzU1VFZR7orgq7sYzup11L539Dm//Gd9GuNgV9LvXatoMD@aa@oKaWVjz2UgHmv8GJ35l@aFyfAFS1HXJneverkIsgBJIalOEvCuQSYGrukcMBHYcJr@2NXBqbM0FPDGnSNN4insdRmeIF2yxYRA2UbIM/0k/2MOQ7dl0t6PQlfPwL "Clojure – Try It Online") ]
[Question] [ The challenge here is to find the longest uninterruped arc around a unit circle with a random amount of points distributed in random positions around it. Here is a diagram to assist my explanation: [![example](https://i.stack.imgur.com/bScM5.png)](https://i.stack.imgur.com/bScM5.png) The red line indicates the largest arc between any two points that is not interrupted by any other points. The challenge is to find the two points on either end of the red line. The green line is simply the straight line distance. A clarification about what interrupted means: When drawing an arc around the edge of the circle (the red line), this arc should not be intersected by any other point. Here is a template for the function in C#: ``` int[] FindPair(double[][] points) { return new[]{ 0, 1}; //Find the indices of the two points } ``` The function should return two integers, the indices of the two points on either end of the green line. Assumptions: * The Length of the points array is arbitrary but more than two. In the example we have: points[40][] * Each element of the points array contains the x, y position of the point, for example: points[i] = {x, y} * You can assume that the distance of any given point to the origin at the centre of the circle is always 1. Notes: * The answer with the smallest Big O algorithm complexity wins. In case of a tie, shorter code wins. * Bonus points for the solution to have the ability to work in more dimensions than two. * I do have a solution, but it is very computationally expensive and only produces the correct answer around 99% of the time. * I am not sure if the problem has a name in mathematics, or a generally accepted solution. If anyone knows of a better name for this problem so that I can have a better title, that would be helpful. **Test case 1**: [![example](https://i.stack.imgur.com/ekAQW.png)](https://i.stack.imgur.com/ekAQW.png) ``` Points: { { -0.71997 , -0.69400 }, { 0.88564 , 0.46437 }, { 0.78145 , -0.62397 }, { 0.98409 , -0.17765 }, { 0.88220 , 0.47087 }, { 0.69938 , 0.71475 }, { -0.89036 , -0.45526 }, { -0.70588 , -0.70833 }, { 0.70507 , 0.70914 }, { -0.34971 , 0.93686 } } Solution: {6, 9} ``` **Test case 2:** [![example](https://i.stack.imgur.com/14ip4.png)](https://i.stack.imgur.com/14ip4.png) ``` Points: { { -0.71038 , 0.70382 }, { 0.04882 , 0.99881 }, { -0.53250 , -0.84643 }, { -0.86814 , -0.49632 }, { 0.97588 , -0.21829 }, { 0.73581 , -0.67719 }, { 0.88413 , -0.46724 }, { -0.28739 , -0.95781 }, { -0.68325 , 0.73019 }, { 0.91879 , 0.39475 }, { 0.65335 , 0.75706 }, { -0.21009 , -0.97768 }, { -0.94542 , -0.32585 }, { 0.83207 , -0.55467 }, { 0.99482 , 0.10170 }, { 0.86228 , 0.50643 }, { 0.98017 , 0.19817 }, { 0.67520 , 0.73763 }, { -0.03982 , -0.99921 }, { -0.57624 , -0.81728 } } Solution: {0, 12} ``` **Invalid example:** [![example](https://i.stack.imgur.com/8RO79.png)](https://i.stack.imgur.com/8RO79.png) This is invalid, because when drawing an arc around the edge of the circle (the red line) between the two points connected by the green line, this arc is intersected by another point. [Answer] # [Python 3](https://docs.python.org/3/), O(n\*log(n)), 167 bytes ``` import math def f(p):p=[math.atan2(*x)for x in p];q=sorted(p);d=[b-a for a,b in zip(q,q[1:])]+[math.pi*2-q[-1]+q[0]];i=d.index(max(d));return map(p.index,(q*2)[i:i+2]) ``` [Try it online!](https://tio.run/##XVLLbqNAELzzFXMEv9Tz7G5b/hLEgQhb4WA8EFby7s97Bw9JOrkhaqq6qqvj3/n9Ptjns7/F@zSrWzu/F93lqq5lrI7xXC8/Du3cDqbcPKrrfVIP1Q8qNqfx/JEYly49PHXn@m3fqgVud2/Lg399LMfdWOtjUzXbLBP7jdmP9V4327GGpjn15@7QD93lUd7aR9lV1Wm6zH@mIdmIZczQrhw3pqr7Y781TfWM6qzqQqla7eGAmhnVbvkM7ABUs3tBcCDywSUEDi44i98AknZ@pRjLAmFywBnRiMFLMWMgiyGQoARmSy8AtcMvRlIgBhuymPPeBAEheKIMJTVrhTfwgFkOWDvBsY5RvxC2gZJa0RRx6oe53CxFVUXxay/w6St9mO8J4FKWrMNEWkzw1njIrmhZmcwS0s7WLByskGP8imI0GRZRrCe9rhlTTXKZTttVLaCRKQ2hXRtgjz/sBUr@ciILUo41Ib8Ay6KCxPDWrgyPIAswGj6L5lQ0CYiddyZDaR7JG7AG1lPzPhkXDtitO9WgUd5gMCa34EFsdLm09DAzmLS8J/TroaHFIDsAy7QaY2bzozkMZq0niaWJv4/j@R8 "Python 3 – Try It Online") The sorting step takes O(n\*log(n)) time, all other steps take linear time. --- ## Ungolfed ``` import math def f(p): p=[math.atan2(x, y)for x, y in p] # convert coords to angle (radians) q=sorted(p) # sort by angle d=[b-a for a,b in zip(q,q[1:])] # calculate the difference between two adjacent points d+=[math.pi*2-q[-1]+q[0]] # difference between first and last point i=d.index(max(d)) # where is the maximum delta? return map(p.index,(q*2)[i:i+2]) # where were these two points in the original list? ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), O(n), ~~234~~ ~~229~~ ~~228~~ 211 bytes ``` a=>(b=a.map(s=>Math.atan2(...s)/Math.PI+2),k=[],b.map(t=>d=![k[u=t*a.length|1]=t<k[u]?k[u]:t,k[--u]=t>k[u]?k[u]:t]),k.filter(t=>t).map((v,i,s)=>d=d<(t=s[i+1]||s[0]+2)-v?(T=t)-(V=v):d),[T,V].map(x=>b.indexOf(x))) ``` [Try it online!](https://tio.run/##VZJLb@IwFIX3/ApmFXtIjN/2pTXsWs2imllU3USRCJBSBgYQSRES5bczzqOt2UTRPb6fj8@9f/NjXs4Pq32VbHeL4vrgrrkbo5nLyb98j0o3fsqrN5JX@ZYjQkiJh03hz68Bx/HapVk8a05WbrxwP9J1@u6qnznZFNtl9fbBMlfd@1o2qT@jKl6nSfLui@OgmHkQeV1tquJQYyrcANExXsUlrrGLe18v09WAZR8fZUozf3dynKBnV@EEvbgjHi1wnD7HL1nTenLjGVltF8Xp9ys6YYyvd4/OF@e7bbnbFGSzW6IHVBzzDUKnQRRhcij2m3xeoGF6vmTDZVzbcC46R5MojUZRFnkIvus9Ts@9fv/cTygxDMD04/pXg6S0f4kbiRJrlZZeoURqKcy3YCyTqmvhAgIFrKTQKswYrUIY57SFGWqDFg0gbCMYJs1XhydYoEK3MKkU14FkqLK2lTxNiMAbVdS0OApMBj1CgmGNAkJbT@tdetPbJOinE//Dv5lUevdtJ1jLAqYSXNHWh61DCt1rn1LnHrQIcGC@zHNmOQTmhbKsC9b4wYTxSSY6mjY8fBe3RnSZgzI39rT1/toXCRrigFkDjSAgCN13KCG6DmVoGDln9HO04EdrAwmkkryV/H02nLrgtFsupbzxwAHILlNGmQm3TnPeTkHRINF6t/zBtgMsCzfIqG61jDA6nAEVYDtjAMBvJmc078bjYf5Gvw7T638 "JavaScript (Node.js) – Try It Online") Assuming: * atan2 is O(1) * x.map, x.filter are O(n) function calls * x.indexOf is O(n) --- ``` a=>( n=a.length, b=a.map(([t,u])=>Math.atan2(t,u)/Math.PI+2), // [1, 3) k=[...Array(n*4)], b.map(t=>d=![k[u=t*n|1]=t<k[u]?k[u]:t,k[--u]=t>k[u]?k[u]:t]), // interval = 2/n, just enough k.filter(t=>t).map( (v,i,s)=>d=d<(t=s[i+1]||s[0]+2)-v?(T=t)-(V=v):d ), // furthest [b.indexOf(T),b.indexOf(V)] ) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), O(n), 92 bytes ``` L←12○⎕ x←(n←⍴L)⍴⊂⍬ L{x[⌊n×.5+⍺÷○2],←⊂⊂⍺⍵}¨⍳n 1∘⊃¨{2↑⍵⌽⍨⊃⍸(⌊/=⊢)2-/{⍵,⍵+○2}⊃¨⍵}⊃,/{⍵[⍋⊃¨⍵]}¨x ``` [Try it online!](https://tio.run/##jVJNTxNRFN3Pr2jCBgK07/u9S@KCBguWaVELaiAsSiFtI8506BQKhI0mSApjdGFw48YVCxMXajQkbuCfvD9S73sDrl3MzHvn3nPuvedOs7c7u33Y3I3bY/vu46MVe/qeBPbsbW8c4pEye3mOeDDEy2SEL5v9CKfwZUevbfY1CI@HG/ZiFN1eFuW0za5vfyGBbc64TMxwSdc2@3lyc2Wz71FA7dknO3pzc3XM7OkHDNiLPza7QshmvydRqPTAjr5MsdnSMQZn8Jl2eiee43TwMONjGzY7v0c3UX44xqbHNvtcaMXR/s5eWmg1@zv9ucBBnTTt9edKpbQbF/cGUWliYpnE6WFrGNYfH5X2aVLukkGnEndoJeyawdLTrnm1vJxutdcGSw25kPAoibcOBouJbK8kolJuJJUXT@pQO6iHDV5vN5Py6kI9fHhQW@g8i7f71UY5ip9XkvWX1bXa@vyRWa0N6@1WczFO5@eDXnDzjRQ1BdBVd1IgCCmQojFSiSopCiW4xrs2VMg8g3FwCBhBwCNUayU9hzHiOJoYl6EAuKk6daFlwWUaIFx5jpCSKY9pIo2p5ifDecEjRDseASp8DhegKSLAlVH/eia5On4YsojA@i4HjKGeJTmTxCsbN0begcJB8g5AcccDfV@fUcPA1efS0HxWjc74yQTlOUtplvfEjOb5/CD1XUVlsKTriRPPA2o04J2DcwDjknMfl5rk0zNK7lwEdNF4DIQUzGOoZryznJF8P1JiB04ZhJ@WEqr9vhRjzg1J3KRuOxhwcTDU70JLvxvNtcqdIBxMXgUA2J1jWrHcHWQx839/R/AX "APL (Dyalog Unicode) – Try It Online") Takes input as a vector of complex numbers and outputs a single array of the two indices. This uses bucket sort to achieve linear complexity. Requires `⎕IO←0` ## Details ``` L←12○⎕ ⍝ Take input to L and convert all points to their phases -- O(n) n←⍴L ⍝ Set n to be the length of L x←n⍴⊂⍬ ⍝ Create an array consisting of `n` empty buckets -- O(n) L{...}¨⍳n ⍝ For each ⍺=element of of L, ⍵=corresponding index: -- ×n: ⍺⍵ ⍝ Create an entry consisting of the two-element array ⍺ ⍵ -- O(1) x[...],←⊂⊂ ⍝ Append it to the correct bucket in x -- O(1) ⌊n×.5+⍺÷○2 ⍝ Map phases in [-pi, pi) to bucket indices in 0..n-1 -- O(1) x ⍝ Now, x is a vector of buckets, ⍝ each of which contains a vector of entries (phase, index) {⍵[⍋⊃¨⍵]}¨ ⍝ Sort each bucket by phase (buckets contain 1 element on average, so this is O(1) average case per bucket) ⊃,/ ⍝ Join so we have a single sorted vector of all entries (phase, index) {...} ⍝ Computationally less-worrisome part now that we have the phases sorted ⍝ Most following lines are O(n), rest are O(1) ⊃¨ ⍝ Extract the phase of of each entry {⍵,⍵+○2} ⍝ Add 2pi to each phase, and append (deals with wrapping around) 2-/ ⍝ Compute the difference of each consecutive pair of phases ⍝ (always negative since the phases are increasing) ⊃⍸(⌊/=⊢) ⍝ Find the index i of the minimum difference (most negative --- furthest) ⍵⌽⍨ ⍝ Rotate the original vector of (phase, index) by i 2↑ ⍝ Take the first 2 entries 1∘⊃¨ ⍝ Get the indices of these two entries ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), O(n log n)?, ~~130~~ ~~129~~ 125 bytes ``` a=>a.map((r,i)=>[Math.atan2(...r)+6,i]).sort().map(([r,s],i,a,[p,q]=a[++i]||a[a=0])=>[p-r+!a*2*Math.PI-8,[s,q]]).sort()[0][1] ``` [Try it online!](https://tio.run/##VZJPb9pAEMXvfAp6sh0WZ/bvzDQyvSXqoVLvliVWFCVEFKixokiEz04XdkMWn1Z6Oz@/fW9e/ZvfL/rVbphutn@Wp8fm5JuZr//6XVn2YlU1s/aXH15qP/iNKuu67quJE6uuqvfbfiireLPtxb4TK@FFuxP/usa3k8mq@/jwrW@gO0N2037yzd@puwvt988piXYfrl5BLXSt7E4PT817M1tsN/vtelmvt8/lY7l88@uyfJ8URVX3y93aL5blfXs4dvfPYmhmQ9MUh@JH0Rbfi66owvcwepofRuPxYTyFGiUzjsX56NgAjI/iIkFNZJ0JCtTGGY1fApI0No0ozZnCZICjIhGdzWFKQYQhUDbimDVdBJQGrxOBQAzaRZixVrlMQrBEUQo0rTNvYAEjDliabEYbRnlRWDsKtNFxNL9NAj6dhIP6YoIJ7uMkE8mMabWyEH3QOaTcvQspJffsdIZjvJpXkhRn5rUlmYLFUEwen5E60Ryq/F2KUKfM2eKNPUfBX3yRhhzHkpAvguYs9DBhtU4TFiGPXEn4rJZDtZRJbKxRUQr/o7x1rSAtl7XBeOaATcpUgsR865xSsQULWaLn3QoX4wSTzDcIbVot1OjyDkAzJWPMrG6aQ6dSPQEW/hjWYX76Dw "JavaScript (Node.js) – Try It Online") If the sorting is treated as O(n log n), then the whole algorithm is O(n log n); however it sorts by ASCII, so I'm not quite sure if the complexity remain [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 92 bytes ``` s~Position~#-1&/@Last@(S=SortBy)[Partition[S[s=#,ArcTan@@#&],2,1,-1],EuclideanDistance@@#&]& ``` [Try it online!](https://tio.run/##bVJNa9tAEL37VwgMpgXZmZ3Z3Zk5GNTS3nowuDfjg3BNKmhksJRDCclfV9faTTKB3gRP7@37mId2/H1@aMfu1E7322l42V2Gbuwu/cty7VZ3zY92GJtP@@3@ch2//v182LXXccYP@8OwXdZfrqefbd80y9WxxtrVa3esvz@e/nS/zm3/rRvGtj@dZ3g17a5dP1bN/eFpUVVP1Ro27FS5qm@fUT1A9VzPEGxEQvQJgY2PnvgdYHE@FAqSGkTFg2bEMcdgxRAhizGIoURVkhlg5/mNkRREgWIW8yFgNBBDEMlQUiMy3iAAZzlQ5w2HvLKbEaUoSW3xfFws/lcIvBpKH/guDT6FyAIq4ox0IAyQ7citKxsiprJKCI1k5JTfMqATVJOBgrjSL6d9bIveUVGLjDYeClOpXgN/sBcl@cuJCKycOmGdAVLTfWIEosIIDLZ5dPC6sKaFxUDqg8cMpffEjk8I5cZCSMaNA/WlUweO7fFFxLxCANPo7cTSj5mh4uwhcSgXxsTRbgCkUoypKn5YjiOWeZJYejFdxeI4Tf8A "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ Most people are familiar with the trope about counting sheep to fall asleep. There's a herd of sheep, some of them jumping over a fence, and you count the sheep as they jump. Supposedly, this helps quiet your mind and gets you into a sleep-like state so that you'll fall asleep. Here's an ASCII sheep facing to the right, waiting to be counted: ``` '00^> || ``` Here's an ASCII sheep jumping over a fence: ``` '00^> /\ ++ ``` Here's one facing to the left, having already been counted: ``` <^00' || ``` ### The Challenge Given two input integers, `n` and `m`, with `n > 2` describing how many sheep total, and `m > 0` saying how many sheep have already been counted, output an ASCII art representation of counting sheep to fall asleep. **Now for the twist:** * Due to the size of the pens the sheep are in, the top row can only hold a maximum of `10` sheep, not counting the currently jumping sheep which must also always be in the top row. * The subsequent rows cannot have the sheep outside their respective pens (you can't have more sheep on the left in the second row than you do in the first row, and same for the right). * If there are `11` or more total sheep, the top row must have `10` plus the jumping sheep in it. * Leading/trailing whitespace, and whitespace between the sheep doesn't matter, so long as: 1. There is a minimum of one whitespace character between sheep 2. All the characters line up appropriately. So long as these rules are met, the actual arrangement of the sheep is up to your implementation. ### Examples For example, here is `n=3` and `m=1`, the simplest case. ``` '00^> '00^> /\ <^00' || ++ || ``` Here is `n=11` and `m=6`, the most sheep that can fit on one horizontal line. ``` '00^> '00^> '00^> '00^> '00^> /\ <^00' <^00' <^00' <^00' <^00' <^00' || || || || ++ || || || || || || ``` Here's a different example of that, with `n=11` and `m=1` ``` '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> /\ <^00' || || || || || || || || || ++ || ``` A bigger example with `n=30` and `m=12` ``` '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> /\ <^00' <^00' || || || || || || || || ++ || || '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> <^00' <^00' || || || || || || || || || || '00^> <^00' <^00' || || || <^00' <^00' || || <^00' <^00' || || <^00' <^00' || || ``` Here's an example with `n=17` and `m=2` ``` '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> /\ <^00' <^00' || || || || || || || || ++ || || '00^> '00^> '00^> '00^> '00^> '00^> || || || || || || ``` Here's an example with `n=19` and `m=3` ``` '00^> '00^> '00^> '00^> '00^> '00^> '00^> '00^> /\ <^00' <^00' <^00' || || || || || || || ++ || || || '00^> '00^> '00^> '00^> '00^> '00^> '00^> || || || || || || || '00^> || ``` Note that all of these are *examples*. For the last one, you may wind up creating a vertical array of sheep on the right-hand side, which will allow the left hand side to fit onto two rows instead. Or maybe a 2x2 square of sheep on the right-hand side, which would also fit the left-hand side sheep onto two rows. Etc. ## I/O and Rules * Input can be taken in any reasonable format and [by any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * Output can be to the console, returned as a list of strings, returned as a single string, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 118 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous infix lambda. Takes `n` as left argument and `m` as right argument. Returns a nested array result, but the default display of this nested array follows specifications. Uses up to nine columns for counted sheep and remaining columns for waiting sheep. ``` {(r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)(↑(s←'>',⍨¯1↓b)' /\' ' ++')(r⍴(×/r←9,⍨⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')} ``` [Try it online!](https://tio.run/##VY3BasJAEIbvPsXeZpco2U1ADIj0HXIthUjQHAJKPISiQvEQJCTQ0oJ3T731oghCLuZN5kXizFIsvX3zz8/3R8t0EL9G6WLedTMs3tcyw/ok24Ob0RX3sf7Gap@3l5hOowdYn7EqsTy6mcLiI@dyTi@sr/xzjKIEy93qycOqCZWkklxRASbAstuPweJzqkC4zyBAOA6of5PB7yTJ2kvAGzxpnSHvVA1FAHLKTgCtX8ZAts0G1LZL2DDSLuDXG3S@mAnTS7KeMUTDB9nM10zeI/yjkSWPKLBkNfoO) `{`…`}` anonymous lambda; `⍺` is left argument, `⍵` is right argument This function has three distinct parts: **Waiting**, **Jumping**, and **Counted**. Each one is parenthesised, causing the result to be a three-element list. ### Counted `(r⍴(×/r←9,⍨∘⌈⍵÷9)↑⍵⍴⊂S←⌽↑''(b←'''00^<')' ||')` `''(`…`)' ||'` the three lines of a mirrored counted sheep, the middle one being:  `b←'''00^<'` the body and is assigned to `b` `↑` mix the list of strings into a character matrix (padding with spaces) `⌽` mirror that `S←` assign to `S` (big **S**heep) `⊂` enclose it so we can deal with it as a unit `⍵⍴` use the number of counted sheep to cyclically reshape that `(`…`)↑` take the following number of elements from that (padding with prototypical items, i.e. the same array but with all characters replaced by spaces)  `⍵÷9` a ninth of the number of counted sheep  `⌈` round up  `9,⍨` append 9 to that  `r←` assign to `r` (what we will **r**eshape with; rows and columns)  `×/` product of that list (this is how many elements we need, including fills) `r⍴` reshape that to an array with the dimension lengths `r` ### Jumping `(↑(s←'>',⍨¯1↓b)' /\' ' ++')` `(`…`)' /\' ' ++'` the three lines of a jumping sheep, the first one being:  `¯1↓b` drop the last character from `b`  `'>',⍨` append a right-facing head  `s←` store in `s` (small **s**heep) `↑` mix the list of strings into a character matrix (padding with spaces) ### Waiting `(r⍴(×/r←d,⍨⌈w÷d←10-⍵⌊⊢/r)↑w⍴(w←⍺-⍵+1)⍴⊂s@2⌽S)` `⌽S` mirror `S` `s@2` put `s` **at** line 2 of that (replacing the current data there) `⊂` enclose it so we can deal with it as a unit `(`…`)⍴` cyclically reshape that to the following size:  `⍵+1` the number of counted sheep plus one  `⍺-` subtract that from the total  `w←` assign to `w` (**w**aiting) `(`…`)↑` take the following number of elements from that (padding with prototypical items)  `⊢/r` the rightmost element of `r` (i.e. the number of used columns for counted sheep)  `⍵⌊` the minimum of total and that  `10-` subtract that from ten  `d←` assign to `d` (**d**ifference; missing columns)  `w÷` divide `w` by that  `⌈` round up (gives number of needed rows)  `d,⍨` append `d`  `r←` assign to `r` (what we will **r**eshape with; rows and columns)  `×/` product of that list (this is how many elements we need, including fills) `r⍴` reshape that to an array with the dimension lengths `r` [Answer] # Javascript, ~~281~~, ~~293~~, 288 Bytes ``` a=" ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," || "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?" ":["'00^>"," /\\ "," ++ "][j])+[a," <^00'"," || "][j].repeat(m>i?1:0)+"\n"}}return b}); ``` ### Be careful when using the below snippet, there's a heavy risk of sudden induced narcolepsy. ``` <form id="form"> <input type="text" name="n" placeholder="n (sheep total)"> <input type="text" name="m" placeholder="m (sheep in right hand field)"> <button type="submit">Let's Go!</button> </form> <pre id="output"> </pre> <script> a=" ";c=((n,m)=>{b="";for(i=0;i<(q=m>(o=(l=(t=n-m-1)?t:0)/9)?m:o);++i){for(j=0;j<3;++j){b+=[a,"'00^> "," || "][j].repeat(r=l>i*9?(z=o-i)>1?9:Math.ceil(z*9):0)+a.repeat((l>9?9:l)-r)+(i?" ":["'00^>"," /\\ "," ++ "][j])+[a," <^00'"," || "][j].repeat(m>i?1:0)+"\n"}}return b}); form.addEventListener("submit", function(e){ e.preventDefault(); var n = parseInt(form.n.value); var m = parseInt(form.m.value); if(n != NaN && m != NaN){ if(m > n){ output.innerText = "C'mon man, how can you have more sheep in the right hand field than there are sheep in general?"; } else{ output.innerText = c(n, m); } } else{ output.innerText = "Numbers only please."; } }); </script> ``` [Answer] # C, 392 bytes *Thanks to @Jonathan Frech for saving a byte!* ``` #define F;for( x,y,k;p(L,a,b,t)char L[][78];{F k=5;k--;)L[x=a*4+(t<2)][y=b*6+k]=t?"'00^>"[k]:"<^00'"[k];L[++x][y-=~!t]=47;L[x][++y]=92;L[x][--y]=L[x+=(t>1)][y]=t<2?'|':43;}i,l;f(n,m){char L[i=n*4][78]F;i--;){F L[i][l=77]=0;l--;)L[i][l]=32;}F l=n+~m;++i<l&&i<9+!m;)p(L,0,i,1);l-=i;p(L,0,i++,2)F;i<11&&m--;)p(L,0,i++,0)F i=0;l--;)p(L,++i,0,1)F i=1;m-->0;)p(L,i++,10,0)F l=0;l<i*4;)puts(L+l++);} ``` [Try it online!](https://tio.run/##pY9NTsMwEIX3PYUbRGvHjmQngVAmLruscoPUSKUQsPIDaoPUqrRXL@ME1AXd4ZXnezNv3qyC19XqdLp6filt@0IyKN/XdLQVO1HBB83FUjyJjq3elmuSF6ZI7gzsM1LpG6iCAFhebPXSjznt0pCZYqef/FteGd09eFMpH@deUZl7L32Ucuq@kBecb7Ev0MdxZ3ScIMGa853Rs3AoggAL/HFNu7lyruiXhg/Tr@l9HMHBihpK2oqG7X9yWd36cR8uA@tiYUSkpqh1khgtoR6yOmJ0FMIhI7Vu@bEBzm1aTyY2nfFxA8ydLIUViuGMtvBTcy5Cht6pUpNJ48zOgmQZsb87HEZLlFSPFWD3XA6C61ayH6jdQGr9GJXPbkNzXnPO4HCybUeapW0pG@1HBF9/or/RXvDvt2g96D0/1rimpN6ivd4gFGTDBqGkkSB4e5/pDJUS5PYi/dsbSaTh3@ZEkAt0Jkh00XiGdEjp@OH0DQ) **Unrolled:** ``` #define F;for( x, y, k; p(L, a, b, t) char L[][78]; { F k=5; k--;) L[x=a*4+(t<2)][y=b*6+k] = t ? "'00^>"[k] : "<^00'"[k]; L[++x][y-=~!t] = 47; L[x][++y] = 92; L[x][--y] = L[x+=(t>1)][y] = t<2 ? '|' : 43; } i, l; f(n, m) { char L[i=n*4][78] F; i--;) { F L[i][l=77]=0; l--;) L[i][l] = 32; } F l=n+~m; ++i<l&&i<9+!m;) p(L,0,i,1); l-=i; p(L,0,i++,2) F; i<11&&m--;) p(L,0,i++,0) F i=0; l--;) p(L,++i,0,1) F i=1; m-->0;) p(L,i++,10,0) F l=0; l<i*4;) puts(L+l++); } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~222~~ 277 bytes ``` n,m=input();n-=m+1 s=" '00^>" j=1;L=' || ' a,b=[[[5,5],[10-m,m]][m<9],[n,10-n]][n<9] print' '*6*a+s while n>0 or 0<m:N,M=min(n,a),min(m,b);n-=a;m-=b;print '%-*s'%(6*a,N*s),'%5s'%('/\ '*j)+'%*s'%(6*b,M*" <^00'")+'\n'+'%*s'%(-6*a,N*L),'%5s'%('++ '*j),'%*s'%(6*b,M*L)+'\n';j=0 ``` [Try it online!](https://tio.run/##VY7RasMwDEXf8xUiEJTYMrMHGbSO@wVpf8BNIYFCE2Y1NBlj0H/P3GZj7E3nSkfc8Wu@XPl1WZiC63n8mPPCsnJBmmRyKaDWp12aDM7Y2iHA/Q6ASUud896XVDbkjVaBQtP4UG0iMsWAI3LEZLz1PCOgeBOtnJLPS/9@Bt5puN5AV2F7oL0LPedMbUGPIVD3LNDaoFxnnz5gpsSEWR6f0EFMBWFWPhhfjrGOGAqJ2c9BR3uRQnXSGtMYHxl/d2q16z9bytWmf3a9anZwelmMJvMN "Python 2 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 293 bytes ``` {f=" '00^>" l=" || " L=" /\\ " p=" ++ " Y=$2 X=$1-Y-1 E=" " x=$1>11?Y<5?10-Y:X>5?5:X:X y=$1>11?X<5?10-X:5:Y printf"%"6*(x+1)"s\n",f for(;X>0||Y>0;A=B=""){for(i=0;i++<x;B=B (X>=0?l:E))A=A (--X>=0?f:E) A=A L B=B p for(i=0;i++<y&&--Y>=0;B=B l)A=A"<^00' " print A"\n"B"\n" L=p=E" "}} ``` [Try it online!](https://tio.run/##TVDBasMwDL3rK4To2mSZmdUsHXNqhwRy6wfYEAq9BMJCF7rBUpp@e2ZnO@zyeHrvSUg6fb/P863VhBspj4ag9xSnCZEQDoE/Nw36CoZQJMnCnV5tweoVCycY6uDgYoxeM8yF22cFS@GUNVmRKassXP8s@2tZlSkHw6U7f7X0QLvHaEw4ps/mTE8ttB@XKLdGTpMzMi91pYniW1A7LfMuSfZjXukKI2u0LHpVx3GpS4yEWITWCxCEA4TUAP87r@u1EM7Hlgl9aKT9UcpNODLsgyX5LaoA/gWDrgnpfp9nfkMJKTIw4y4AQyqRt8CvuAC/gM@k8AM "AWK – Try It Online") I tried using string substitutions to avoid some loops, but it took a lot more code. **Explanation** ``` {f=" '00^>" Let's assign l=" || " some variables L=" /\\ " for the ASCII p=" ++ " pieces Y=$2 The number of sheep that have already jumped X=$1-Y-1 Sheep patiently waiting to jump E=" " A string to keep things spaced properly x=$1>11?Y<5?10-Y:X>5?5:X:X If there's enough sheep, let's use 5 per column y=$1>11?X<5?10-X:5:Y Otherwise, use enough to get 11 sheep in first row printf"%"6*(x+1)"s\n",f Print the top part of the jumping sheep for(;X>0||Y>0;A=B=""){ Loop until we've printed all the sheep for(i=0;i++<x; Loop over waiting sheep in this row B=B (X>=0?l:E)) Build the "legs" string A=A (--X>=0?f:E) Build the "bodies" string A=A L Add the legs and post B=B p for the jumping sheep for(i=0;i++<y&&--Y>=0; Loop over the jumped sheep in this row B=B l) A=A"<^00' " Add to the "legs" and "bodies" string print A"\n"B"\n" Print what we've got so far L=p=E" " Prevent the jumping sheep's parts from printing lots of times }} ``` I must say the sheep art is rather cute. :) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 98 bytes ``` Nθ≔⁻⊖NθηF⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+ η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧«J⁰¦⁰‖T§ι⁰↗F§ι¹«<^00'¶ || ↗¿¬﹪⊕κ§ι²”|I4O ``` [Try it online!](https://tio.run/##hZDNasMwEITP8VMsvnRFUuq09NAfCoFeUnAoIT1ZDri2Eovaki3LIdDk2d2VEmigh64QiNn5RivlZWZynVXDMFdNbxd9/SkMtuwpmHWd3CqMpeo7fBW5EbVQVhR4aWRsAi3tkoCNNoBJEkYRVzecczUeQ0jtCVCGrPsakzjbnw73XqTgaeTg1MWkLJ0A4esXrjwODi//xVuPl4SnDL6D0VtfNyuN1IloqtFSbCqR25XJVEcj1ujEdyOVxZmdq0LsUTqrk2O9E/j40SzltrRO8G@6sE2Zv@LMh8/rKLriCuBwgND5/yaM5AZwoS3GuugrTb/3@5NfNPdF@C2jgnM0N24BlQ8@BsdhuAumD8P1rvoB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the number of sheep that have already been counted. ``` ≔⁻⊖Nθη ``` Input the total number of sheep and calculate how many still need to be counted. ``` F⟦⟦00¶/\¶++ θ⌊⟦⌈⟦⁵⁻χη⟧θ⟧⟧⟦0^>¶\¶+ η⌊⟦⌈⟦⁵⁻χθ⟧η⟧⟧⟧« ``` Create an array of two arrays. Each array has the following elements: * A string containing half of the jumping sheep * The number of sheep on that side of the fence * The number of sheep in one row on that side of the fence, which is either + the number of sheep on that side of the fence, if fewer than 5, or + 10 - the number of sheep on the other side of the fence, if fewer than 5, or + 5, if both sides have at least 5 sheep ``` J⁰¦⁰‖T§ι⁰↗ ``` Reflect the canvas and print the half jumping sheep. ``` F§ι¹« ``` Loop through the sheep on that side. ``` <^00'¶ || ↗ ``` Print a sheep. ``` ¿¬﹪⊕κ§ι²”|I4O ``` If this is the end of the row then print some newlines and spaces to get to the start of the next sheep. ]
[Question] [ This task is to output the shortest path to a file, after glob expansion. What is shell globbing? In most shells, you can use the `*` character in a path to represent any characters at the position. For example, If directory `foo` contains files `bar` `baz` and `asdf`, then `foo/b*` will expand to `foo/bar foo/baz`. Now, lets say that the current directory contains a file called `ihavealongname` and nothing else. If I want to reference this file, I might type `*`, which will represent only that one file, rather than typing out the full name. If the directory also contains a file called `ialsohavealongname`, I can't do `*`, as it will match both files. The I would have to do, at least, `ih*`. The `*` pattern also works for matching directories above the file I'm looking for. If there are only two directories `foo` and `bar`, but `foo` contains only a file `baz` and `bar` contains file `asdf`, I can match `foo/baz` with `*/baz`. Or, even more concisely, `*/b*`. If `bar` was empty, `*/*` would work. Your task: Given a string array of paths that represent the "current directory" and a single target path, output the shortest possible string that would expand to only that target path after expanding \*s. The target path can be taken as it's own string, as an index into the array of paths, as the first item on the array of paths passed in, or some other convenient way that isn't hard-coding. Ask in comments if unsure. The target path is guaranteed to be present in the "current directory". You can assume that all paths contain only alphanumeric ASCII (and `/`s). You may take as input paths that are rooted (start with `/`) or relative (don't start with `/`). If there are multiple equally short possibilities, return any or all of them. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Test cases](https://gist.github.com/pavelbraginskiy/70ff280556d577633da162c4b8585e52), thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). [Answer] # [Perl 5](https://www.perl.org/), ~~136~~ ~~107~~ 102 bytes Includes `+2` for `n0` Give list of files on STDIN. The first one is assumed to be the target file ``` perl -n0E '@a="";for$a(@a){s%%s/(?=$a )/;/g;$$_//=push@a,map$_.$a,/./g,"\\w*";/^;/>/ ;/&&1/!say$a=~s/\\w//gr%e}' foo/barber/test foo/barber/testing foo/barber/coding foo/test foo/bar/test ^D ``` Just the code without making the newlines literal: ``` @a="";for$a(@a){s%%s/(?=$a\n)/;/g;$$_//=push@a,map$_.$a,/./g,"\\w*";/^;/>/\n;/&&1/!say$a=~s/\\w//gr%e} ``` Crashes intentionally after printing the solution. Still seems too long (the use of `$a` and `1/0` are very awkward), but it's a start and should be reasonably efficient. [Try it online!](https://tio.run/##XYrdCoIwGIbPvYvGFA3dawceDcsb6A4k@axpQrmxGRFRl94KIpAOnx@j7KnwvqKSMdlpyymuKLm7MHSINyWnIIFELzlvgNJc3LGi9EyGN4JTCoE@ZXV9XTKJncQagUQUrbBwdONUPh0@EehtqB7ed1qjJdsqi0m5KfjjYeznaq8PPzO/v/DSZhr06Hw25j7bFmKVi/wN "Perl 5 – Try It Online") # How it works The program builds candidate globs by growing them from the back to the front starting with the empty string. It does this in a breadth first way, so first globs of length 0 are tried (only ``), then length 1 (like `t`, `i`, `*`), next length 2 (like `fb`, `i*`, `*g`, `**`), next length 3 and so on until a glob is found that only matches the first path. This will then be the shortest glob that solves the problem (others of the same length may exist). The globs of length `n+1` are generated from the globs of length `n` by prepending each character from the list of paths and also `*` in front of each glob of length `n`. So e.g. length 3 glob `*i*` will contribute length 4 globs `f*i*`, `o*i*`, `o*i*`, `/*i*`, `b*i*` ... `s*i*`, `t*i*` and finally `**i*`. Notice that every character from the list of input paths is prepended even if it appears multiple times or makes no sense whatsoever because it leads to something that can never match. Doing this naively would lead to a combinatorial explosion. That is why every candidate glob gets evaluated for how useful it is by determining at which points in the paths it could match if the glob was used at the end of a complete glob. I do this by inserting a `;` at each place where a match is possible. For example for the glob `t*` I will get the string: ``` foo/barber/;tes;t foo/barber/;tes;ting foo/barber/coding foo/;tes;t foo/bar/;tes;t ``` This represents the "distinguishing power" of the glob. Every glob that has exactly the same distinguishing power is equally good. If you replace them by each other at the end of a complete glob they will all match exactly the same paths. So you can just as well use the shortest one. So when considering the length `n` globs I first look at its distinguishing power. If it has been seen before there was another glob of length `n` or shorter that was already considered and expanded, so this glob is pointless and gets pruned. This will for example get rid of candidates like `**i*` since the same distinguishing power will already have been seen as `*i*`. It also prunes impossible candidates like `f*i*` since the distinguishing string will have no `;` and just be the original list of paths. Only the very first impossible glob will be accepted, all the others will be seen as having the same distinguishing power and will be pruned. And even that first one won't really get expanded since all expansions are still impossible and will be pruned when they are considered. Simularly `in*` will be pruned by `i*` etc. The above leads to very aggressive pruning and the program is therefore able to handle complex cases in a very short time. A major inefficiency though is that it prefixes the candidate globs with all possible characters, not only the ones just before a `;` in target path part of the distinguishing string. All added characters that are not in front of a `;` are no problem since they lead to an impossible glob which will be pruned when it gets considered, but that still leaves the characters just before `;` in the other paths. So in the end the program also builds globs that will be able match any combination of the given paths. It has no idea that it should be concentrating on the first path. Now consider a solution to the problem. In the given example that could be `*/*er/t`. This gives the following distinguishing string: ``` ;f;o;o;/barber/test foo/barber/testing foo/barber/coding foo/test foo/bar/test ``` I recognize a solution by having a `;` at the first position (so it matches the first path) and not having a `;` at the start of any other path (so the others don't match) With the algorithm explained I now get to the actual program: The candidate globs will be in array `@a` which I loop over using variable `$a` which contains the glob currently under consideration. Instead of `*` in the glob I will however use `\w*` so `$a` is actually a regex instead of a glob. I'm going to abuse a weirdness of the perl for loop that you can append elements to the array being looped while the loop is running and these new elements will get picked up in the loop. Since when generating the length `n+1` globs all length `n` globs are already on array `@a` this is breadth first. Due to the `-n0` option (implicit loop over the whole input) the list of paths is in `$_` as one big string with each path terminated with a newline ``` @a=""; Start everything with the length 0 glob for$a(@a){ } Loop over candidates in a breadth first way ``` Inside the `{ }` we have: ``` s/(?=$a\n)/;/g Loop over the paths and insert a ; at every position that the suffix glob can match by looking ahead and checking that the regex under consideration can match up to the end of the path we are in. The distinguishing sting is now in `$_`. ``` Oops, I just destroyed `$_` and I will need it for the next loop. So wrap the actual working code inside ``` s%% ...code.. %e ``` This matches the empty string at the start of `$_` and allows you to run code to determine what it gets replaced with. If I make sure that that code evaluates to the empty string `$_` will at the end remain unchanged even if I change `$_` during `code`. Going back to just after I replaced `$_` by the distinguishing string: ``` $$_//= expression ``` This is like: ``` $seen{$_} //= expression ``` `//` in perl is`'defined or`. It's like a short circuiting `or` where the second argument is only evaluated if the first one is `undef`. And it can be combined with an assignment just like `+=` in some other languages. So if they key `$_` in hash `%seen` is `undef` (which is is what you get when accessing a non-existing element) only then execute expression and assign it as value to key `$_`. So if I make sure `expression` does not return `undef` that basically means "evaluate expression if and only if this is the first time we see that particular distinguishing string". And because `$_` is guaranteed to contain a `\n` it is in fact safe to abuse the perl global hash to store the distinguishing strings, so `$$_` instead of `$seen{$_}` For the `expression` I use: ``` push@a,map$_.$a,/./g,"\\w*" ``` Basically "For every character (except newline) in the distinguishing string and also `*` prepend it to the current glob and push that on the array of candidate globs". Execpt I use `\w*` for `*` to get a valid regex (I could use `''` instead of `""` to get rid of one backslash but then I couldn't run my code from the command line). Notice that this also picks up the `;` and adds them to the candidate globs but when later testing them to the restored `$_` which has no `;` that will again be an impossible glob and get pruned. ``` /^;/>/\n;/ && If the distinguishing string corresponds to a solution say$a=~s/\\w//gr Then replace all \w* back to * and print the solution 1/! Say returns 1 so this becomes a division by 0. The program exits by crashing after solving it ``` Notice that `/^;/>/\n;/` has a value equivalent to the empty string in case a solution was not yet found, so this will function as empty replacement string and `$_` gets restored [Answer] # Java 10, ~~854~~ ~~824~~ ~~796~~ ~~738~~ ~~728~~ ~~703~~ ~~688~~ ~~655~~ ~~652~~ ~~647~~ 624 bytes ``` import java.util.*;a->f->{var L=new Stack();List<String>s;int i=999,j,k;for(var t:f.split("/")){s=new java.util.concurrent.CopyOnWriteArrayList();s.add(t);for(k=1;k>0;){k=0;for(var x:s)for(j=0;j<x.length();)if(!s.contains(f=x.substring(0,j)+"~"+x.substring(++j))){s.add(f);k=1;}}for(var x:s)s.add(x.replaceAll("~+","\\*"));L.add(s);}p(L,s=new Stack(),0,f="");for(var y:s){k=0;for(var x:a)if(x.matches(y.replace("*",".*"))&x.split("/").length==y.split("/").length)k++;if(k==1&(j=y.length())<i){f=y;i=j;}}return f;};void p(List L,List r,int d,String c){if(d==L.size())r.add(c);else for(var o:(List)L.get(d))p(L,r,d+1,c+"/"+o);} ``` What a mess.. This is certainly not an easy challenge in Java. ~~Can definitely be golfed by a couple hundred bytes, but I'm just glad it's finally working now.~~ Told ya. :) -5 bytes thanks to *@ceilingcat*. -23 bytes switching from Java 8 to Java 10 Input as a String-array of file-paths (with directories as separated items, and all items containing a leading `/`), and a String with input file-path to grop. **Explanation:** [Try it online.](https://tio.run/##zVjdb9s2EH/PX0HzodCXpaRtWsSKPARZCwzw0KIrsId1D7REJbJlSSNp1x9z//XsKJESHSdZU2SL/SAe73h3v/sgZWpCFqQ/SaY32awqmUATmPtzkeW@EyL4BQH6SIBfpkhcUzReCdqPy3khjuKccI5@JVmxOUKGXjovYpGVhf9eEee/CZYVV3/86X3HKg8143CIYhShG9Ifpv3hZkEYGkUF/QpiEk8tOxxlXCidIQ@zQqAsOjs78ybeNExLZkkNMUh9XuWZsHCAbXvDawsdiLgs4jljtBD@ZVmtPhS/s0zQC8bISpoHL9wnSWIJuzY5jU7C6fA4tDfT6Lh1shxwW9IT4E3Ol35OiytxDbp2llo9Lp0ISBK30mjp8/mY15itY29iu/gbdk2m605sibP2mtqh9Ljdmp5AxuisXFBrqdEtgVPlJKYXeW7hby728JcvDsQbbkf1Ag5UZY08bibQO/bSCGO7jWMlre8GRmQIS39GRHxNubXSjizsgBNf@nixNDKsYo@i1T7TnrpuCOamUXTyApK1ahNln2f2Jo1WYRZNIFpGxZwVKA234aLMEgTIoRZo5NUD82SpE6@pPIrtDdhMomjk82xNwRirQ47tkOacIh1LOait2CP/igorsW2ZD@Yl7okXu4DSLSFHNwhV83GexYgLImCo/c@geJZuYWLLZkd126MZNKjMqJxAvWvBkdo0nymAPRnUUwG0NfPQiYdwkJYlkg89BmOAp4h1QxCepHqNFGPQAxIrdaxcPZFZbdkpU@eJTWuyXuOwp7e@bpAHzvqpbUu@Mk4c7SV9@tS3KZLpD9oC6A56udtBL01/nR8Nti3lbZz/rtfhkIVqiPGP2Hk4cTquV7txvWrtGrljXRbXtaDm7WwG5WBvSzzSXht7M@zH/Xh8LQ3otN3UuWMT/JDp9f2N//jQO6hj2YFNIvZb8fVuyV7f3QpAjGlHB3K5KbmbIY9ykxeXScuS8geb@zmQGNvF2DiEHQo2EGtQBnUwqWvnTf4Cp8vg4dRXq3SJDJxu4sjJgSEFucYXCOfqkOA14hZdfBhVNsor2h4Ut0@@092T71Suo0syq3KKgMhyKlUVp7GiX30zNVZ78d5rJdM2sr0j@M0ukDdyGZzo8NcCnhDeGGipS9QIb@C9vywPKan6XH23jh6NV6bG@nYX69t7yxtkqUFfkwUlBZlRg0dyXt5ipWolSB58N/znbs3j/1mcA7/dVQa5X/j/CU2r3qG6djpYJr14rozppR1EYsDiBp0bdPlsBd7lN2h0u22P4GHeV2twzf20vitn@q5M9LcVlGrK9326rGgsaKIutmoFo3yeC7jfzvzYJ1WVryyi7/QIrv2Kl6qEjMsyhwhRXDIG1kAvBbS0Eco7uDILztAAtS5rMWq1/o6UX5/@NQd9CxYqB0pflB@ZjClCuD5ksJu5eIAs7KYutgcwbwwopRUXdOaXc@FXUi0vLGXAhSDkxwxKhHV63Ffc7ouEaylMP@HLD58@vbv83MMD3Ouh9xe/jN79jHo9@Xmlzv725h8) (The test cases with `ialsohavealongname`/`ihavealongnameaswell` are slightly reduced in length and `s.add(x.replaceAll("~+","\\*"));` has been replaced with `{s.remove(x);s.add(x.replaceAll("~+","\\*"));}` to work in 5-10 seconds on TIO, instead of timing out after 60+ sec.) ``` import java.util.*; // Required import for List and Stack // Method with String-array and String parameters and String return-type a->f->{ var L=new Stack(); // Create a List of Lists List<String>s; // List of Strings (uninitialized) int i=999,j,k; // Three integers (`i` starting at 999, // because 260 is the maximum file-path length in Windows) for(var t:f.split("/")){ // Loop over the input file-path split by "/": s=new java.util.concurrent.CopyOnWriteArrayList(); // Create a List (which we can modify while iterating it) s.add(t); // Add the input to this List for(k=1;k>0;){ // Loop as long as there are new items added to the List k=0; // Reset the newAdded-flag to false for(var x:s) // And inner loop over the List for(j=0;j<t.length();) // Inner loop `j` in range [0,length-of-item): if(!s.contains(f=x.substring(0,j)+"~"+x.substring(++j))){ // Replace the character at index `j` with a '~' // And if it's a new item: s.add(f); // Add it to the List k=1;}} // And set the newAdded-flag to true for(var x:s) // Loop over the List again s.add(x.replaceAll("~+","\\*"))); // And replace all 1 or more '~' with a single asterisk // (NOTE: To reduce bytes it doesn't remove the existing items) L.add(s);} // Add this List to the List of Lists p(L,s=new Stack(),0,""); // Generate all permutations of the groppings // (List `s` now contains all groppings of the given file-path) for(var y:s){ // Loop over the groppings in the String-List: k=0; // Reset integer `k` to 0 for(var x:a) // Inner loop over the input file-paths: if(x.matches(y.replace("*",".*")) // If the current file-path matches the current gropping x.split("/").length==y.split("/").length) // and the amount of slashes are the same: k++; // Increase integer `k` by 1 if(k==1 // If only one of the file-paths matched, &(j=y.length())<i){ // and the length is shorter than `i`: f=y; // Replace the result with this gropping file-path i=j;}} // And also replace `i` with this shorter `j` return f;} // Finally return this shortest gropping file-path // Separated method to generate gropping file-path permutations given a List of Lists void p(List L,List r,int d,String c){ if(d==L.size()) // If we've reached the final depth r.add(c); // Add the current gropping-file path to the result-List else // Else: for(var o:(List)L.get(d)) // Loop over the List of the current depth: p(L,r,d+1, // Recursive call with depth+1, c+"/"+o);} // and current + "/" + item of loop ``` **Additional general explanation:** Example: Let's take `/foo, /foo/bar, /foo/barber, /foo/bar/test, /foo/barber/test, /foo/barber/testing, /foo/barber/coding, /foo/test` as given file-paths, and `foo/bar/test` as input file-path to grop. 1) I start by splitting the file-path input by `/`, and generate all file-groppings of these separated words: ``` foo: [foo, *oo, f*o, fo*, *o, *o*, f*, *] bar: [bar, *ar, b*r, ba*, *r, *a*, b*, *] test: [test, *est, t*st, te*t, tes*, *st, *e*t, *es*, t*t, t*s*, te*, *t, *s*, *e*, t*, *] ``` 2) I then generate all permutations with these words in the same order (reapplying the `/` in between and at the front): ``` [/foo/bar/test, /foo/bar/*est, /foo/bar/t*st, /foo/bar/te*t, /foo/bar/tes*, /foo/bar/*st, /foo/bar/*e*t, /foo/bar/*es*, /foo/bar/t*t, /foo/bar/t*s*, /foo/bar/te*, /foo/bar/*t, /foo/bar/*s*, /foo/bar/*e*, /foo/bar/t*, /foo/bar/*, /foo/*ar/test, /foo/*ar/*est, /foo/*ar/t*st, /foo/*ar/te*t, /foo/*ar/tes*, /foo/*ar/*st, /foo/*ar/*e*t, /foo/*ar/*es*, /foo/*ar/t*t, /foo/*ar/t*s*, /foo/*ar/te*, /foo/*ar/*t, /foo/*ar/*s*, /foo/*ar/*e*, /foo/*ar/t*, /foo/*ar/*, /foo/b*r/test, /foo/b*r/*est, /foo/b*r/t*st, /foo/b*r/te*t, /foo/b*r/tes*, /foo/b*r/*st, /foo/b*r/*e*t, /foo/b*r/*es*, /foo/b*r/t*t, /foo/b*r/t*s*, /foo/b*r/te*, /foo/b*r/*t, /foo/b*r/*s*, /foo/b*r/*e*, /foo/b*r/t*, /foo/b*r/*, /foo/ba*/test, /foo/ba*/*est, /foo/ba*/t*st, /foo/ba*/te*t, /foo/ba*/tes*, /foo/ba*/*st, /foo/ba*/*e*t, /foo/ba*/*es*, /foo/ba*/t*t, /foo/ba*/t*s*, /foo/ba*/te*, /foo/ba*/*t, /foo/ba*/*s*, /foo/ba*/*e*, /foo/ba*/t*, /foo/ba*/*, /foo/*r/test, /foo/*r/*est, /foo/*r/t*st, /foo/*r/te*t, /foo/*r/tes*, /foo/*r/*st, /foo/*r/*e*t, /foo/*r/*es*, /foo/*r/t*t, /foo/*r/t*s*, /foo/*r/te*, /foo/*r/*t, /foo/*r/*s*, /foo/*r/*e*, /foo/*r/t*, /foo/*r/*, /foo/*a*/test, /foo/*a*/*est, /foo/*a*/t*st, /foo/*a*/te*t, /foo/*a*/tes*, /foo/*a*/*st, /foo/*a*/*e*t, /foo/*a*/*es*, /foo/*a*/t*t, /foo/*a*/t*s*, /foo/*a*/te*, /foo/*a*/*t, /foo/*a*/*s*, /foo/*a*/*e*, /foo/*a*/t*, /foo/*a*/*, /foo/b*/test, /foo/b*/*est, /foo/b*/t*st, /foo/b*/te*t, /foo/b*/tes*, /foo/b*/*st, /foo/b*/*e*t, /foo/b*/*es*, /foo/b*/t*t, /foo/b*/t*s*, /foo/b*/te*, /foo/b*/*t, /foo/b*/*s*, /foo/b*/*e*, /foo/b*/t*, /foo/b*/*, /foo/*/test, /foo/*/*est, /foo/*/t*st, /foo/*/te*t, /foo/*/tes*, /foo/*/*st, /foo/*/*e*t, /foo/*/*es*, /foo/*/t*t, /foo/*/t*s*, /foo/*/te*, /foo/*/*t, /foo/*/*s*, /foo/*/*e*, /foo/*/t*, /foo/*/*, /*oo/bar/test, /*oo/bar/*est, /*oo/bar/t*st, /*oo/bar/te*t, /*oo/bar/tes*, /*oo/bar/*st, /*oo/bar/*e*t, /*oo/bar/*es*, /*oo/bar/t*t, /*oo/bar/t*s*, /*oo/bar/te*, /*oo/bar/*t, /*oo/bar/*s*, /*oo/bar/*e*, /*oo/bar/t*, /*oo/bar/*, /*oo/*ar/test, /*oo/*ar/*est, /*oo/*ar/t*st, /*oo/*ar/te*t, /*oo/*ar/tes*, /*oo/*ar/*st, /*oo/*ar/*e*t, /*oo/*ar/*es*, /*oo/*ar/t*t, /*oo/*ar/t*s*, /*oo/*ar/te*, /*oo/*ar/*t, /*oo/*ar/*s*, /*oo/*ar/*e*, /*oo/*ar/t*, /*oo/*ar/*, /*oo/b*r/test, /*oo/b*r/*est, /*oo/b*r/t*st, /*oo/b*r/te*t, /*oo/b*r/tes*, /*oo/b*r/*st, /*oo/b*r/*e*t, /*oo/b*r/*es*, /*oo/b*r/t*t, /*oo/b*r/t*s*, /*oo/b*r/te*, /*oo/b*r/*t, /*oo/b*r/*s*, /*oo/b*r/*e*, /*oo/b*r/t*, /*oo/b*r/*, /*oo/ba*/test, /*oo/ba*/*est, /*oo/ba*/t*st, /*oo/ba*/te*t, /*oo/ba*/tes*, /*oo/ba*/*st, /*oo/ba*/*e*t, /*oo/ba*/*es*, /*oo/ba*/t*t, /*oo/ba*/t*s*, /*oo/ba*/te*, /*oo/ba*/*t, /*oo/ba*/*s*, /*oo/ba*/*e*, /*oo/ba*/t*, /*oo/ba*/*, /*oo/*r/test, /*oo/*r/*est, /*oo/*r/t*st, /*oo/*r/te*t, /*oo/*r/tes*, /*oo/*r/*st, /*oo/*r/*e*t, /*oo/*r/*es*, /*oo/*r/t*t, /*oo/*r/t*s*, /*oo/*r/te*, /*oo/*r/*t, /*oo/*r/*s*, /*oo/*r/*e*, /*oo/*r/t*, /*oo/*r/*, /*oo/*a*/test, /*oo/*a*/*est, /*oo/*a*/t*st, /*oo/*a*/te*t, /*oo/*a*/tes*, /*oo/*a*/*st, /*oo/*a*/*e*t, /*oo/*a*/*es*, /*oo/*a*/t*t, /*oo/*a*/t*s*, /*oo/*a*/te*, /*oo/*a*/*t, /*oo/*a*/*s*, /*oo/*a*/*e*, /*oo/*a*/t*, /*oo/*a*/*, /*oo/b*/test, /*oo/b*/*est, /*oo/b*/t*st, /*oo/b*/te*t, /*oo/b*/tes*, /*oo/b*/*st, /*oo/b*/*e*t, /*oo/b*/*es*, /*oo/b*/t*t, /*oo/b*/t*s*, /*oo/b*/te*, /*oo/b*/*t, /*oo/b*/*s*, /*oo/b*/*e*, /*oo/b*/t*, /*oo/b*/*, /*oo/*/test, /*oo/*/*est, /*oo/*/t*st, /*oo/*/te*t, /*oo/*/tes*, /*oo/*/*st, /*oo/*/*e*t, /*oo/*/*es*, /*oo/*/t*t, /*oo/*/t*s*, /*oo/*/te*, /*oo/*/*t, /*oo/*/*s*, /*oo/*/*e*, /*oo/*/t*, /*oo/*/*, /f*o/bar/test, /f*o/bar/*est, /f*o/bar/t*st, /f*o/bar/te*t, /f*o/bar/tes*, /f*o/bar/*st, /f*o/bar/*e*t, /f*o/bar/*es*, /f*o/bar/t*t, /f*o/bar/t*s*, /f*o/bar/te*, /f*o/bar/*t, /f*o/bar/*s*, /f*o/bar/*e*, /f*o/bar/t*, /f*o/bar/*, /f*o/*ar/test, /f*o/*ar/*est, /f*o/*ar/t*st, /f*o/*ar/te*t, /f*o/*ar/tes*, /f*o/*ar/*st, /f*o/*ar/*e*t, /f*o/*ar/*es*, /f*o/*ar/t*t, /f*o/*ar/t*s*, /f*o/*ar/te*, /f*o/*ar/*t, /f*o/*ar/*s*, /f*o/*ar/*e*, /f*o/*ar/t*, /f*o/*ar/*, /f*o/b*r/test, /f*o/b*r/*est, /f*o/b*r/t*st, /f*o/b*r/te*t, /f*o/b*r/tes*, /f*o/b*r/*st, /f*o/b*r/*e*t, /f*o/b*r/*es*, /f*o/b*r/t*t, /f*o/b*r/t*s*, /f*o/b*r/te*, /f*o/b*r/*t, /f*o/b*r/*s*, /f*o/b*r/*e*, /f*o/b*r/t*, /f*o/b*r/*, /f*o/ba*/test, /f*o/ba*/*est, /f*o/ba*/t*st, /f*o/ba*/te*t, /f*o/ba*/tes*, /f*o/ba*/*st, /f*o/ba*/*e*t, /f*o/ba*/*es*, /f*o/ba*/t*t, /f*o/ba*/t*s*, /f*o/ba*/te*, /f*o/ba*/*t, /f*o/ba*/*s*, /f*o/ba*/*e*, /f*o/ba*/t*, /f*o/ba*/*, /f*o/*r/test, /f*o/*r/*est, /f*o/*r/t*st, /f*o/*r/te*t, /f*o/*r/tes*, /f*o/*r/*st, /f*o/*r/*e*t, /f*o/*r/*es*, /f*o/*r/t*t, /f*o/*r/t*s*, /f*o/*r/te*, /f*o/*r/*t, /f*o/*r/*s*, /f*o/*r/*e*, /f*o/*r/t*, /f*o/*r/*, /f*o/*a*/test, /f*o/*a*/*est, /f*o/*a*/t*st, /f*o/*a*/te*t, /f*o/*a*/tes*, /f*o/*a*/*st, /f*o/*a*/*e*t, /f*o/*a*/*es*, /f*o/*a*/t*t, /f*o/*a*/t*s*, /f*o/*a*/te*, /f*o/*a*/*t, /f*o/*a*/*s*, /f*o/*a*/*e*, /f*o/*a*/t*, /f*o/*a*/*, /f*o/b*/test, /f*o/b*/*est, /f*o/b*/t*st, /f*o/b*/te*t, /f*o/b*/tes*, /f*o/b*/*st, /f*o/b*/*e*t, /f*o/b*/*es*, /f*o/b*/t*t, /f*o/b*/t*s*, /f*o/b*/te*, /f*o/b*/*t, /f*o/b*/*s*, /f*o/b*/*e*, /f*o/b*/t*, /f*o/b*/*, /f*o/*/test, /f*o/*/*est, /f*o/*/t*st, /f*o/*/te*t, /f*o/*/tes*, /f*o/*/*st, /f*o/*/*e*t, /f*o/*/*es*, /f*o/*/t*t, /f*o/*/t*s*, /f*o/*/te*, /f*o/*/*t, /f*o/*/*s*, /f*o/*/*e*, /f*o/*/t*, /f*o/*/*, /fo*/bar/test, /fo*/bar/*est, /fo*/bar/t*st, /fo*/bar/te*t, /fo*/bar/tes*, /fo*/bar/*st, /fo*/bar/*e*t, /fo*/bar/*es*, /fo*/bar/t*t, /fo*/bar/t*s*, /fo*/bar/te*, /fo*/bar/*t, /fo*/bar/*s*, /fo*/bar/*e*, /fo*/bar/t*, /fo*/bar/*, /fo*/*ar/test, /fo*/*ar/*est, /fo*/*ar/t*st, /fo*/*ar/te*t, /fo*/*ar/tes*, /fo*/*ar/*st, /fo*/*ar/*e*t, /fo*/*ar/*es*, /fo*/*ar/t*t, /fo*/*ar/t*s*, /fo*/*ar/te*, /fo*/*ar/*t, /fo*/*ar/*s*, /fo*/*ar/*e*, /fo*/*ar/t*, /fo*/*ar/*, /fo*/b*r/test, /fo*/b*r/*est, /fo*/b*r/t*st, /fo*/b*r/te*t, /fo*/b*r/tes*, /fo*/b*r/*st, /fo*/b*r/*e*t, /fo*/b*r/*es*, /fo*/b*r/t*t, /fo*/b*r/t*s*, /fo*/b*r/te*, /fo*/b*r/*t, /fo*/b*r/*s*, /fo*/b*r/*e*, /fo*/b*r/t*, /fo*/b*r/*, /fo*/ba*/test, /fo*/ba*/*est, /fo*/ba*/t*st, /fo*/ba*/te*t, /fo*/ba*/tes*, /fo*/ba*/*st, /fo*/ba*/*e*t, /fo*/ba*/*es*, /fo*/ba*/t*t, /fo*/ba*/t*s*, /fo*/ba*/te*, /fo*/ba*/*t, /fo*/ba*/*s*, /fo*/ba*/*e*, /fo*/ba*/t*, /fo*/ba*/*, /fo*/*r/test, /fo*/*r/*est, /fo*/*r/t*st, /fo*/*r/te*t, /fo*/*r/tes*, /fo*/*r/*st, /fo*/*r/*e*t, /fo*/*r/*es*, /fo*/*r/t*t, /fo*/*r/t*s*, /fo*/*r/te*, /fo*/*r/*t, /fo*/*r/*s*, /fo*/*r/*e*, /fo*/*r/t*, /fo*/*r/*, /fo*/*a*/test, /fo*/*a*/*est, /fo*/*a*/t*st, /fo*/*a*/te*t, /fo*/*a*/tes*, /fo*/*a*/*st, /fo*/*a*/*e*t, /fo*/*a*/*es*, /fo*/*a*/t*t, /fo*/*a*/t*s*, /fo*/*a*/te*, /fo*/*a*/*t, /fo*/*a*/*s*, /fo*/*a*/*e*, /fo*/*a*/t*, /fo*/*a*/*, /fo*/b*/test, /fo*/b*/*est, /fo*/b*/t*st, /fo*/b*/te*t, /fo*/b*/tes*, /fo*/b*/*st, /fo*/b*/*e*t, /fo*/b*/*es*, /fo*/b*/t*t, /fo*/b*/t*s*, /fo*/b*/te*, /fo*/b*/*t, /fo*/b*/*s*, /fo*/b*/*e*, /fo*/b*/t*, /fo*/b*/*, /fo*/*/test, /fo*/*/*est, /fo*/*/t*st, /fo*/*/te*t, /fo*/*/tes*, /fo*/*/*st, /fo*/*/*e*t, /fo*/*/*es*, /fo*/*/t*t, /fo*/*/t*s*, /fo*/*/te*, /fo*/*/*t, /fo*/*/*s*, /fo*/*/*e*, /fo*/*/t*, /fo*/*/*, /*o/bar/test, /*o/bar/*est, /*o/bar/t*st, /*o/bar/te*t, /*o/bar/tes*, /*o/bar/*st, /*o/bar/*e*t, /*o/bar/*es*, /*o/bar/t*t, /*o/bar/t*s*, /*o/bar/te*, /*o/bar/*t, /*o/bar/*s*, /*o/bar/*e*, /*o/bar/t*, /*o/bar/*, /*o/*ar/test, /*o/*ar/*est, /*o/*ar/t*st, /*o/*ar/te*t, /*o/*ar/tes*, /*o/*ar/*st, /*o/*ar/*e*t, /*o/*ar/*es*, /*o/*ar/t*t, /*o/*ar/t*s*, /*o/*ar/te*, /*o/*ar/*t, /*o/*ar/*s*, /*o/*ar/*e*, /*o/*ar/t*, /*o/*ar/*, /*o/b*r/test, /*o/b*r/*est, /*o/b*r/t*st, /*o/b*r/te*t, /*o/b*r/tes*, /*o/b*r/*st, /*o/b*r/*e*t, /*o/b*r/*es*, /*o/b*r/t*t, /*o/b*r/t*s*, /*o/b*r/te*, /*o/b*r/*t, /*o/b*r/*s*, /*o/b*r/*e*, /*o/b*r/t*, /*o/b*r/*, /*o/ba*/test, /*o/ba*/*est, /*o/ba*/t*st, /*o/ba*/te*t, /*o/ba*/tes*, /*o/ba*/*st, /*o/ba*/*e*t, /*o/ba*/*es*, /*o/ba*/t*t, /*o/ba*/t*s*, /*o/ba*/te*, /*o/ba*/*t, /*o/ba*/*s*, /*o/ba*/*e*, /*o/ba*/t*, /*o/ba*/*, /*o/*r/test, /*o/*r/*est, /*o/*r/t*st, /*o/*r/te*t, /*o/*r/tes*, /*o/*r/*st, /*o/*r/*e*t, /*o/*r/*es*, /*o/*r/t*t, /*o/*r/t*s*, /*o/*r/te*, /*o/*r/*t, /*o/*r/*s*, /*o/*r/*e*, /*o/*r/t*, /*o/*r/*, /*o/*a*/test, /*o/*a*/*est, /*o/*a*/t*st, /*o/*a*/te*t, /*o/*a*/tes*, /*o/*a*/*st, /*o/*a*/*e*t, /*o/*a*/*es*, /*o/*a*/t*t, /*o/*a*/t*s*, /*o/*a*/te*, /*o/*a*/*t, /*o/*a*/*s*, /*o/*a*/*e*, /*o/*a*/t*, /*o/*a*/*, /*o/b*/test, /*o/b*/*est, /*o/b*/t*st, /*o/b*/te*t, /*o/b*/tes*, /*o/b*/*st, /*o/b*/*e*t, /*o/b*/*es*, /*o/b*/t*t, /*o/b*/t*s*, /*o/b*/te*, /*o/b*/*t, /*o/b*/*s*, /*o/b*/*e*, /*o/b*/t*, /*o/b*/*, /*o/*/test, /*o/*/*est, /*o/*/t*st, /*o/*/te*t, /*o/*/tes*, /*o/*/*st, /*o/*/*e*t, /*o/*/*es*, /*o/*/t*t, /*o/*/t*s*, /*o/*/te*, /*o/*/*t, /*o/*/*s*, /*o/*/*e*, /*o/*/t*, /*o/*/*, /*o*/bar/test, /*o*/bar/*est, /*o*/bar/t*st, /*o*/bar/te*t, /*o*/bar/tes*, /*o*/bar/*st, /*o*/bar/*e*t, /*o*/bar/*es*, /*o*/bar/t*t, /*o*/bar/t*s*, /*o*/bar/te*, /*o*/bar/*t, /*o*/bar/*s*, /*o*/bar/*e*, /*o*/bar/t*, /*o*/bar/*, /*o*/*ar/test, /*o*/*ar/*est, /*o*/*ar/t*st, /*o*/*ar/te*t, /*o*/*ar/tes*, /*o*/*ar/*st, /*o*/*ar/*e*t, /*o*/*ar/*es*, /*o*/*ar/t*t, /*o*/*ar/t*s*, /*o*/*ar/te*, /*o*/*ar/*t, /*o*/*ar/*s*, /*o*/*ar/*e*, /*o*/*ar/t*, /*o*/*ar/*, /*o*/b*r/test, /*o*/b*r/*est, /*o*/b*r/t*st, /*o*/b*r/te*t, /*o*/b*r/tes*, /*o*/b*r/*st, /*o*/b*r/*e*t, /*o*/b*r/*es*, /*o*/b*r/t*t, /*o*/b*r/t*s*, /*o*/b*r/te*, /*o*/b*r/*t, /*o*/b*r/*s*, /*o*/b*r/*e*, /*o*/b*r/t*, /*o*/b*r/*, /*o*/ba*/test, /*o*/ba*/*est, /*o*/ba*/t*st, /*o*/ba*/te*t, /*o*/ba*/tes*, /*o*/ba*/*st, /*o*/ba*/*e*t, /*o*/ba*/*es*, /*o*/ba*/t*t, /*o*/ba*/t*s*, /*o*/ba*/te*, /*o*/ba*/*t, /*o*/ba*/*s*, /*o*/ba*/*e*, /*o*/ba*/t*, /*o*/ba*/*, /*o*/*r/test, /*o*/*r/*est, /*o*/*r/t*st, /*o*/*r/te*t, /*o*/*r/tes*, /*o*/*r/*st, /*o*/*r/*e*t, /*o*/*r/*es*, /*o*/*r/t*t, /*o*/*r/t*s*, /*o*/*r/te*, /*o*/*r/*t, /*o*/*r/*s*, /*o*/*r/*e*, /*o*/*r/t*, /*o*/*r/*, /*o*/*a*/test, /*o*/*a*/*est, /*o*/*a*/t*st, /*o*/*a*/te*t, /*o*/*a*/tes*, /*o*/*a*/*st, /*o*/*a*/*e*t, /*o*/*a*/*es*, /*o*/*a*/t*t, /*o*/*a*/t*s*, /*o*/*a*/te*, /*o*/*a*/*t, /*o*/*a*/*s*, /*o*/*a*/*e*, /*o*/*a*/t*, /*o*/*a*/*, /*o*/b*/test, /*o*/b*/*est, /*o*/b*/t*st, /*o*/b*/te*t, /*o*/b*/tes*, /*o*/b*/*st, /*o*/b*/*e*t, /*o*/b*/*es*, /*o*/b*/t*t, /*o*/b*/t*s*, /*o*/b*/te*, /*o*/b*/*t, /*o*/b*/*s*, /*o*/b*/*e*, /*o*/b*/t*, /*o*/b*/*, /*o*/*/test, /*o*/*/*est, /*o*/*/t*st, /*o*/*/te*t, /*o*/*/tes*, /*o*/*/*st, /*o*/*/*e*t, /*o*/*/*es*, /*o*/*/t*t, /*o*/*/t*s*, /*o*/*/te*, /*o*/*/*t, /*o*/*/*s*, /*o*/*/*e*, /*o*/*/t*, /*o*/*/*, /f*/bar/test, /f*/bar/*est, /f*/bar/t*st, /f*/bar/te*t, /f*/bar/tes*, /f*/bar/*st, /f*/bar/*e*t, /f*/bar/*es*, /f*/bar/t*t, /f*/bar/t*s*, /f*/bar/te*, /f*/bar/*t, /f*/bar/*s*, /f*/bar/*e*, /f*/bar/t*, /f*/bar/*, /f*/*ar/test, /f*/*ar/*est, /f*/*ar/t*st, /f*/*ar/te*t, /f*/*ar/tes*, /f*/*ar/*st, /f*/*ar/*e*t, /f*/*ar/*es*, /f*/*ar/t*t, /f*/*ar/t*s*, /f*/*ar/te*, /f*/*ar/*t, /f*/*ar/*s*, /f*/*ar/*e*, /f*/*ar/t*, /f*/*ar/*, /f*/b*r/test, /f*/b*r/*est, /f*/b*r/t*st, /f*/b*r/te*t, /f*/b*r/tes*, /f*/b*r/*st, /f*/b*r/*e*t, /f*/b*r/*es*, /f*/b*r/t*t, /f*/b*r/t*s*, /f*/b*r/te*, /f*/b*r/*t, /f*/b*r/*s*, /f*/b*r/*e*, /f*/b*r/t*, /f*/b*r/*, /f*/ba*/test, /f*/ba*/*est, /f*/ba*/t*st, /f*/ba*/te*t, /f*/ba*/tes*, /f*/ba*/*st, /f*/ba*/*e*t, /f*/ba*/*es*, /f*/ba*/t*t, /f*/ba*/t*s*, /f*/ba*/te*, /f*/ba*/*t, /f*/ba*/*s*, /f*/ba*/*e*, /f*/ba*/t*, /f*/ba*/*, /f*/*r/test, /f*/*r/*est, /f*/*r/t*st, /f*/*r/te*t, /f*/*r/tes*, /f*/*r/*st, /f*/*r/*e*t, /f*/*r/*es*, /f*/*r/t*t, /f*/*r/t*s*, /f*/*r/te*, /f*/*r/*t, /f*/*r/*s*, /f*/*r/*e*, /f*/*r/t*, /f*/*r/*, /f*/*a*/test, /f*/*a*/*est, /f*/*a*/t*st, /f*/*a*/te*t, /f*/*a*/tes*, /f*/*a*/*st, /f*/*a*/*e*t, /f*/*a*/*es*, /f*/*a*/t*t, /f*/*a*/t*s*, /f*/*a*/te*, /f*/*a*/*t, /f*/*a*/*s*, /f*/*a*/*e*, /f*/*a*/t*, /f*/*a*/*, /f*/b*/test, /f*/b*/*est, /f*/b*/t*st, /f*/b*/te*t, /f*/b*/tes*, /f*/b*/*st, /f*/b*/*e*t, /f*/b*/*es*, /f*/b*/t*t, /f*/b*/t*s*, /f*/b*/te*, /f*/b*/*t, /f*/b*/*s*, /f*/b*/*e*, /f*/b*/t*, /f*/b*/*, /f*/*/test, /f*/*/*est, /f*/*/t*st, /f*/*/te*t, /f*/*/tes*, /f*/*/*st, /f*/*/*e*t, /f*/*/*es*, /f*/*/t*t, /f*/*/t*s*, /f*/*/te*, /f*/*/*t, /f*/*/*s*, /f*/*/*e*, /f*/*/t*, /f*/*/*, /*/bar/test, /*/bar/*est, /*/bar/t*st, /*/bar/te*t, /*/bar/tes*, /*/bar/*st, /*/bar/*e*t, /*/bar/*es*, /*/bar/t*t, /*/bar/t*s*, /*/bar/te*, /*/bar/*t, /*/bar/*s*, /*/bar/*e*, /*/bar/t*, /*/bar/*, /*/*ar/test, /*/*ar/*est, /*/*ar/t*st, /*/*ar/te*t, /*/*ar/tes*, /*/*ar/*st, /*/*ar/*e*t, /*/*ar/*es*, /*/*ar/t*t, /*/*ar/t*s*, /*/*ar/te*, /*/*ar/*t, /*/*ar/*s*, /*/*ar/*e*, /*/*ar/t*, /*/*ar/*, /*/b*r/test, /*/b*r/*est, /*/b*r/t*st, /*/b*r/te*t, /*/b*r/tes*, /*/b*r/*st, /*/b*r/*e*t, /*/b*r/*es*, /*/b*r/t*t, /*/b*r/t*s*, /*/b*r/te*, /*/b*r/*t, /*/b*r/*s*, /*/b*r/*e*, /*/b*r/t*, /*/b*r/*, /*/ba*/test, /*/ba*/*est, /*/ba*/t*st, /*/ba*/te*t, /*/ba*/tes*, /*/ba*/*st, /*/ba*/*e*t, /*/ba*/*es*, /*/ba*/t*t, /*/ba*/t*s*, /*/ba*/te*, /*/ba*/*t, /*/ba*/*s*, /*/ba*/*e*, /*/ba*/t*, /*/ba*/*, /*/*r/test, /*/*r/*est, /*/*r/t*st, /*/*r/te*t, /*/*r/tes*, /*/*r/*st, /*/*r/*e*t, /*/*r/*es*, /*/*r/t*t, /*/*r/t*s*, /*/*r/te*, /*/*r/*t, /*/*r/*s*, /*/*r/*e*, /*/*r/t*, /*/*r/*, /*/*a*/test, /*/*a*/*est, /*/*a*/t*st, /*/*a*/te*t, /*/*a*/tes*, /*/*a*/*st, /*/*a*/*e*t, /*/*a*/*es*, /*/*a*/t*t, /*/*a*/t*s*, /*/*a*/te*, /*/*a*/*t, /*/*a*/*s*, /*/*a*/*e*, /*/*a*/t*, /*/*a*/*, /*/b*/test, /*/b*/*est, /*/b*/t*st, /*/b*/te*t, /*/b*/tes*, /*/b*/*st, /*/b*/*e*t, /*/b*/*es*, /*/b*/t*t, /*/b*/t*s*, /*/b*/te*, /*/b*/*t, /*/b*/*s*, /*/b*/*e*, /*/b*/t*, /*/b*/*, /*/*/test, /*/*/*est, /*/*/t*st, /*/*/te*t, /*/*/tes*, /*/*/*st, /*/*/*e*t, /*/*/*es*, /*/*/t*t, /*/*/t*s*, /*/*/te*, /*/*/*t, /*/*/*s*, /*/*/*e*, /*/*/t*, /*/*/*] ``` 3) Then I loop over the items in this list above and validate if it only matches a single file-path in the input array of file-paths. (I do this by checking two things: are the amount of slashes the same, and does it match the regex where every `*` is replaced with `.*`.) If it does: keep the (first) shortest, which we return in the end. ]
[Question] [ The task is simple, given two IP adresses `a` and `b`, output all addresses within that range. --- # Examples Example #1: ``` f(a = 192.168.0.1, b = 192.168.0.4) 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 ``` Example #2 (TIO will truncate this, use a smaller range when testing): ``` f (a = 123.0.200.0, b = 124.0.0.0) 123.0.200.0 123.0.200.1 ... # Omitted pattern 123.0.200.255 123.0.201.0 ... # Omitted pattern 123.0.201.255 ... # Omitted pattern 123.0.255.255 123.1.0.0 ... # Omitted pattern 123.255.255.255 124.0.0.0 ``` # Input and Output * `a < b` in other words: + **Defined Programatically**: `a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]) || (a[0:1] == b[0:1] && a[2] < b[2]) || (a[0:2] == b[0:2] && a[3] < b[3])` + **Defined in Words:** `a` will always be lower than `b` (so you will have to increment the subnet to reach `b`). + No, you ***do not*** have to handle `a == b` (if you do, kudos). * Output should be in order from "lowest" to "highest" (see examples). * For this challenge, the valid syntax for an IP is: `\d{1-3}\.\d{1-3}\.\d{1-3}\.\d{1-3}`. * You do not have to handle non-IP address input, if it's unexpected input you may error. * Output may be as an array or as a delimited string (using any whitespace character). # Winning * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. [Answer] # Pyth, 22 ``` mj\.jd256}FmivMcd\.256 ``` [Try it online](https://tio.run/##K6gsyfj/PzcrRi8rxcjUrNYtN7PMNzklRg/I@f8/Wt3Q0kjP0MxCz0DPUF1HAc410TNRjwUA). ``` cd\. # split string by "." vM # eval list (convert strings to integers) i 256 # convert list of base256 digits to integer m Q # map the above over implicit input list }F # inclusive range jd256 # convert to list of base256 digits j\. # join by "." m # map over inclusive range ``` [Answer] ## Batch, 623 bytes ``` @echo off set s=%1.%2 call:c %s:.= % exit/b :c if %1==%5 goto d call:d %1 %2 %3 %4 %1 255 255 255 set/al=%1+1,u=%5-1 for /l %%i in (%l%,1,%u%)do call:d %%i 0 0 0 %%i 255 255 255 call:d %5 0 0 0 %5 %6 %7 %8 exit/b :d if %2==%6 goto e call:e %1 %2 %3 %4 %1 %2 255 255 set/al=%2+1,u=%6-1 for /l %%j in (%l%,1,%u%)do call:e %1 %%j 0 0 %5 %%j 255 255 call:e %5 %6 0 0 %5 %6 %7 %8 exit/b :e if %3==%7 goto f call:f %1 %2 %3 %4 %1 %2 %3 255 set/al=%3+1,u=%7-1 for /l %%k in (%l%,1,%u%)do call:e %1 %2 %%k 0 %5 %6 %%k 255 call:e %5 %6 %7 0 %5 %6 %7 %8 exit/b :f for /l %%l in (%4,1,%8)do echo %1.%2.%3.%%l ``` Unfortunately Batch's 32-bit arithmetic can't print all IP addresses, so I have to split it up into octets. [Answer] # [Python 2](https://docs.python.org/2/), 128 bytes ``` a,b=[reduce(lambda a,b:a<<8|int(b),x.split('.'),0)for x in input()] while a<=b:print'.'.join(`a>>i&255`for i in[24,16,8,0]);a+=1 ``` [Try it online!](https://tio.run/##JYvRCoIwGIXve4pdtY1@xlxaZuqLiOBWhgubwyYZ9O7rjzjn3Hycz7/DMDkVowZTNXN/XS49G/XDXDVBVOiyzD/WBWY4rOLpRxsYFZSD5LdpJiuxDuuXwHi7eQ127IkuK1P4GSU8ivtkHet0XdutyrLuJ1k0GpVCcoAcZMvPelclMdLkpAR@/kslBSR7ITFH@gU "Python 2 – Try It Online") [Answer] # PHP, 71 Bytes Output as string ``` for($s=ip2long($argv[1]);$s<=ip2long($argv[2]);)echo long2ip($s++)," "; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFSKbTMLjHLy89I1VBKL0suiDWM1rVWKbdBEjYCimqnJGfkKIEGjzAKgRm1tTR0lBSXr////G1oa6RmaWegZ6BmZGsB5hnomAA "PHP – Try It Online") or Output as array ``` print_r(array_map(long2ip,range(ip2long($argv[1]),ip2long($argv[2])))); ``` [Try it online!](https://tio.run/##K8go@G9jXwAkC4oy80riizQSi4oSK@NzEws0cvLz0o0yC3SKEvPSUzUyC4xAAhoqiUXpZdGGsZo6qCJGsZpAYP3//39DSyM9QzMLPQM9I1MDOM9QzwQA "PHP – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ṣ”.V€ḅ⁹µ€r/b⁹j”.$€ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGubqhT1qWvNwR@ujxp2HtgKZRfpJQGYWSEYFyP3//7@SoZ6hnpGekZKOEog21jNRAgA "Jelly – Try It Online") The output appears to by a mush of digits and decimals, but is stored internally as a list of strings. Append a `Y` to the end (+1 byte) to join the strings by newlines. **How it Works** ``` ṣ”.V€ḅ⁹µ€r/b⁹j”.$€ - main link, input is a list of addresses which are strings µ€ - for each address string, ṣ”. - split on periods V€ - eval each element in the list (convert strings to numbers) ḅ⁹ - transform from base 256 to integer (⁹ is 256) r/ - take the inclusive range b⁹ - convert each element in the range from integer to base 256 j”.$€ - join each address with periods. ``` [Answer] # JavaScript (ES6), 104 bytes ``` g=s=>s.replace(/(\d+)\.256/,(_,n)=>++n+'.0') f=(a,b)=>a==b?a:a+` `+f(g(g(g(g(a+'.256').slice(0,-2)))),b) ``` This solution replaces the pattern **n**.256 with **n+1**.0, and it calls itself recursively until the two parameters are equal. It appends '.256' to the initial input to get the ball rolling. `slice(0,-2)` is then used to remove the trailing '.0'. **Examples:** ``` g=s=>s.replace(/(\d+)\.256/,(_,n)=>++n+'.0') f=(a,b)=>a==b?a:a+` `+f(g(g(g(g(a+'.256').slice(0,-2)))),b) console.log('192.168.0.1 ... 192.168.0.4'); console.log(f('192.168.0.1', '192.168.0.4')); console.log('123.255.255.0 ... 124.0.3.0'); console.log(f('123.255.255.0', '124.0.3.0')); console.log('192.1.1.1 ... 192.1.1.1 ... kudos'); console.log(f('192.1.1.1', '192.1.1.1')); ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~339~~ ~~314~~ 282 bytes Golfed: ``` long f(String i)throws Exception{return java.nio.ByteBuffer.wrap(java.net.InetAddress.getByName(i).getAddress()).getInt()&(1L<<32)-1;}void g(String[] a)throws Exception{for(long l=f(a[0]),m=255;l<=f(a[1]);)System.out.println(((l>>24)&m)+"."+((l>>16)&m)+"."+((l>>8)&m)+"."+(l++&m));} ``` Ungolfed: ``` long ipToLong(String ip) throws Exception { return java.nio.ByteBuffer.wrap(java.net.InetAddress.getByName(ip).getAddress()).getInt() & (1L << 32) - 1; } void printRange(String[] ips) throws Exception { for (long ip = ipToLong(ips[0]), m = 255; ip <= ipToLong(ips[1]);) System.out.println(((ip >> 24) & m) + "." + ((ip >> 16) & m) + "." + ((ip >> 8) & m) + "." + (ip++ & m)); } ``` [Try it online!](https://tio.run/##ZZBBawIxEIXv/RXBg0zYGsxWxbIqVOhBaHvxKB5SN2tjs8mSzGpF9rdv03Shtp1D8t4MDN@8gziKga2kOeTvbVW/arUjOy28J89CGXJptTV7UsAanQpCUXxz9uTJ48dOVqisuTiJtTPkEBYxoyxbnlEu66KQjp2cqOB7IJGtwvOQ5056z/YSl@cXUUpQ9Mt0faDRrQwC7QN/ms3uUjrgWXO0Kif7jmKzJeI/R2EdRFg9L0Bshlt6W87T8TjTs9jgW5rR9dmjLJmtkVVhFWoDAHqxSEe0X9Kkx3pJ9Hzy209/rE6SoGnWtCRUF5lHgeGLmGUI7pqU/EUllxvSlZGnGDSEu0HQLA6am6Zt@X3K@GTKhoxf6dEn "Java (OpenJDK 8) – Try It Online") ]
[Question] [ I have trouble remembering everything I have to do when leveling up a D&D character. For whatever reason, one of the things that gives me trouble is figuring out what their new maximum HP value should be. For this challenge, you will write a program or function to calculate the correct value automatically. # Terminology The first thing you need to know about to calculate max HP is the "Constitution modifier". Each DND character has six integer ability scores, including one for Constitution. The only relevant knowledge required for this challenge is how the Constitution ability score affects another stat, which is the Constitution modifier. In short, the modifier is equal to `floor( (ability_score - 10) / 2 )`. Adventurers can only have ability scores from 1 to 20, inclusive. Your code will never have to handle scores outside that range, which also means it will never have to handle a modifier lower than -5 or greater than +5. Though the Constitution modifier can change as a character levels up, its effects on HP are applied retroactively, so only its current value is needed to calculate current max HP. > > (This is entirely irrelevant to the challenge, but if you're curious about how it affects maximum HP: You can assume the "Tough" feat adds 2 to a character's Constitution modifier for the purposes of HP calculation, since that's *effectively* what it does. That's not the text of the feat but the math works out to be exactly the same. You don't have to handle this feat in your answer.) > > > Next, every class has an assigned "hit die" type, which is involved in calculating HP. The following table lists the hit dice for each class. ``` Sorcerer: d6 Wizard: d6 Bard: d8 Cleric: d8 Druid: d8 Monk: d8 Rogue: d8 Warlock: d8 Fighter: d10 Paladin: d10 Ranger: d10 Barbarian: d12 ``` Finally, the character's level. All that this affects is how many times to add a value to the running total in the following section. A character's level is an integer from 1 to 20, inclusive1. Your code will never have to handle a level outside that range. To reach level `n`, a character starts at level 1 and levels up `n-1` times. For example, a level 3 character got to where they are by being a level 1 character and levelling up twice. # How to Calculate Max HP A character's maximum HP is equal to their HP at level 1 plus the sum of the increase they received at each level. ### At level 1 At level 1, a character's HP is equal to the highest possible roll on their hit die (the number in the name of the die, for those of you unfamiliar with dice that have more than 6 sides) plus their Constitution modifier. Remember that when calculating HP at a later level, you may assume a character's Constitution has always been the same, as this part of the calculation is re-done every time Constitution changes. ### When levelling up Every time a character levels up, they have two options. They may either roll one of their hit dice or take the average roll of that die (rounded up). Whichever they choose, their Constitution modifier is added to the result. This total is the amount that their HP increases. For this challenge, the average roll is always taken, so output is deterministic. (Again, if you're not familiar with >6 sided dice, you can calculate the rounded-up average roll as `(highest_possible_roll / 2) + 1`.) There is one notable exception. A character's maximum HP always increases by at least 1 each time they level up2. If the instructions in the above paragraph would result in an increase of 0 or less when leveling up, it increases by 1 instead. # The Challenge Your program or function will take three [inputs](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods): * The character's class, as a string * The character's level * The character's Constitution ability score (*not* modifier) It will [output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) only one thing: The character's current maximum HP. # Examples [Every possible combination of inputs and their associated outputs can be found at this link.](https://gist.github.com/undergroundmonorail/ff39c9ea9105a2b1de7af5b57c0cb51b) For the sake of having something to look at on this page, here are 30 test cases chosen at random: ``` Barbarian, 15th level, 13 CON: 125 Rogue, 10th level, 18 CON: 93 Wizard, 15th level, 18 CON: 122 Wizard, 16th level, 1 CON: 16 Barbarian, 15th level, 7 CON: 80 Warlock, 15th level, 3 CON: 18 Ranger, 14th level, 1 CON: 18 Warlock, 3rd level, 14 CON: 24 Druid, 3rd level, 4 CON: 9 Cleric, 11th level, 5 CON: 25 Bard, 20th level, 11 CON: 103 Barbarian, 11th level, 13 CON: 93 Bard, 8th level, 19 CON: 75 Bard, 16th level, 17 CON: 131 Fighter, 10th level, 6 CON: 44 Monk, 10th level, 2 CON: 13 Cleric, 14th level, 17 CON: 115 Cleric, 6th level, 5 CON: 15 Rogue, 7th level, 13 CON: 45 Cleric, 4th level, 14 CON: 31 Rogue, 19th level, 15 CON: 136 Paladin, 13th level, 13 CON: 95 Cleric, 13th level, 15 CON: 94 Bard, 8th level, 5 CON: 19 Monk, 20th level, 11 CON: 103 Barbarian, 8th level, 20 CON: 101 Monk, 1st level, 4 CON: 5 Bard, 5th level, 17 CON: 43 Monk, 18th level, 7 CON: 57 Wizard, 17th level, 5 CON: 19 ``` --- 1. Strictly speaking, I don't think there's a rule that says 20 is the maximum level. However, 21 is the point where there stop being tables in the book to tell you what some of the various numbers in the rules should be, including the amount of experience you need to obtain to reach it. That's a good enough level cap for me. 2. I actually don't think this is true with RAW. [I asked on rpg.se](https://rpg.stackexchange.com/questions/98574/is-there-a-floor-for-maximum-hp) and such a thing doesn't appear to be written down anywhere. However, Mike Mearls, lead designer of D&D, [tweeted it in March 2015](https://twitter.com/mikemearls/status/582601826031132673). This is not authoritative the way that you could argue a tweet from lead rules developer Jeremy Crawford would be, but it is evidence that it's what they intended, so I'll use it for this challenge. [Answer] ## JavaScript (ES6), ~~81~~ ~~78~~ ~~76~~ 74 bytes Takes input as *(class, level, constitution\_ability\_score)*. The class is case-insensitive. ``` (c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2 ``` This is essentially using the same math as my initial version, but ***d*** is now computed without any lookup table. ### Test cases ``` let f = (c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2 console.log(f('Barbarian', 15, 13)) // 125 console.log(f('Rogue', 10, 18)) // 93 console.log(f('Wizard', 15, 18)) // 122 console.log(f('Wizard', 16, 1)) // 16 console.log(f('Barbarian', 15, 7)) // 80 console.log(f('Warlock', 15, 3)) // 18 console.log(f('Ranger', 14, 1)) // 18 console.log(f('Warlock', 3, 14)) // 24 console.log(f('Druid', 3, 4)) // 9 console.log(f('Cleric', 11, 5)) // 25 console.log(f('Bard', 20, 11)) // 103 console.log(f('Barbarian', 11, 13)) // 93 console.log(f('Bard', 8, 19)) // 75 console.log(f('Bard', 16, 17)) // 131 console.log(f('Fighter', 10, 6)) // 44 console.log(f('Monk', 10, 2)) // 13 console.log(f('Cleric', 14, 17)) // 115 console.log(f('Cleric', 6, 5)) // 15 console.log(f('Rogue', 7, 13)) // 45 console.log(f('Cleric', 4, 14)) // 31 console.log(f('Rogue', 19, 15)) // 136 console.log(f('Paladin', 13, 13)) // 95 console.log(f('Cleric', 13, 15)) // 94 console.log(f('Bard', 8, 5)) // 19 console.log(f('Monk', 20, 11)) // 103 console.log(f('Barbarian', 8, 20)) // 101 console.log(f('Monk', 1, 4)) // 5 console.log(f('Bard', 5, 17)) // 43 console.log(f('Monk', 18, 7)) // 57 console.log(f('Wizard', 17, 5)) // 19 ``` --- ## Initial version, ~~87~~ 84 bytes ``` (c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2 ``` ### How it works The tricky part is to convert the class string ***c*** into the corresponding hit dice. More precisely, the value that we're going to store is ***d = dice / 2 + 1***. We use the formula `parseInt(c, 35) % 24 % 15` which gives: ``` Class | Base 35 -> decimal | MOD 24 | MOD 15 | d ------------+--------------------+--------+--------+--- "Sorcerer" | 1847055419467 | 19 | 4 | 4 "Wizard" | 1138 | 10 | 10 | 4 "Bard" | 484833 | 9 | 9 | 5 "Cleric" | 662409592 | 16 | 1 | 5 "Druid" | 20703143 | 23 | 8 | 5 "Monk" | 973475 | 11 | 11 | 5 "Rogue" | 41566539 | 3 | 3 | 5 "Warlock" | 59391165840 | 0 | 0 | 5 "Fighter" | 28544153042 | 2 | 2 | 6 "Paladin" | 46513817828 | 20 | 5 | 6 "Ranger" | 1434103117 | 13 | 13 | 6 "Barbarian" | 25464249364423 | 7 | 7 | 7 ``` By inserting the values of ***d*** at the corresponding positions into a string and padding unused slots with zeros, we get: ``` 00000000001111 01234567890123 -------------- 55654607554506 ``` Hence the final formula: ``` d = +'55654607554506'[parseInt(c, 35) % 24 % 15] ``` Once we have ***d***, we compute: ``` h = d + ((s - 10) >> 1)) ``` which is the theoretical number of points that are gained at each level-up. If ***h*** is positive, we simply compute: ``` h * l ``` If not, we need to take into account the fact that at least 1 point is gained at each level-up. So we compute instead: ``` h + l - 1 ``` In both cases, we adjust the result by adding ***d - 2***, so that the initial number of points is correctly integrated. ### Test cases ``` let f = (c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2 console.log(f('Barbarian', 15, 13)) // 125 console.log(f('Rogue', 10, 18)) // 93 console.log(f('Wizard', 15, 18)) // 122 console.log(f('Wizard', 16, 1)) // 16 console.log(f('Barbarian', 15, 7)) // 80 console.log(f('Warlock', 15, 3)) // 18 console.log(f('Ranger', 14, 1)) // 18 console.log(f('Warlock', 3, 14)) // 24 console.log(f('Druid', 3, 4)) // 9 console.log(f('Cleric', 11, 5)) // 25 console.log(f('Bard', 20, 11)) // 103 console.log(f('Barbarian', 11, 13)) // 93 console.log(f('Bard', 8, 19)) // 75 console.log(f('Bard', 16, 17)) // 131 console.log(f('Fighter', 10, 6)) // 44 console.log(f('Monk', 10, 2)) // 13 console.log(f('Cleric', 14, 17)) // 115 console.log(f('Cleric', 6, 5)) // 15 console.log(f('Rogue', 7, 13)) // 45 console.log(f('Cleric', 4, 14)) // 31 console.log(f('Rogue', 19, 15)) // 136 console.log(f('Paladin', 13, 13)) // 95 console.log(f('Cleric', 13, 15)) // 94 console.log(f('Bard', 8, 5)) // 19 console.log(f('Monk', 20, 11)) // 103 console.log(f('Barbarian', 8, 20)) // 101 console.log(f('Monk', 1, 4)) // 5 console.log(f('Bard', 5, 17)) // 43 console.log(f('Monk', 18, 7)) // 57 console.log(f('Wizard', 17, 5)) // 19 ``` [Answer] ## Batch, 172 bytes ``` @set/aa=1-%3/2,h=4-a @for %%c in (-1.Sorcerer -1.Wizard 1.Fighter 1.Paladin 1.Ranger 2.Barbarian)do @if %%~xc==.%1 set/aa-=c=%%~nc,h+=c*2 @cmd/cset/a"a*=(a>>9),-~a*~-%2+h ``` Takes class, level, and constitution as command-line arguments. Explanation: The HP can be calculated as (HP at level 1) + (level - 1) + min(further HP per level, 0) \* (level - 1). The further HP per level is half the hit die plus the constitution modifier. Most classes use d8 so this becomes one less than half the constitution (`%3/2-1`), while the HP at level 1 is 3 more than that. The further HP per level and HP at level 1 are then adjusted for the six classes that don't use d8. The further HP per level is then limited to 0 (this actually uses the negative value as it's slightly golfier this way.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OSị“#®Ʋ?[’ṃ6¤ð+‘»1×⁵’¤+⁸Ḥ¤+ð⁹_10:2 ``` Full program taking three command line arguments: class, score, level. **[Try it online!](https://tio.run/nexus/jelly#AVMArP//T1Phu4vigJwjwq7Gsj9b4oCZ4bmDNsKkw7Ar4oCYwrsxw5figbXigJnCpCvigbjhuKTCpCvDsOKBuV8xMDoy////IkJhcmFyaWFuIv8xM/8xNQ "Jelly – TIO Nexus")** ### How? The middle of the code, separated by `ð`s is a dyadic link which calculates the result from some previously calculated values: ``` +‘»1×⁵’¤+⁸Ḥ¤+ - maxHitPoints(halfDieValue, modifier) + - add: halfDieValue + modifier ‘ - increment »1 - maximum of that and 1: this is the level-up delta ¤ - nilad followed by links as a nilad: ⁵ - program's 3rd argument, level (5th command line argument) ’ - decrement: this is the number of level-ups × - multiply: level-ups * level-up delta ¤ - nilad followed by links as a nilad: ⁸ - link's left argument: halfDieValue Ḥ - double: dieValue + - add: level-ups * level-up delta + dieValue + - add: level-ups * level-up delta + dieValue + modifier ``` The modifier is calculated at the right hand side: ``` ⁹_10:2 - getModifier(class, score) ⁹ - link's right argument, the 2nd argument, the score _10 - minus 10 :2 - integer divide by 2 ``` Half the die value is calculated at the left hand side: ``` OSị“#®Ʋ?[’ṃ6¤ - getHalfDieValue(class) O - cast to ordinals S - sum ¤ - nilad followed by link(s) as a nilad: “#®Ʋ?[’ - base 250 literal 140775266092 ṃ6 - convert to base 6 but with 6s in place of 0s ị - index into (1-indexed and modular) ``` Considering the ordinal sums of the class names modulo `m` such that `m` is minimal while keeping the classifications (by die) from colliding yields `m=15`. Placing the required values (half-die roll) at those indexes in a list of length 15 allows lookup using Jelly's modular indexing with `ị`. Compressing the list as a base 6 number with the lone `6` replaced by a `0` is a byte shorter than the alternatives of base-7 compression or base-4 compression & increasing the values (with the byte overhead associated with using an extra nilad in the chain). The base 6, rather than 7, decompression is achieved by using the fact that base decompression, `ṃ` (rather than base conversion, `b`), has implicit range construction when it's right argument, `r`, is an integer, which means is is like converting to base `r` and then changing any `0` to an `r` all in one go. That is: ``` class: Sorcerer,Wizard,Bard,Cleric,Druid,Monk,Rogue,Warlock,Fighter,Paladin,Ranger,Barbarian Ordinal sum: 837, 625, 377, 594, 504, 405, 514, 723, 713, 697, 607, 898 mod 15: 12, 10, 2, 9, 9, 0, 4, 3, 8, 7, 7, 13 required value: 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6 ``` Rearranging to the list, converting the 6 at index 13 to a zero and making it minimal in base 6: ``` mod 15: 2 3 4 7 8 9 10 12 13 0 value: 1, 4, 4, 4, 0, 0, 5, 5, 4, 3, 0, 3, 0, 0, 4 ``` Making the code ``` list: [1,4,4,4,0,0,5,5,4,3,0,3,0,0,4] from base 6: 140775266092 to base 250: [36,9,154,64,92] code page characters: # ® Ʋ ? [ final code: “#®Ʋ?[’ṃ6 ``` [Answer] ## R, ~~181~~ 163 bytes ``` function(s,n,t){a=Hmisc::Cs(rc,za,rd,er,ui,mk,gu,rl,gh,la,ng,rb) b=c(6,6,rep(8,6),rep(10,3),12) d=b[a == substr(s,3,4)] m=floor((t-10)/2) d+m+(n-1)*max(d/2+1+m,1)} ``` Anonymous function. Runs as `f(class, level, CON)`. Explanation: Creates vectors for class `s` to dice max `d`, using the 3rd and 4th letters in the class name (smallest unique mapping I found). CON mod `m` is straight from the spec, and HP = first level (`d + m`) + the rest of the levels (`(n-1) * max(average_die + m, 1)`. ``` > f("Barbarian", 15, 13) [1] 125 > f("Rogue", 10, 18) [1] 93 > f("Wizard", 15, 18) [1] 122 > f("Wizard", 16, 1) [1] 16 > f("Barbarian", 15, 7) [1] 80 > f("Warlock", 15, 3) [1] 18 > f("Ranger", 14, 1) [1] 18 ``` ]
[Question] [ **Objective:** > > Code two programs where each of the programs outputs both source codes > interlaced per character like a zipper, a Double-slit Quine. The output from a Double-slit Quine > is starting with the first character from the source code of the first > program. If the source code of one of the programs is shorter in length > than the other, then the rest of the output must be filled with the > rest of the longer source code. > > > **Rules:** 1. You can use any programming language for both programs, not necessary the same programming language for both. 2. Your programs should not take any input from a file, file name, network, the other program or anything else. **Mandatory criteria:** * There is a catch, somewhere in the output the word `QUINE` in capital letters must exist, uninterrupted. * You need to state what two programming languages you are using. If you are using the same programming language for both, then you only need to state one programming language. * Both programs should be able to execute, or be interpreted, respectively independent of the other program. **Example:** Having this example source code of program **one**: ``` "QIE" ``` Having this example source code of program **two**: ``` "UN" ``` Then the valid Double-slit Quine output from both programs must be: ``` ""QUINE"" ``` This is code-golf, the least bytes when summing the length of both source codes, and obviously also the length of each programs output, wins! [Answer] # CJam, ~~49~~ 47 bytes ``` {`:_"__~~e#QUINE"}_~ ``` and ``` {`:_"__~~e#QUINE"}_~e#QUINE ``` both print ``` {{``""__~~""++::__""ee##QQUUIINNEE""}}__~~e#QUINE ``` Try it online: [program 1](http://cjam.tryitonline.net/#code=e2A6XyJfX35-ZSNRVUlORSJ9X34&input=), [program 2](http://cjam.tryitonline.net/#code=e2A6XyJfX35-ZSNRVUlORSJ9X35lI1FVSU5F&input=), [proof of validity](http://cjam.tryitonline.net/#code=bFtffk5dbyBlIyBSZWFkIGxpbmUsIGV2YWwgY29weSwgcHJpbnQuCmxbX35OXW8gZSMgRGl0dG8uCiAgICAgXXogZSMgWmlwIGxpbmVzLg&input=e2A6XyJfX35-ZSNRVUlORSJ9X34Ke2A6XyJfX35-ZSNRVUlORSJ9X35lI1FVSU5F) ### How they work ``` { } e# Push a code block. _~ e# Execute a copy. ` e# Convert the code block into a string. :_ e# Duplicate each character of the resulting string. "__~~e#QUINE" e# Push this string. ``` Program 1 finishes here and has a string representation of its entire source code (which each character repeated twice) as well as the string **e#QUINE** on the stack. Program 2 additionally parses `e#QUINE`, which is a comment. In both cases, CJam prints the two strings automatically, resulting in the aforementioned output. [Answer] ## Seriously, ~~46~~ ~~56~~ 42 bytes ``` QUNX;RZtdXεj.ƒ£REIQ ``` Hex Dump: ``` 51554e583b525a746458ee6a2e7f9f9c524549510a ``` The second program is this exact program reversed. It does contain an invisible character, but the byte count is correct. Both programs output this palindromic string: ``` QQUINEXR;£RƒZ⌂t.djXεεXjd.t⌂ZƒR£;RXENIUQQ ``` (For some reason it displays the invisible character when it outputs it in my terminal. I don't really understand that 7F byte.) How it works: ``` Q Push the source to the stack U Nop NX Push and pop lyrics to 99 bottles of beer ;R Make a copy of the source reversed. Z Zip them together. t Completely flatten the list. dX Delete the trailing newline εj Join it into a string. . Print it with a trailing newline. ⌂ (This is that 7F byte that won't show up. It halts.) ``` The rest of the program is not executed. Then the other direction: ``` \n Nop Q Push the source code. IE Nops R Reverse source code to get source of first program £ Eval it into a function ƒ Call it. ``` At this point, we are now running the first program above, so execution continues as described there. I am heavily exploiting the fact that several commands do nothing to strings or empty stacks here. I'm also exploiting the unexpected behavior of `t` when there is only one item on the stack. Do not expect this program to work in future versions of Seriously. As the online version of the Seriously interpreter continues to be broken, you'll have to [download the interpreter](https://github.com/Mego/Seriously) and run it on your own machine to test it. [Answer] # GolfScript, 46 bytes ``` {`{.}%"..~~QUINE"}.~ ``` and ``` {`{.}%"..~~QUINE"}.~QUINE ``` both print ``` {{``{{..}}%%""....~~~~QQUUIINNEE""}}..~~QUINE ``` Try it online: [program 1](http://golfscript.tryitonline.net/#code=e2B7Ln0lIi4ufn5RVUlORSJ9Ln4&input=), [program 2](http://golfscript.tryitonline.net/#code=e2B7Ln0lIi4ufn5RVUlORSJ9Ln5RVUlORQo&input=), [proof of validity](http://golfscript.tryitonline.net/#code=J3tgey59JSIuLn5-UVVJTkUifS5-JyAgICAgIDpwcm9ncmFtMSB-IF0gcHV0cwoKJ3tgey59JSIuLn5-UVVJTkUifS5-UVVJTkUKJyAgICAgICAgICAgICAgICAgICAgICAgICAgIDpwcm9ncmFtMiB-IF0gcHV0cwoKcHJvZ3JhbTEgcHJvZ3JhbTIgXSB6aXAgOm47&input=) ### How it works ``` {`{.}%"..~~QUINE"}.~ { } # Push a code block. .~ # Execute a copy. ` # Convert the code block into a string. {.}% # Duplicate each character of the resulting string. "..~~QUINE" # Push that string. ``` The source code of program 2 additionally parses `QUINE\n`, which are two undefined tokens. [Answer] # Perl, 61+60=121 bytes Program 1: ``` $x=q<print"\$x=q<$x>;eval\$x#"=~s/./$&$&/gr,QUINE>;eval$x#QIE ``` Program 2: ``` $x=q<print"\$x=q<$x>;eval\$x#"=~s/./$&$&/gr,QUINE>;eval$x#UN ``` I thought I'd give this a go in a non-golfing language. This is basically just a universal quine constructor in Perl modified to double every character before printing it, and append `QUINE` to the end. Then we just have to stick a comment at the end of the code to compensate for the added text. (I wrote this without really looking at the other answers. Turns out it'd be possible to save a byte by putting the entire comment in one program, but I'm not sure if I should just be blatantly copying algorithms like that.) ]
[Question] [ People have written many things allowing one thing to be visualized as another. Now I propose being able to translate letters to music! Its your job to write a program that takes a text file and outputs a sound file with each letter converted to a specific note from [`C3-C8`](http://en.wikipedia.org/wiki/C_%28musical_note%29#Designation_by_octave). *Disclaimer - I don't actually expect the music to sound any good but I hope to be surprised.* ## Specifications * You take the name of a file as a string and the [BPM](http://en.wikipedia.org/wiki/Tempo#Beats_per_minute) (beats per minute) as an int * You make uppercase `A` to be the note [`C3`](http://en.wikipedia.org/wiki/C_%28musical_note%29#Designation_by_octave) * And go up a half-step for every character after in this order: `ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'"abcdefghijklmnopqrstuvwxyz` * Yes, not every character will be used since that spans too many octaves. * You translate every character in the file in this way * Put the notes together at the given BPM as quarter notes * Either save as a sound file (I'm guessing midi will be the easiest, but anything is ok) or play it * Any sane input format is fine * No [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) * This is code-golf, so shortest code in **bytes** wins! ## Bonuses * Allow [transposing](http://en.wikipedia.org/wiki/Transposition_%28music%29) of output - **50 bytes** * Allow multiple tracks to be superimposed over each other by taking multiple files - **75 bytes** * Join consecutive letters into one longer note - **50 bytes** **Edit:** Wow, we have negative scores. I'll be announcing the winner on Saturday. [Answer] # MATLAB, 159-50-50-75 = -16 [Sample input](https://www.dropbox.com/s/iuhtx4dva0fvttp/input.txt?dl=0) [Sample output](https://www.dropbox.com/s/dmy86b9zlceh3de/output.wav?dl=0) Generates pure sine sound waves, very funky (sawtooth is also possible, with an even better score, but that sounds a bit... *too* funky). Works as a function, so expects it a character array (`['abc';'def']`) with one row per 'track'. I think that is covered under *'any sane input format'*, but if the general consensus is that I need to read a file, I suppose I can change it. Input `i` is text tracks (of equal length), `b` beats per minute and `t` transpose (supply 0 for not transposed). It blends two sines into one by offsetting the sine input, so I got all three bonuses, giving me a negative score. ``` function v(i,b,t) s=0;for r=1:size(i) o=[];for k=i(r,:) o=cat(2,o,sin(55*pi*2^((k-28+t)/12)*(numel(o)/2^13+(0:1/2^13:60/b))));end s=s+o;end sound(s/max(s)) end ``` # Version using input file: 211-175=36 Input argument `i` now represents the file name, other parameters unchanged. Might not work on newer releases because I'm getting a warning that `textread` may soon be deprecated. EDIT: textread apparently automatically splits up at whitespaces, so I fixed that. Also, I think I may have accidentally contacted some aliens with the weird sounds made while testing. ``` function v(i,b,t) i=textread(i,'%s','whitespace','','delimiter','\n');s=0;for r=1:size(i) o=[];for k=i{r,:} o=cat(2,o,sin(55*pi*2^((k-28+t)/12)*(numel(o)/2^13+(0:1/2^13:60/b))));end s=s+o;end sound(s/max(s)) end ``` Which version do you prefer? :) [Answer] ## [Snap*!*](http://snap.berkeley.edu) - 401 - 75 = 326 [Try it online here.](http://snap.berkeley.edu/snapsource/snap.html#present:Username=Scimonster&ProjectName=sound%20of%20words) I'm using [this method](http://meta.codegolf.stackexchange.com/questions/673/golfing-from-scratch/5013#5013) of counting bytes for the program. ![enter image description here](https://i.stack.imgur.com/q0qsa.png) I added playing multiple sounds at once. The basic structure is the same as the original (see below), but with the addition of `launch{}`. `launch{}` starts a new thread with the code inside, allowing for concurrency. The code as text is: ``` set[c v]to[ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'"abcdefghijklmnopqrstuvwxyz set[l v]to(list> ask[BPM]and wait set tempo to(answer)bpm repeat until<(answer)=[ ask[notes]and wait add(answer)to(l end delete(last v)of(l for each(i)of(l launch{ repeat(length of(i))(# play note(i(c)(letter(#)of(i)))for(0.25)beats (i(h)(n)) report(call(JavaScript function ([h][n]) {[return h.indexOf(n)+48]})with inputs(h)(n ``` --- Original code, 308. ![enter image description here](https://i.stack.imgur.com/KLmpX.png) Lucky Snap! has MIDI playing built in. ;) Unfortunately, it doesn't have an `indexOf` function, so i have to make an external JavaScript call, which is pretty expensive. The `repeat () (#)` block comes from the iteration library. The code can be written out as text like this, which is how i get 308 bytes: ``` set[c v]to[ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'"abcdefghijklmnopqrstuvwxyz ask[BPM]and wait set tempo to(answer)bpm ask[notes]and wait repeat(length of(answer))(#) play note(i(c)(letter(#)of(answer)))for(0.25)beats (i(h)(n)) report(call(JavaScript function ([h][n]) {[return h.indexOf(n)+48]})with inputs(h)(n ``` [Answer] # Mathematica, 219 - 50 - 75 - 50 = 44 ``` c=CharacterRange;d=Import;EmitSound[Function[b,Sound[Split@Characters@d@b/.a:{__String}:>SoundNote[StringPosition[c["A","Z"]<>" ()-,;.'\""<>c["a","z"],a[[1]]][[1,1]]+#3-12,60Length@a/#2],{0,60StringLength@d@b/#2}]]/@#]& ``` Takes the list of input files, BPM, and number of half-steps to transpose by as input and plays the sound (from a piano, any other instrument would take more bytes.) Doesn't sound that bad! [Answer] # JavaScript (ES6) 377 - 50 - 50 - 75 = 202 First, here's a runnable snippet that uses `<input>` fields instead of file-reads: ``` <b>BMP:</b> <input id="bpm" size=3 placeholder="BMP" value="120"> <b>Transpose:</b> <input size=3 id="transpose" placeholder="Transpose" value="0"><br/><br/><div id="tracks" style="float:left;padding-right:5px;"><input placeholder="Track" class="track"></div><button id="add">Add Additional Track</button><div style="clear:both; padding-top:5px;"></div><button id="play"><b>Play</b></button><script>f=function(s,b,z){C=new (window.AudioContext||window.webkitAudioContext);b=6e4/b;s.map(function(p){var o=C.createOscillator(t=setTimeout);o.connect(C.destination);o.start();p.split("").map(function(c,i){t(function(){o.frequency.value=440*Math.pow(2, ("ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'\"abcdefghijklmnopqrstuvwxyz".indexOf(c)-21+z)/12)},b*i)});t(function(){o.stop()},p.length*b)})};document.getElementById("play").onclick=function(){f([].map.call(document.getElementsByClassName("track"),function(e){return e.value;}),+document.getElementById("bpm").value,+document.getElementById("transpose").value);};document.getElementById("add").onclick=function(){var i=document.createElement("input");i.placeholder="Track";i.className="track";document.getElementById("tracks").appendChild(document.createElement("br"));document.getElementById("tracks").appendChild(i);};</script> ``` And now, the actual entry: ``` f=(n,b,z)=>{C=new AudioContext;b=6e4/b;s=n.map(m=>(x=new XMLHttpRequest,x.open("GET",m,0),x.send(),x.responseText));s.map(p=>{var o=C.createOscillator(t=setTimeout);o.connect(C.destination);o.start();[...p].map((c,i)=>t(_=>o.frequency.value=440*Math.pow(2,("ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'\"abcdefghijklmnopqrstuvwxyz".indexOf(c)-21+z)/12),b*i)),t(_=>o.stop(),p.length*b)})} ``` The three arguments are an array of filepath strings to play concurrently, notes per minute, and number of half-steps to transpose all inputs. With whitespace and comments: ``` f=(n,b,z)=>{ C=new AudioContext; b=6e4/b; // fill s with the contents of each file s = n.map(m=>(x=new XMLHttpRequest,x.open("GET",m,0),x.send(),x.responseText)); // play each track s.map(p=>{ var o=C.createOscillator(t=setTimeout); o.connect(C.destination); o.start(); // queue up each note with setTimeout [...p].map((c,i)=> t(_=> o.frequency.value=440* Math.pow(2, ("ABCDEFGHIJKLMNOPQRSTUVWXYZ ()-,;.'\"abcdefghijklmnopqrstuvwxyz".indexOf(c)-21+z)/12 ), b*i) ); // queue up termination of those track t(_=>o.stop(),p.length*b)}) } f(["file:///home/users/apsillers/notes.txt", "file:///home/users/apsillers/notes2.txt"], 240, 5) ``` ]
[Question] [ [Inspired by this question](https://codegolf.stackexchange.com/questions/47895/generate-a-brainf-ck-program-that-outputs-a-string-of-given-length), your goal today is to encode an URL in brainfuck. My browser has been hacked! The location bar has been turned into a brainfuck interpreter. I need a program that turns an URL into a brainfuck program. My computer is also very slow, so if the brainfuck program is small it's better. Oh and I only have one working tab left open, my twitter. So you can only send me the program in a tweet. --- 1. Write a program that fits in a tweet (140 characters) in any language that takes a string as input and outputs a brainfuck program. 2. This brainfuck program will be run without input and will generate an output. 3. This output will be inserted into the location bar of Google Chrome, and executed. 4. If the behaviour of Google Chrome is identical to the behaviour you would get by entering the input string from #1, then the solution is valid. *Redirection by URL shorteners is considered different behaviour - stay at least on the same domain.* You may assume the brainfuck interpreter has infinite precision signed integers in each cell and an unlimited amount of cells. Your score is determined by the sum of the lengths of the brainfuck programs generated to encode the following set of URLs: ``` https://www.google.com/ https://codegolf.stackexchange.com/questions/47895/ http://www.golfscript.com/golfscript/examples.html http://en.wikipedia.org/wiki/Percent-encoding ftp://ftp.freebsd.org/pub/FreeBSD/ https://github.com/isaacg1/pyth/blob/master/doc.txt#L92 http://ftp.gnu.org/non-gnu/nethack/nethack-3.4.0.tar.gz.back-RSN.README ``` Smallest score wins. [Answer] # Pyth - 118 bytes, score: 154 + 567 + 597 + 620 + 530 + 875 + 1092 = 6630 6623 4653 4435 Now using the factor multiplication algo! This is a pretty simple algorithm, although slightly better than the above ones. I was planning to use Pyth, but with the current algorithm Python fits<140 bytes. ``` =zecz"//"=z?>z4}"www."zz=z?Pzqez\/zFNzKCNJ/^K.5 1=d\+pk+holN[?*-KZd>KZ*-ZK\-+\>*dK+++++\>*Jd"[>"*Jd"<-]>"*-K*JJd)\.=ZK ``` It first strips out the `http://` by using `split("//")` and the `www.` and `/` at the end. Then it uses the min function to check which is the best of the the three options that is considered: 1. Use `+` or `-` to update current cell value to desired cell value 2. Go to new cell and just fill with `+`'s 3. Go to new cell and use multiplication to update by doing sqrt(n)\*sqrt(n)+remainder since square has minimum perimeter of constant area. <http://cydathria.com/bf/bf_ex3.html> I then always put a `.` to output each char. A detailed explanation of the new code is coming soon. I kind of half-assed the golfing, especially the stripping of `www.` and the `/` at the end but I can't be bothered since I'm 20 bytes under the limit. This surprisingly works on the `ftp://` urls since this is chrome and chrome automatically makes `ftp.freebsd.org/pub/FreeBSD/` into `ftp://ftp.freebsd.org/pub/FreeBSD/` I plan to next use a dictionary to store the cell values and see if the character was already made in a cell. --- ## Brainfuck Omnibox Extension That's right! After I saw @BrainSteel's comment, I knew I had to make it. This doesn't take over the entire omnibox, only when you do `bf`,`tab`. Also since the omnibox api is weird, it doesn't let me forward the code to the omnibox, I have to handle it myself. So I do my own `http://` checking and then set the tab's url. Since I didn't feel like paying the $5 necessary to put your extension on the webstore, you guys will have to install it manually. Just download the zip from here: <https://drive.google.com/file/d/0B0qkKIzGc0QiNzBzVUJjZkRIZ0k/view?usp=sharing>, unzip, go into the extensions page in chrome, click dev mode option box on top-right, and load the unpacked extension. Hope you guys enjoy! :) [Answer] # C, ~~140~~ ~~134~~ ~~132~~ ~~138~~ ~~128~~ 139 Bytes # 263 + 816 + 911 + 955 + 827 + 1355 + 1779 = ~~7269~~ 6906 bytes Update: 6 bytes less, thanks to nutki! Update again, 128 bytes. Code is significantly less readable. It now attempts to strip the URL of `ftp://`, too. Update the third, at 139 bytes. Code is a bit more readable, and got rid of some nasty undefined behavior. Now, if the site name is preceded by `www.`, it is stripped. I got under 7k, but I think I must concede to Maltysen with Pyth. Well done. ``` #define p putchar a;main(int c,char**V){while(*V[1]++-47);*++V+=1;for(*V+=**V-'w'?0:4;c=**V;*V+=1,p(46))for(;c-a;a+=c>a?1:-1)p(c>a?43:45);} ``` Unraveled a bit: ``` #define p putchar a; main(int c,char**V){ while(*V[1]++-47); *++V+=1; for(*V+=**V-'w'?0:4;c=**V;*V+=1,p(46)) for(;c-a;a+=c>a?1:-1) p(c>a?43:45); } ``` This code takes a URL at the command line, and converts it into BF using only `.`,`-`, and `+`. The code makes an attempt to strip the string of `ftp://`,`http://`,`https://`, and `www.` before converting to BF. Here is a list of outputs of the outputs: ``` google.com/ codegolf.stackexchange.com/questions/47895/ golfscript.com/golfscript/examples.html en.wikipedia.org/wiki/Percent-encoding ftp.freebsd.org/pub/FreeBSD/ github.com/isaacg1/pyth/blob/master/doc.txt#L92 ftp.gnu.org/non-gnu/nethack/nethack-3.4.0.tar.gz.back-RSN.README ``` [Answer] # Brainfuck, 77 bytes, Score = 31647 Score is the sum of `codepoint+4` for every character. ``` +++++[>+++++++++<-]>+[>++>+>++>+>+<<<<<-]>+>->->>--->,[[<.>-]<<.<.<.<.>>>>>,] ``` (Uses BF implementation with EOF = 0.) Example: ``` input: !bar output: +++++++++++++++++++++++++++++++++.[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.[-] ``` [Answer] # JavaScript (ES6) - 137 bytes, score - 7413 This uses only `.`, `+` and `-`. You can test it in Firefox console. ``` B=s=>[...s.replace(/^h.+\/\//,'')].map((c,i,a)=>(v=i?c[C]()-a[i-1][C]():c[C='charCodeAt']())?'-+'[v>0|0].repeat(v>0?v:-v):'').join('.')+'.' ``` This is my score counter: ``` [ 'https://www.google.com/', 'http://codegolf.stackexchange.com/questions/47895/', 'http://www.golfscript.com/golfscript/examples.html', 'http://en.wikipedia.org/wiki/Percent-encoding', 'ftp://ftp.freebsd.org/pub/FreeBSD/', 'https://github.com/isaacg1/pyth/blob/master/doc.txt#L92', 'http://ftp.gnu.org/non-gnu/nethack/nethack-3.4.0.tar.gz.back-RSN.README' ].map(B).join('').length ``` ]
[Question] [ Create a bidirectional Gematria calculator, for any given sequence of Unicode characters as the alphabet. # Gematri-What? [Gematria](http://en.wikipedia.org/wiki/Gematria) is a system of assigning numerical values to symbols, developed by ancient Greeks and adopted by ancient Jews. It is in a way like ASCII or Unicode, it's just non-linear... See the following table (full table is available in the link above): ``` Index Letter Letter name Value -------------------------- 0 א "Alef" 1 1 ב "Bet" 2 ... 8 ט "Tet" 9 9 י "Yud" 10 10 כ "Kaf" 20 ... 17 צ "Tsady" 90 18 ' "Kuf" 100 19 ר "Resh" 200 ... ``` The names of letters are not important, only their index in the "Array" of the alphabet and the respective numerical value. The Hebrew alphabet only has 22 letters (not including "final" letters), so the maximum available value is 400. If we borrow this system to the English alphabet (A-Z) we will end up with A=1, B=2... L=30... U=300... Z=800. Two things we need to know. 1. One of the most important features in this system is calculating the "Gematria Value" of a **word**, by **summing up** its letters' values. (Some say there is a mystical connection between words, or phrases (when the value of space is zero) - that share the same Gematria Value). 2. Any non-negative Integer can be represented in symbols. For example (and let's stay with the English alphabet for now) the value of 32 is LB (L=30 + B=2). The value of 1024 is ZTKD (800+200+20+4. Note that ZSSKD is also 1024, but that's not a legal representation, since it can be compacted). # The Challenge Write a program / a function / a code snippet in your language-of-choice, which is first set up with an alphabet (see API below) and then accept an argument. That argument may be an Integer, or a word/phrase. If it's an Integer - your program should output/return its representation in the alphabet symbols - the most compacted one (see (2) above). If it is a word or a phrase, your program should output/return the Gematria Value (by summing up symbols' values, not counting whitespaces, see (1) above). # API Your program/function should accept 3 arguments. You can get them from STDIN, or as function arguments, you can even assume they are variables which initialized programmatically prior to your function invocation. * First argument - the first character (in Unicode) of the alphabet. * Second argument - the last character (in Unicode) of the alphabet. * Third argument - An Integer, to be represented in symbols, OR a phrase which is created by the given alphabet. Output / Return Value: Depending on the third argument, as explained above. # Assumptions * First two arguments will always be one character long each, and the second will always be grater than the first. * The sequence (first until last, inclusive) will never include any of the values 30-39 (which represent the digits 0-9), otherwise it will make the third argument ambiguous. **EDIT:** It won't contain space as well, since in phrases spaces are counted as zeros. * The third argument, in case it's a phrase, may only contain spaces and letters of the given alphabet. Empty string is not a valid input (you can assume it's not empty). In case it's an Integer, you can assume it's a positive Integer. # Examples ``` Input Output A Z CODE GOLF 175 a s 512 sssssjb A B 7 BBBA ≐ ⊐ ≤≫ ≥ 1700 ``` # Scoring `Score = upvotes - length/100.0` Your code should be short, but more-importantly popular. Negative scores can also play along. The winner will be the answer with highest score in a week from now, 2014-11-29 19:20:00 UTC. [Answer] # Java 7, Score = Upvotes - 3.97 Yay!!! Java!!! The world's favourite golfing language in the world. What, you can actually golf in java??? Well, it's kind of like using a bulldozer to putt. `a` is expected to contain the first character. `b` is expected to contain the last character. `c` is expected to have the input string. Here is the function golfed: ``` int d=0;try{d=Integer.parseInt(c);}catch(Exception e){}int l=b-a+1;char[]f=new char[l];int[]g=new int[l];int h=1;int i=1;g[0]=1;f[0]=a;int j;for(j=1;j<b-a+1;){g[j]=(h+=i);f[j]=(char)(f[j++-1]+1);i*=h==10*i?10:1;}if(d==0){h=0;for(char k:c.toCharArray()){for(j=0;j<l;j++){if(f[j]==k){h+=g[j];}}}System.out.println(h);}else{c="";for(j=l;j>0;){if(g[--j]<=d){c+=f[j];d-=g[j++];}}System.out.println(c);} ``` Here it is indented with structure code: ``` public class G{ public static void main(String[] args){ new G(args); } public G(String[] args){ a = args[0].charAt(0); b = args[1].charAt(0); for (int i = 2; i < args.length; i++){ c += args[i]; } function(); } char a; char b; String c = ""; void function(){ int d=0; try{ d=Integer.parseInt(c); }catch(Exception e){} int l=b-a+1; char[]f=new char[l]; int[]g=new int[l]; int h=1; int i=1; g[0]=1; f[0]=a; int j; for(j=1;j<b-a+1;){ g[j]=(h+=i); f[j]=(char)(f[j++-1]+1); i*=h==10*i?10:1; } if(d==0){ h=0; for(char k:c.toCharArray()){ for(j=0;j<l;j++){ if(f[j]==k){ h+=g[j]; } } } System.out.println(h); }else{ c=""; for(j=l;j>0;){ if(g[--j]<=d){ c+=f[j]; d-=g[j++]; } } System.out.println(c); } } } ``` Here it is completely expanded: ``` public class Generator{ public static void main(String[] args){ beginning = args[0].charAt(0); end = args[1].charAt(0); for (int i = 2; i < args.length; i++){ phrase += args[i]; } function(); } static char beginning; static char end; static String phrase = ""; static void function(){ int convertTo = 0; try{ convertTo = Integer.parseInt(phrase); } catch (Exception e){} char[] alphabet = new char[end - beginning + 1]; int[] values = new int[alphabet.length]; int value = 1; int base = 1; values[0] = 1; alphabet[0] = beginning; int i; for (i = 1; i < values.length;){ values[i] = (value += base); alphabet[i] = (char)(alphabet[i++-1]+1); base*=value==10*base?10:1; } if(convertTo==0){ value = 0; for (char character : phrase.toCharArray()){ for (i = 0; i < alphabet.length;i++){ if (alphabet[i] == character){ value += values[i]; } } } System.out.println(value); } else { phrase = ""; for (i = values.length;i > 0;){ if (values[--i] <= convertTo){ phrase += alphabet[i]; convertTo -= values[i++]; } } System.out.println(phrase); } } } ``` [Answer] # CJam, ~~80~~ ~~75~~ 70 bytes, Upvotes - 0.7 ``` Arc:Irc\-):N,f#{9,:)f*~}%N<lS-_A,s&{i{1${1$)<},)\,I+o-}h;;}{If-\f=:+}? ``` [Test it here.](http://cjam.aditsu.net/) This is a full program, which takes input from STDIN and prints the result to STDOUT. I'm not really sure how I'm supposed to shoot for popularity here, so I'm simply golfing this, hoping to get a reasonably impressive code size instead. ;) I believe the int-to-string conversion can still be improved, but I don't see it right now. Thanks to Optimizer for reminding me about set intersection and that empty arrays are falsy. ``` A "Push integer 10."; rc:I "Read token, convert to character, save in I."; rc "Read token, convert to character."; \-) "Swap, subtract, increment."; :N "Store number of characters in N."; , "Turn into range [0 1 2 ... N-1]."; f# "Map 10^i onto that range."; { }% "Map this block onto the powers of 10."; 9, "Create range [0 1 2 ... 8]."; :) "Increment each element."; f* "Multiply each by the current power of 10."; ~ "Unwrap/dump the resulting array."; "Now we've got the values of the first 9N digits."; N< "That's too much, so truncate to the first N."; l "Read the rest of the line."; S- "Remove spaces."; _ "Duplicate string and get first character."; A, "Create range [0 1 2 ... 9]."; s "Turn into string '0123456789'."; & "Intersection of characters."; { }{ }? "If/else depending on whether the result is empty."; "If it was a digit..."; i "Convert string to integer."; { }h "While that integer isn't zero..."; 1$ "Copy digit values."; { }, "Filter digit values."; 1$ "Copy remaining integer."; )< "Increment, compare."; "This discards values greater than the integer."; )\ "Slice off last digit value, and swap with list."; ,I+ "Get length of list and add to I."; o "Print character."; - "Subtract digit value from integer."; ;; "Empty stack."; "If the string was not a number..."; I "Push initial character."; f- "Subtract it from each character in string."; \ "Swap differences and digit values."; f= "Use differences to index into the values."; :+ "Sum up all the values."; ``` In the second case, the result is left on the stack, which is printed automatically at the end of the program. [Answer] # Haskell, 188 bytes; Upvotes - 1.88 This is a full-blown STDIN-to-STDOUT program, heavily golfed. *EDIT: Now in under 200 bytes! EDIT2: Saved one byte with @proudhaskeller's suggestion.* ``` x=[1..9]++map(*10)x f(a:_:b:_:z@(u:_))|u>'/'&&u<':'=w$read z|1<2=show.sum$map v z where v ' '=0;v c=x!!(length[a..c]-1);w 0="";w n=(\c->c:w(n-v c))$last[d|d<-[a..b],v d<=n] main=interact$f ``` It constructs the infinite list of values `x = [1,2,3,4,5,6,7,8,9,10,20,30,..]` on the first line, and does I/O on the third line. The value of a letter `c`, given the range `[a..b]`, is then the value at position `length [a..c] - 1` of `x`. On the second line, we branch on the first letter `u` of the third argument, and either sum its gematria values (if `u` is not a digit), or greedily construct a word with the given value (if `u` is a digit). Ungolfed version with more readable variable names: ``` values = [1..9] ++ map (*10) values f (low:_:high:_:rest@(first:_)) | first > '/' && first < ':' = construct $ read rest | otherwise = show . sum $ map value rest where value ' ' = 0 value c = values !! (length [low..c] - 1) construct 0 = "" construct n = (\c -> c : construct (n - value c)) $ last [d | d <- [low..high], value d <= n] main = interact $ f ``` [Answer] ## APL (upvotes - 1.05) ``` {U←⎕UCS⋄A←V↑∊(10*0,⍳⌊9÷⍨V←1+|-/U⍺)∘.×⍳9⋄⍬≢0↑⍵:+/A[1+(U⍵~' ')-U⊃⍺]⋄U(U⊃⍺)+{⍵≤0:⍬⋄(¯1+A⍳T),∇⍵-T←⊃⌽A/⍨⍵≥A}⍵} ``` This is a function that takes the two characters on the left, and the argument to be converted on the right: ``` 'A' 'Z'{U←⎕UCS⋄A←V↑∊(10*0,⍳⌊9÷⍨V←1+|-/U⍺)∘.×⍳9⋄⍬≢0↑⍵:+/A[1+(U⍵~' ')-U⊃⍺]⋄U(U⊃⍺)+{⍵≤0:⍬⋄(¯1+A⍳T),∇⍵-T←⊃⌽A/⍨⍵≥A}⍵}'CODE GOLF' 175 gematria←{U←⎕UCS⋄A←V↑∊(10*0,⍳⌊9÷⍨V←1+|-/U⍺)∘.×⍳9⋄⍬≢0↑⍵:+/A[1+(U⍵~' ')-U⊃⍺]⋄U(U⊃⍺)+{⍵≤0:⍬⋄(¯1+A⍳T),∇⍵-T←⊃⌽A/⍨⍵≥A}⍵} 'A' 'Z' gematria 'CODE GOLF' 175 'a' 's' gematria 512 sssssjb 'A' 'B' gematria 7 BBBA '≐' '⊐' gematria '≤≫ ≥' 1700 ``` Ungolfed version: ``` gematria←{ ⍝ get Unicode values for characters first last←⎕UCS¨⍺ amount←1+last-first ⍝ find the value for each character in the alphabet alphabet←amount↑∊(10*0,⍳⌊amount÷9)∘.×⍳9 ⍝ right arg is string: calculate number ⍬≢0↑⍵: +/ alphabet[1+(⎕UCS ⍵~' ')-first] ⍝ otherwise, right arg is number: find string ⎕UCS first+{ ⍝ number ≤ 0? empty string ⍵≤0:⍬ ⍝ find highest value we can subtract val←⊃⌽(⍵≥alphabet)/alphabet ⍝ return it, followed by the conversion of the rest of the number (¯1+alphabet⍳val), ∇⍵-val }⍵ } ``` [Answer] # CJam, 70 bytes, #Upvotes - 0.7 ``` {{_9%)A@9/#*}%}:M;rcrc),\i>:QlS-_@&{Qf#M:+}{i{Q,,M{1$)<},)Q@,=@@-}h;}? ``` This assumes that a valid input will be passed. Takes input from STDIN like the API spec says and prints result to STDOUT. Examples: ``` Input Output A Z CODE GOLF 175 a s 512 sssssjb A B 7 BBBA ≐ ⊐ ≤≫ ≥ 1700 ``` [Try it online here](http://cjam.aditsu.net/) **Block wise explanation**: ``` {{_9%)A@9/#*}%}:M; { }:M; "Define a function M which takes an input array of" "indeces and calculates the Gematri number for them"; { }% "Run this code block for each element of the array"; _9%) "Copy the number, take modulus by 9 and increment it"; A@ "Put 10 on stack, and rotate to get the number on top"; 9/ "Integer divide the number by 9"; # "Calculate 10 to the power the above quotient"; * "Multiply the above result by modulus 9"; rcrc),\i>:QlS-_@& rcrc "Read the first two characters, representing the lower" "and upper end of the character list"; ), "Increment the upper end and get a list of U to ASCII 0" "characters where U is the upper limit"; \i "Swap and convert the lower limit to its ASCII number"; >:Q "Slice the character list to get our desired character" "list range and store it in Q"; lS- "Read the rest of the line as string and remove spaces"; _@& "Take a copy, get Q on top of stack and take" "intersection with the input string. If the resulting" "string is empty, then the third input was a number"; {...}{...}? "First code block is for string input and second for" "number input based on the above intersected string"; {Qf#M:+} Qf# "For each character of input string, calculate its" "position in Q"; M "Get the Gematri numbers for these inceces"; :+ "Sum them all to get the final Gematri number for the" "input string" {i{Q,,M{1$)<},)Q@,=@@-}h;} i "Convert the input number string to integer"; { }h "Run the code block till we get 0 on top of stack"; Q,,M "Get the first length(Q) Gematri numbers"; {1$)<}, "Filter and take only which are less than input number"; ) "Pop the last number from the filtered array. This is" "The maximum Gematri number that can be deducted"; Q@ "Put Q on stack and rotate the remaining filtered array" "to top of stack"; , "Calculate the length of that array, which is also the" "index of the Gematri number used."; = "Get the corresponding character to that Gematri number"; @@- "Put the number and Gematri number on top and subtract." "The next loop runs on the above result now"; ; "Pop the resedual 0 from stack. The remaining stack now" "contains just the Gematri characters." ``` ]
[Question] [ An \*\*\*ameoba graph\*\*\*\* is a type of [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) whose nodes all have values from 0 to some non-negative integer N, and any particular node with value x < N connects to x+1 *distinct* nodes with values x+1. # Ameoba graph for N = 3: (Denoted A3) ![ameoba 3](https://i.stack.imgur.com/RolTn.png) Note that the 2's are not allowed to share any of the 3's; exactly three 3's must "belong" to each 2. # Challenge Your task is to inductively "grow" these ameoba graphs in a 2-dimensional grid by greedily minimizing the [Manhattan distance](http://en.wikipedia.org/wiki/Taxicab_geometry) between nodes: * **Base case:** A0 is simply the graph `0`. * **Inductive step:** AN+1 is generated by iteratively placing the new N+1 valued nodes as close as possible to the N values nodes in the existing AN structure. (It can only be as close as possible since the closest spots may already be filled.) For the inductive step the general procedure you must follow is: ``` for each existing node P with value N: for each new N+1 valued node Q you need to connect to P: //this loops N+1 times find the set of vacant spots that are minimally distant from P //by Manhattan distance place Q in any of these vacant spots ``` (A different procedure with indistinguishable output is fine.) # Growth example for A4: ``` A0 is always the same: 0 For A1 I happen to put the 1 to the right of the 0 (it has to go on one of the 4 open sides): 01 For A2 I happen to put the two 2's above and to the right of the 1: 2 012 For A3 I find that one of the six 3's I must place cannot be directly next to a 2, so I put in one of the next closest places: 3 323 0123 33 <-- this 3 is distance two away from its 2 The process continues in A4. Note that I'm iterating over each 3 and placing four 4's next to it or as close as possible, then moving to the next 3 (the order of 3's does not matter): 444 443444 4323444 4012344 44334 4444 44 Always keep in mind that nodes cannot be "shared". ``` # Program The program you write must take in a number from 0 to 8 (inclusive) and output a valid ameoba graph of it, using the inductive growth pattern explained above. What happens beyond 8 does not matter. (A8 contains 46234 nodes which is pushing it. Anything beyond A8 would be too far. Thanks to Martin Büttner for noticing this.) The input should come from stdin or the command line and output should go to stdout or a file. # Examples (taken directly from above) ``` Input: 0 Output: 0 Input: 1 Output: 01 Input: 2 Output: 2 012 Input: 3 Output: 3 323 0123 33 Input: 4 Output: 444 443444 4323444 4012344 44334 4444 44 ``` *\* These type of graphs might already have a name. I admit I just made them up. ;)* [Answer] ## Mathematica, ~~353~~ ~~288~~ ~~285~~ 275 bytes ``` n=Input[];f@_=" ";g={z={0,0}};i=f@z=0;For[r=Range,i++<n,g=Reap[(j=i;o={};For[d=0,j>0,o=Rest@o,If[o=={},o=Join@@({e={#,d-#},-e,e={d-#,-#},-e}&/@r@++d)];If[f[c=#&@@o+#]==" ",f@c=i;Sow@c;--j]])&/@g][[2,1]]];Riffle[(x=#;ToString@f@{x,#}&/@m~r~M)&/@r[m=Min@{g,0},M=Max@g]," "]<>"" ``` Ungolfed: ``` n = Input[]; f@_ = " "; g = {z = {0, 0}}; i = f@z = 0; For[r = Range, i++ < n, g = Reap[( j = i; o = {}; For[d = 0, j > 0, o = Rest@o, If[o == {}, o = Join @@ ({e = {#, d - #}, -e, e = {d - #, -#}, -e} & /@ r@++d) ]; If[f[c = # & @@ o + #] == " ", f@c = i; Sow@c; --j ] ] ) & /@ g ][[2, 1]] ]; Riffle[( x = #; ToString@f@{x, #} & /@ m~r~M ) & /@ r[m = Min@{g, 0}, M = Max@g ], " "] <> "" ``` Here is an example output for `n = 5`: ``` 5 5555 555555 5555555 555555555 55555555555 5555554445555 5555544444555 5555443305555 55554432144555 55555443234555 5555544344555 555554445555 5555555555 5555555 55555 55 ``` Input `8` takes about 4.5 minutes. For a quick breakdown of my algorithm: I'm using two look-up tables, `f` and `g`. The first one is just a sparse map containing the non-empty cells. The latter is a list containing all coordinate pairs for each cell-value (I think I don't even need to keep track of old ones here). I'm iterating through the coordinates in `g` to extend every cell from the last iteration. To do that I iterate over Manhattan distances, creating all possible vectors for each distance, and checking if the resulting cell is still empty (in which case I fill it). Repeat until enough new cells have been created. When I'm done, I find the minimum and maximum coordinate in `g` and I create an appropriate grid, which is filled by looking up the cells in `f`. The rest is just joining everything into a single string with line breaks. [Answer] # C - 309 305 301 275 bytes Meh, too long...if only one could type `#D` or something instead of `#define`, then C would be really great. Of course `-D` compiler flags are possible but that seems like cheating to me, to have characters other than the ones in the source file. ## Running instructions: Be careful! The first key you press after the program starts constitutes the input. Upon a character entry other than '0' through '8', who knows what undefined things will happen. ``` #define F(D,O)x=*r+O d;for(c=d;h*c--;x+=D)!g[x]?g[*w++=x]=l,--h:5; L=400;g[1<<18];n;s;*r;*w;*m;h;l;d;x;main(c){n=getch()-32;r=w=g+L*L;for(l=g[*w++=80200]=16;l++<n;)for(m=w;r<m;r++)for(d=1,h=l-16;h;d++){F(L+1,-)F(L-1,-L*)F(-L+1,L*)F(~L,)}for(n=L*L;--n;)putch(n%L?g[n]+32:10);} ``` Ungolfed (but already thinking about future golfing) version: ``` void exit(int); #define L 400 #define FIND(D, X0) x = *pread X0 d; \ for(c = d; c--; x+=D) { \ if(x%L == 0 || x%L == L-1 || x/L == 0 || x/L == L-1) \ exit(5); \ if(!g[x]) { \ g[*pwrite++ = x] = '0' + l; \ if(!--children) \ goto pnext; \ } \ } main() { int n = getch() - '0'; //char g[3] = {}; char g[L*L] = {}; int plist[46324]; int *pwrite = plist, *pread = plist; *pwrite++ = L/2*L + L/2; g[*plist] = '0'; int factorial = 1; int l, c, parents, children, d, x; for(l = 1; l <= n; l++) { for(parents = factorial; parents--; pread++) { children = l; for(d = 1; ; d++) { FIND(L + 1, - ) FIND(L - 1, -L* ) FIND(-L + 1, +L* ) FIND(-L - 1, + ) } pnext:; } factorial *= l; } int i; for(i = L*L; i--; ) putch(i%L ? (g[i] ? g[i] : ' ') : '\n'); } ``` Edit: I realized that since I moved the declarations outside of main(), the arrays can no longer be allocated on the stack, so I am free to use memory in a profligate manner without risk of overflow. [Answer] ## Ruby - 296 ``` g=[s=' ']*d=10**6 $*[g[50500]=0].to_i.times{|c|d.times{|x|g[x]==c&&(r=1;a=c;(4.times{|v|r.times{|w|g[q=x+r*(1e3*(v-1-v/2)+v%2-v/2)+w*(1e3*~0**(v/2)+~0**v)]==s&&a>~0?(g[q]=c+1;a-=1):0}};r+=1)while~0<a)}} g=g.join.scan(/.{1000}/) g.map{|s|s[/\d/]&&(puts s[g.map{|s|s[/\A */].size}.min..-1].rstrip)} ``` Slightly ungolfed. ``` g=[s=' ']*d=10**6 # Initialize a big 1d array as a 2d grid $*[g[50500]=0].to_i.times{|c| # For n times d.times{|x| # For each index in the grid g[x]==c&&( # If the element at x is equal to the current growth stage, c r=1; # Initial manhattan radius = 1 a=c; # a is number of times the ameoba must replicate (4.times{|v| # For each of the 4 sides of the manhattan diamond r.times{|w| # For each node in each side # Spawn the 'c+1' ameoba's from the c ameobas... # The messy formula gives the index of the space in the grid to try spawning g[q=x+r*(1e3*(v-1-v/2)+v%2-v/2)+w*(1e3*~0**(v/2)+~0**v)]==s&&a>~0?(g[q]=c+1;a-=1):0 } }; r+=1 # Increase the raidus of the manhattan diamond by one ) while~0<a # while not enough ameoba's have been spawned ) } } g=g.join.scan(/.{1000}/) # Join the 1d array into a huge string and slice it into rows # Strip away the empty spaces all around the graph and print it g.map{|s|s[/\d/]&&(puts s[g.map{|s|s[/\A */].size}.min..-1].rstrip)} ``` [Answer] ## APL (Dyalog) (121) ``` {0::0⋄V←,⍳⍴Z←' '⍴⍨2/M←⌈4×.5*⍨3÷⍨+/!⍳⍵⋄Z[G;G←⌈M÷2]←'0'⋄Z⊣{⍵∘{⍵∘{+((⊃F[⍋+/¨|(F←V/⍨,Z=' ')-⊂⍺])⌷Z)←⍕⍵}¨⍺/⍺}¨V/⍨,Z=⍕⍵-1}¨⍳⍵}⎕ ``` Performance characteristics: it's O(n!). On my system, up to n=5 it's instantaneous; n=6 takes a second, n=7 takes a minute and n=8 takes an hour. [Non-golfed version](https://gist.github.com/marinuso/9f0e68a6ad15654e0849) Test: ``` {0::0⋄V←,⍳⍴Z←' '⍴⍨2/M←⌈4×.5*⍨3÷⍨+/!⍳⍵⋄Z[G;G←⌈M÷2]←'0'⋄Z⊣{⍵∘{⍵∘{+((⊃F[⍋+/¨|(F←V/⍨,Z=' ')-⊂⍺])⌷Z)←⍕⍵}¨⍺/⍺}¨V/⍨,Z=⍕⍵-1}¨⍳⍵}⎕ ⎕: 5 5555 555555 55555555 5555445555 555544445555 55554433445555 5555444323445555 5555544321455555 555554430455555 555555444555555 555555555555 5555555555 55555555 55555 555 ``` Explanation: * `{`...`}⎕`: read a line from the keyboard, evaluate it, and pass the result to the function. * `0::0`: if the other code raises an error, return a single `0`. This is because the math fails when trying to calculate the size for a graph with 0 nodes, which happens to be the case when the output should be `0`. (The previous version had `⍵=0:0`, (if the input is `0` return `0` otherwise make the graph), but `0::0` (just try it and return `0` if it fails) is shorter.) * `M←⌈4×.5*⍨3÷⍨+/!⍳⍵`: assuming the output is a rough circle (this works), sum the factorials from `1` to `⍵` (= area of output), divide by 3 (close enough to pi), take the square root (giving radius of output), multiply by 4, and take the ceiling. This gives twice the diameter of the circle, so the output fits with room to spare. Store this in `M`. * `V←,⍳⍴Z←' '⍴⍨2/M`: make an M-by-M matrix of spaces and store it in `Z`. This will hold the output. Store a list of the coordinates of all elements in `V`. * `Z[G;G←⌈M÷2]←'0'`: set the middle element of `Z` to `0`. * `Z⊢{`...`}¨⍳⍵`: return `Z`, after applying the following function to the numbers `1` to `⍵`: + `⍵∘{`...`}V/,Z=⍕⍵-1`: for each element in `Z` with the value of the previous node: - `⍵∘{`...`}⍺/⍺`: for the current node, N times, * `⊃F[⍋+/¨|(F←V/⍨,Z=' ')-⊂⍺]`: get the free space closest to the current node, * `(`...`⌷Z)←⍕⍵`: and set that space in `Z` to the value of the current node. ]
[Question] [ # Objective Given a date, spell it out in Romanized Japanese. # I/O Format The input format is flexible. The output format is `<month spelling> <day spelling>`; note the space. You can freely mix cases in output. You may output trailing newline. # Mapping ## Months | Month | Spelling | | --- | --- | | January | `Ichigatsu` | | February | `Nigatsu` | | March | `Sangatsu` | | April | `Shigatsu` or `Yongatsu` | | May | `Gogatsu` | | June | `Rokugatsu` | | July | `Shichigatsu` or `Nanagatsu` | | August | `Hachigatsu` | | September | `Kugatsu` or `Kyuugatsu` | | October | `Juugatsu` | | November | `Juuichigatsu` | | December | `Juunigatsu` | ## Days Irregular ones are marked \*. | Day | Spelling | | --- | --- | | 1st | `Tsuitachi`\* | | 2nd | `Futsuka`\* | | 3rd | `Mikka`\* | | 4th | `Yokka`\* | | 5th | `Itsuka`\* | | 6th | `Muika`\* | | 7th | `Nanoka`\* | | 8th | `Youka`\* | | 9th | `Kokonoka`\* | | 10th | `Tooka`\* | | 11th | `Juuichinichi` | | 12th | `Juuninichi` | | 13th | `Juusannichi` | | 14th | `Juuyokka`\* | | 15th | `Juugonichi` | | 16th | `Juurokunichi` | | 17th | `Juunananichi` | | 18th | `Juuhachinichi` | | 19th | `Juukyuunichi` | | 20th | `Hatsuka`\* | | 21st | `Nijuuichinichi` | | 22nd | `Nijuuninichi` | | 23rd | `Nijuusannichi` | | 24th | `Nijuuyokka`\* | | 25th | `Nijuugonichi` | | 26th | `Nijuurokunichi` | | 27th | `Nijuunananichi` | | 28th | `Nijuuhachinichi` | | 29th | `Nijuukyuunichi` | | 30th | `Sanjuunichi` | | 31st | `Sanjuuichinichi` | # Examples * May 5th → `Gogatsu Itsuka` * September 29th → `Kugatsu Nijuukyuunichi` or `Kyuugatsu Nijuukyuunichi` * October 9th → `Juugatsu Kokonoka` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 148 bytes ``` ≔⪪”↶±UH fX>¡yüεω!Ln⎇$φL¹Kσ⎚FV” ζNθF÷θχjuu§ζθgatsu Nη¿››ηχ⁼η²⁰«F÷η²⁰§ζ÷ηχjuu¿⁼⁴﹪ηχyokka⁺§ζηnichi»«§⪪”↶±‽″÷iπλº⊗wÞαα↓✳C⍘↔ω‖σ?Hê⦃¡BUQ(U}⊞▶↔⊙” ﹪η²⁰¿⊖ηka ``` [Try it online!](https://tio.run/##ZZFNbsIwEIXX5BQjrxwplUpFV6yQqCoWrZB6Ajcx2LWxiX9QAXH2dGyStNBFFL/xS743M7VgrrZMd93Ce7k19GOvZaAEZC0kGAmeGfB43FpwVkUwzDAQLN2qY4ykAgKkrOBUzouV2cfwHnef3NEW9cY6oCsTlvIgG07bCqaPZQlrJw0ivvBrNF3VIqxMw7/pqYK2HKtky4KPQO7@LVDLDdBXx1lAPbxFBlTw0kamfZJPyCvhXEzuovRX8A9@Y0lp58XkNu8kkXvCrII320RtB/fY3NEqxbKda8/76lpH/xcmMCsxadIkgS5F9p4H4uDsVyLyLPCRIY9/E5PeSQUIA5lFlGlBFisRlFUWj8HacUm/YfNg@maWvHZ8x03gDY52bOGa/9J1z8V01j0c9A8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs in lower case. Explanation: ``` ≔⪪”...” ζ ``` Get a list of the base names. ``` Nθ ``` Input the month number. ``` F÷θχjuu ``` Print "juu" if it is at least `10`. ``` §ζθgatsu ``` Output the rest of the month name. ``` Nη ``` Input the day number. ``` ¿››ηχ⁼η²⁰« ``` If it's greater than `10` but not `20`... ``` F÷η²⁰§ζ÷ηχjuu ``` Output the tens part of the day. ``` ¿⁼⁴﹪ηχyokka ``` Print "yokka" if the day ends in `4`, otherwise... ``` ⁺§ζηnichi ``` ... print the units part of the day. ``` »«§⪪”...” ﹪η²⁰¿⊖ηka ``` Otherwise, look up the root day and append "ka" unless the day is `1`. [Answer] # [Python 2](https://docs.python.org/2/), 238 bytes Takes a month \$ m \in [1, 12] \$ and a day \$ d \in [1, 31] \$ as input, and outputs the Romaji in lowercase. ``` lambda m,d:m/10*'juu'+O[m%10]+'gatsu '+[O[~d%-20]+1%d*'ka',d/20*O[d/10]+'juu'+[O[d%10]+'nichi','yokka'][d%10==4]][20!=d>10] O=',ichi,ni,san,shi,go,roku,nana,hachi,kyuu,too,kokono,you,nano,mui,itsu,yok,mik,futsu,tsuitachi,hatsu'.split(',') ``` [Try it online!](https://tio.run/##ZZJNcuIwEIX3PkVn4RLgzmA7s6LKWWWb4gAeLzyjMQjHEuWfBZtcneluOUbOFAXV7/WT9KnF9Taenc3vTfHr/lF3v3UNHepDt8/SnbpMk0qOZRdnaZWoUz0OE6ikPJafOn7OyctivVNtrVDv83R3LPVekrKOYtovtObP2ShUN9dSthK7KH5WVZmnT4V@pVB0LBRyDK3BobY4UHly2Lt2QlvbGs81d9vbNOHoHLauddbhzUnbYTcZNMRHToudabGZWNHXjLLyzPTqx3D9MOOGYLb3dyigVHyo3EwhEOlSEsSjDiInt5QM91hKkIsQ2EUx9CIu63p1POkvgip6E7zlAtyXO/G4QdEVfeGHSoV59CbjC57MV2ru@bn5muboi5ljfqeZI1Q0jFAuZ/JlXNjhkay2oamEWgYTGjybRcsbzejmO5Q49psOwcRY0EQFcKJXeH7DEFCcNaJYK0g68vKffJBWUdS4HjowFnr6D/3dZAjZy/YQAft65b/k7ENth5Reu9l0CHrrDdLvZQfPkFWQgKJPAm@lFoMSppHQUyGLeRO49saO9PpFrFHTzwHingNxryAG2Rs5LT/p9v4P "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 236 bytes Expects `(month)(day)` as integers in \$[1,12]\$ and \$[1,31]\$ respectively. ``` m=>d=>(a="/ichi/ni/san/shi/go/roku/nana/hachi/kyuu/futsu/mik/yok/itsu/mui/nano/you/kokono/too".split`/`,m>9?"juu":"")+a[m%10]+"gatsu "+(d<11?d-1?a[d+8]+"ka":"tsuitachi":d-20?a[d/10^d<20]+"juu"+(d%10-4?a[d%10]+"nichi":"yokka"):"hatsuka") ``` [Try it online!](https://tio.run/##dVHdatswFL7vUxwEBQnPkeWusGRxcrMxttDtopdZStXIjlXHOsGWBnmBPUAfcS@SHdkrtKG7EPqk73w/SI/6l@63nT341KEpT1VxaouFKRZcF0zabW2ls7LXTvYEdyg7bIJ02mlZ68g2xxBkFXwfZGsbecRG2uEQbBxDugmywQYJekQ26Q976@/l/bt2MV2yxxDYjDGR6HV7qbJNwnaa5MASbuZKLU2qlnptkg/ENJpGibQ@JrOZSfMsklJld2aeR3G0IyU5pe8jNVo6O8wzKkceYsbqmBHhaYuux3052eOOVxyuRVwCpIQbfYRrX8Of30/wBcdWXwfZxZloKng@HUW35cGX7UPZQT79p12FUfvdUrn4WkMbwA5WdHiLO/NXmYgZg/@Prcfo/mz@7dlhNbwwdXslZj9dmsINOl/3kKZMXFTY8X3poYUC1Efa5rTnBJJEwEtpO/F46zvrdlxMDtp8doZfCUig4q3gSoz/yBkwsc424o3YT/p4FmrGUBNDryI4DzX/D1WCm1ehaiNOfwE "JavaScript (Node.js) – Try It Online") ### Commented ``` m => d => // m = month, d = day ( // a = ( // a[] is a lookup array containing: "/ichi/ni/.../kyuu/" + // 0-9: regular prefixes for 0 to 9 "futsu/mik/.../too" // 10-18: irregular prefixes for 2nd to 10th ).split`/`, // m > 9 ? "juu" : "" // start with "juu" if m > 9 ) + // a[m % 10] + // append the regular prefix for m "gatsu " + // followed by "gatsu " ( // d < 11 ? // if d is less than 11: d - 1 ? // if d is not equal to 1: a[d + 8] + // append the irregular prefix for d "ka" // followed by "ka" : // else (d = 1): "tsuitachi" // "1st" is "tsuitachi" : // else (d > 10): d - 20 ? // if d is not equal to 20: a[d / 10 ^ d < 20] + // according to the tens digit of d, // append either "" or "ni" or "san" "juu" + // followed by "juu" ( // followed by: d % 10 - 4 ? // if d mod 10 is not 4: a[d % 10] + // use the regular prefix for d "nichi" // followed by "nichi" : // else: "yokka" // use the irregular "yokka" ) // : // else (d = 20): "hatsuka" // "20th" is "hatsuka" ) // ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 273 bytes ``` g:m:$``ICHI`NI`SAN`SHI`GO`ROKU`SHICHI`HACHI`KU d:($``TSUITACHI),($`FUTSU`MIK`YOK`ITSU`MUI`NANO`YOU`KOKONO`TOU`HATSU),\:$`KA g:g,\:n:$`NICHI g[4 7]:d[4 7] g[7]:(-3_g[7]),"A",n k:(-1_d),1_,/m[-1 2 3],/:\:"JYUU",/:g k[20]:*|d j:(,/($``JYUU),/:\:m;k) f:"gatsu "/{(*x),_1_x}'j@' ``` [Try it online!](https://ngn.codeberg.page/k#eJwdj1FLwzAUhd/zK2IQ2mwZXbahGF8MgjYGG7DNw+hqI5QFVroXFQbqf/ekLzffOedy701Uk7oOwTyWJlQm1LoKNfDZhTdnfeKUlDpV68mgcnQ3tTdNsriAfPLQ4dXYsHc2mFl4TNOVg+ODddYBG2CpkXJxwEqrSVQReIao0hYS2x297dQwP1DgfLXtE3DBNBNnMsKR/cCF7EUxtStJN3TbiUIdFHvZe8+AkYztZt2pxe9ATioXRTo5hXzum+5HTo6KxY+vz2/Kip98ceGil/3lLzs9ZAR/XMrllcRgSY7Z8J4L4Jqj3tEdvaFS4mpk/ynBVAk=) I booted earlier versions. Thanks to @ngn for saving 5 bytes. [Answer] # [///](https://esolangs.org/wiki////), 293 bytes ``` /[1-/1@/ /[1/_1/ /[7/sh1/ /[4/shi/ /[9/ku/ /[// /@/-/ /-/gatsu _/ /_1]/tsuitachi/ /_2]/futsuK/ /_3]/mikK/ /_4]/yokK/ /_5]/itsuK/ /_6]/muiK/ /_7]/nanoK/ /_8]/youK/ /_9]/kokonoK/ /_10]/tooK/ /_20]/hatsuK/ /_1/juu/ /_2/2_1/ /_3/3_1/ /4]/yokK/ /K/ka/ /]/n1/ /0// /1/ichi/ /2/ni/ /3/san/ /5/go/ /6/roku/ /7/nana/ /8/hachi/ /9/kyuu/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVbNbuM2EEYvPfgpCO5hpaxtWvJ_gAB7anfXaFC0vRSOYHBt2WJkk4ZEJWsYfpJecmkfal-jL9AZUpJFOygQBhFH38x8wxmOSP_1z_6gEyVfvv_47zuSaL3PbxmLc7XlcpN3VbZhzyIVDMa7X43lQkgdZ_sshmdrFa9JvuV5Eude7t-2CIznRGxjktsXHF-L9ZrckTmlbYL_QVSr1iojmghJvB7gbRL6Z7dXuaohIO68F5G7O0IZvdbjyCFoPg9uo1e1X7OYp__L-_DwZmJw16_7YBHmmnQge_LhzgR5I3e8zePXuQ8i3q7eQlmWlXC5sguDjGETLups_LpZvN_yZezdoKHfMlu-VLs9MHj7TG0yvis3DTdziTz0QT_IRu1KM6ArpZp0iR3ht6wRNJZH86XKYnIHbbKNZR3AmkDPFZmsSOxSskJeLKO0orT7qIT0qvY8U4EjP2ByR2Mf3BL6R14IzZeJuKFtA4YA_lTovEh5BfUB-kWkZ2AAwJ-qAQwB-Oz4jNCnEGdgDMA9l-qMTAxLw2cKwEylqmkU9HCRqongsr8UhYBFS3xUeGhx6aJ9i-ZcOvDAwodmFsHQghvlmI4smqm0cPBxGY_DXxOfWDzhlwucWkV6KByiEFP8xJ3yhZjkvXi8TjMMK42baNiv8ItUw0GlcJINhxXsphuOKvwy4XBcR75IOZxUmqukw2mluky7j2n_zuXjBRzUcDP1U6u1U1InTvd69DNoN1g62vbr_vUgoAv2EQRSFx0YtCbAbiwt_LqtPfqzcr1GCP4GtXHhcUm2bPBBv3OHcIJGn_jVoqeIz4racQa1chzxM_BMbzp-QVDC4ooyCEuVbCiginsoIKX070KvO5PvP3xh86DDgo-sBQJbBDiPWZ4YYQCCQGHK0gJnBo-PrAPPDjOsZMFaLXCLmK4OElAuwoit8QyZ4Us_YjuRGnEQMWhCIw4jJiqLEVgUwojjiEFvKSNP0NpaTCOWmpPBvAU9iKesHIKccMuEKgaNY3AWmmwWfdZHocXOwWcs5TBBKKPoYVoBE3bxIZM49Rl8RzAP2UbBNGL4OYAwxvWh94QlZbpQHdgvVpX0HsoLdbaneqfTIbnmmYbDHktfXyBwGuO1ke7a5GmHd4dt767Q8S73GhdLugKLFVrg4e3qcQi5L_QCqNd0fkx3p84xXZ0iWutVocEAv5v5mh6_ncjxadXNcp2Jvff-5r1_ot2teo4zzzfhvmGkp935yszivNhqcDcXDvlQBvQrr_NC1pWtVOanTRnZvVttXSxHu3RoV6a-U7dYrqBqtqwvL3b-Dw) Newlines are added just for clarity and stripped before execution. Input is expected in `[M-D]` format and is appended at the end of the program since the language does not support any form of input. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~255~~ 235 bytes `%W()` declares a space-separated array of strings, which is useful for saving bytes over a `split` solution. An empty string interpolation `#{}` is needed to make the first element an empty string. -3 bytes by incorporating dingledooper's array scheme for storing the special day cases. ``` ->m,d{n=%W(#{} ichi ni san yon go roku nana hachi kyuu too kokono you nano mui itsu yok mik futsu tsuitachi hatsu) 'juu'*(m/10)+n[m%10]+"gatsu "+(d==20||d<11?n[~d%-20]+'ka'*(1%d):n[d/10]*(d/20)+'juu'+(d%10==4?'yokka':n[d%10]+'nichi'))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVA9TsMwFN57iqdWUeI2TePAgBChCxMXYIgq5NZOY4KfS2oLRW25CEuE4FCcgUvwEjoxWH7-_uzP75-NX7fdR5l_eVfOr75_5rcmlgfMg4docjiB3lQaUMNeILQWYWuhsbUHFCigEj1bt96DsxZqW1u0JBtoC8Zr0G7vCanB6BpK359oaTc4K0EzG4VP3ofTyCx4ymZYmICnq9l425MwnkUyz7P0eJQ3nC-xeJPBPCM-rAV5eCDZNRaSrKtpJBcZJQxxZKOYPL9chnQ7aXvVEBxi3ylk7HSu3DXqxetGQSiFUyFM4N7vHWizs43TuIXSNuAqBU4RvBbOqaaNAa0DVEoqCRoHvvS4cZo-iUqr53K0o7oQ3VFoguo1ytI0jXnMWZL8w7L4gjOWGLE7lMUjT4xFV8VAkxTt6vzOrvvbfwE) ]
[Question] [ This challenge is a riff on Dion's challenge "[Is this a rectangle?](https://codegolf.stackexchange.com/q/203098/53884)". The goal of this challenge is to write a program to decide whether or not some collection of tuples of integers represents a hypercube of some dimension. ### Background A [hypercube](https://en.wikipedia.org/wiki/Hypercube) is a generalization of a square. * A \$0\$-cube is a single point. * A \$1\$-cube is a line segment. * A \$2\$-cube is a square. * A \$3\$-cube is an ordinary cube. * An \$n\$-cube is a connected geometric object consisting of pairs of parallel line segments, perpendicular to each other and of the same length. ## Example For example, if you are given the input \$\{(0, 4, 0, 9), (2, 2, -4, 9), (-2, 0, -6, 9), (-4, 2, -2, 9)\}\$, then you should return a truthy value because these four points define a \$2\$-cube (a square). You are allowed to input the data in any reasonable format—but the computation needs to work regardless of the input order of the points. An \$n\$ cube has \$2^n\$ vertices, so if the list of numbers does not contain \$2^n\$ numbers, you must return a falsey value. ## Challenge This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins. ## Test data Cubes: ``` [(1,9,7,7)] [(1),(2)] [(9,1,9),(1,2,9)] [(0,0,5),(0,1,5),(1,0,5),(1,1,5)] [(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] [(0,0,0),(0,3,4),(0,-4,3),(0,-1,7),(5,0,0),(5,3,4),(5,-4,3),(5,-1,7)] ``` Non-cubes: ``` [(1,0,0),(0,1,0),(0,0,1),(1,1,1)] [(0,0,0),(0,0,1),(0,1,0),(1,0,0)] [(1,0,0),(0,1,0),(0,0,1)] [(1,0,0,0,0),(0,1,0,0,0),(0,0,1,0,0),(0,0,1,1,1)] ``` If you'd like more test data, or if you'd like to *suggest* more test data, let me know. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 44 bytes ``` {≡/((÷∘⊃⍨1↓⍋⌷¨⊂)⍤1∘.(+.×⍨-)⍨)¨⍵(,⍳2⍴⍨⌊2⍟≢⍵)} ``` [Try it online!](https://tio.run/##nZDBasJAEIbvPsXeskvV7gRE0rcJlBRpIEW8iHjRIjW6pVBKeystPeReRehR32ReJP7ZNRiKYNM97Pz7z34zsxvexa3rYRgnNzk/vvQSnj3pPMI@4vnHpZS7DT@8cTplkxHPntkseLnZZpxOFJsvQrItL9q7V@RbcDKFnFnLJptvn80KDi9TqHeefyKhxnk@sNXNGk4fMmLzc@VFYS/2oOD3eXHvJbfeuIEy6YREILqiq0SdNRAEmpRs@vXAktVCi45CoCKQO5E9nWWL29qxNkA4ls6w2vU9QocSruD/WG37ljPRcRhdzmRnDiCDwvERav7Vqff@idUHtsJXnlCVv/8O7B4 "APL (Dyalog Unicode) – Try It Online") the argument `⍵` is a vector of coordinate vectors `,⍳2⍴⍨⌊2⍟≢⍵` build a hypercube as the cartesian product \$\{0,1\}^{\left\lfloor \log\_2\left|\omega\right|\right\rfloor}\$ `≡/(`*f*`)¨⍵(`..`)` evaluate *f* for `⍵` and the 01 hypercube, and test if they match `∘.(+.×⍨-)⍨` matrix of pairwise distances `(÷∘⊃⍨1↓⍋⌷¨⊂)⍤1` sort each row and divide by its second element [Answer] # [Python](https://docs.python.org/3.8/), ~~262~~ \$\cdots\$ ~~305~~ 303 bytes Saved a whopping 19 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! Added 118 bytes to fix a bug kindly pointed out by [xnor](https://codegolf.stackexchange.com/users/20260/xnor), [Peter Kagey](https://codegolf.stackexchange.com/users/53884/peter-kagey) and [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2). ``` lambda l,R=range,L=len:(n:=L(l))<2or(d:=L(bin(n))-3)and(p:=sorted([sum((x-y)**2for x,y in zip(i,j))for i in l for j in l]))==[i*p[n]for i in R(d+2)for _ in R(2**d*math.comb(d,i))]and(K:=R(L(l[0])))and L({sum(([sum(l[i][j]for i in R(n))for j in K][j]-n*l[i][j])**2for j in K)for i in R(n)})<2 import math ``` [Try it online!](https://tio.run/##nVLBbqMwEL3nK0a9ZIZ1VkC66gat97iX5hT15qKKFLJ1BAYZR2o2yrentiEJadpDFyPxZua98RvjZmteajX92ejDij8eyqxa5hmUbMF1pv4WbM7LQiWoEj7HkuhXXGvMXbCUChXRZEqZyrFJeFtrU@Qo2k2F@DrZUhDEq1rDK9uCVPBPNijZmsjlpMuU4ODaw5SIcyGDRqj0RFhg/i32/KcujIMgD6rMvHx/rqsl5kwSpW77@4Qv0BoUoW3kDMEcd96It1MKmYr1sLHqfPjN711tooKedfTd1ehCtLcHMJJVY0cF5@Ngita0wEGMwD5CYMRgxuDOvpQyeNCbImXnGjHAmF1XQgb2/eHK9hv1MDpnoz77QU/HCc/KI3TRWRk55Z@sbL8iDXvCtTS8kA74xy7R/0vD3vCgywkOJgrfDXd5LDNfmPWc2MEvHt2n53Wluhrog8SnvyDsFjHLjQa4j07YrqE@HWmOm/HjJr67fR4z6GA0HdPIXVjDCndl/e1M/GYtX6EhDxstlcHVzc7sYfIbdu0edlq0nBfp/oYObw "Python 3.8 (pre-release) – Try It Online") Inputs a list of points and returns `True`/`False`. **How** Calculates the square of the distances between all possible pairs of points (including self-pairs and both \$(p\_i,p\_j)\$ and \$(p\_j,p\_i)\$ for all points \$p\_j\$ and \$p\_i\$ where \$i\neq j\$) and normalises them by the smallest non-zero square distance. For an \$n\$-cube we should then see a pattern of integers \$i = 0,1,\dots, n\$ each occurring \$2^{n}{n\choose i}\$ times. This corresponds with the \$0\$s for all the self-pairs, and the square of the lengths of all the sides being \$a^2\$, and the square of the lengths of all the diagonals being \$2a^2, 3a^2,\dots, na^2\$. **Correction** Also checks that the given vertices are all equidistant from the centre of mass. [Answer] # Python 3, 339 338 ``` lambda P:1==L(P)or P in map(g,permutations(P)) from itertools import* L=len Z=zip D=lambda a,b:sum(x*y for x,y in Z(a,b)) def g(Q):B=[[x-y for x,y in Z(p,Q[0])]for p in Q[3-L(bin(L(Q))):]];return any(D(a,b)or D(a,a)-D(b,b)for a,b in combinations(B,2))or{tuple(x+sum(y)for x,y in Z(Q[0],Z(*C)))for C in product(*[(p,(0,)*L(p))for p in B])} ``` [Try it online!](https://tio.run/##nVPLbtswELzrKxa5eKnSgGS3SK2CPThGTzrYQE9WdJBtKhWgB0FSgFXD3@4uFaV@pYdUIKDlzM5wlw/V2V9NPf2q9CkXz6cyqza7DJZRKESMS9ZoWEJRQ5UpfOFK6qq1mS2a2hDJvFw3FRRWats0pYGiUo22vheLUtbeWvwulLcQg2fGN5FpK9z7HeTku@edc14jEWS1kzm84IpFc5Ek@/FNjuKrJEhZ6kDloFUyHce4KWqMScRYlKbftLStriGrO1z0rpTsgoyNF7ihuVMT7vTbpiLx0MqcTxglH2yrSon7T67Mjl0V4Jbna/SfaC1HPDlY6WbXbi36CRWIAWd@jOqV74ucp@x4stJYAwISD@hLEgw5zDg80mAph5@6lSk/c4wDTvg9E3Cg8cXR9A@HMDyj4YC@4@lygrPyLXSzszJ0yh9ZaT4iDYaEe2lwJb3If3MJ/18aDAVfuPwNLzoKbpq73pZZT8yGnIkLP7h1/9yvO9VdQ@8At0eQep4W2I6e28nj5@2Iw2sYTkf07uiGWS7dHeuvV9QXYESORlq09JzcXOmitpg/HOwRxt/hYI5w0IkRQqbHB3b6Aw "Python 3.8 (pre-release) – Try It Online") Takes a `set` of points as input. Pseudocode explanation: ``` def f(points): let n = log_2(|points|) for each permutation Q of the points: let q be the first point in Q let B be the following n points, with q subtracted from each if all pairs of points in B are orthogonal and have equal magnitude: let S be the set of points which can be obtained by summing q and any subset of B if S == points: return True return False ``` Can definitely be golfed further but it's bedtime. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 258 bytes ``` x=>(q=(x,z)=>g=x.flatMap(a=>x.map(b=>z*a.reduce((s,v,i)=>s+(v-b[i])**2,0))).sort((a,b)=>b-a))([...x,x[0].map((_,i)=>x.reduce((s,v)=>s+v[i],P=0)/(K=x.length))],K)+''==q([x.slice(D=~Math.log2(K)).map(_=>!P++||.5),...x.map(_=>[...(K++).toString(2)])],g[0]/~D|0) ``` [Try it online!](https://tio.run/##lY5Bb4JAEIXv/RX25IyM60JijDHLyRsxMemRbMyiiDQUFCjZGONfpwvSlsbGpqeZ3ffeN@9VVarY5vGxHKfZLqz3otbChZMATWcUbiQ02yeqXKkjKOFq9maWQLjnkWJ5uHvfhgAFVRQbb2FBNQ78WOJo5BBHRFZkeQmgKDByMFaI4DPGNGmfyxYFmzaq@7AWVRkOrQXHCXimQxKmUXlAlOShNRwKcQJfsyKJTWYpritVHliSRQ545moD3gj3eW1ZlwubIjU3P3@bAuBZFrIyeynzOI3AQWnAkek0uS4vHOvF0zZLiywJGybswfdtmtOMZlIOEBeDe1mS79zEO40Tp6nROdnttLu33b5/zzQe3mVu02xdxn5wp@/9ztpd9qbbPRb/gzk32rz1OGb@p@sDb9/f7/xj/@pUfwA "JavaScript (Node.js) – Try It Online") Similar to [Noodle9's answer](https://codegolf.stackexchange.com/a/204661/), but generate another square to compare rather than use formula and add midpoint like normal ones [Answer] # [JavaScript (Node.js)](https://nodejs.org), 182 bytes ``` x=>(g=(q=(x,z)=>x.flatMap(a=>x.flatMap(c=>x.map(b=>z*a.reduce((s,v,i)=>s+(v-b[i])**2+(v-c[i])**2,0)))).sort((a,b)=>a-b))(x,K=x.length))+''==q(x.map(_=>[...(K++).toString(2)]),g[K]|0) ``` [Try it online!](https://tio.run/##lU7RaoNAEHzvV@Qtu7oed0IJEs4fkD718ZByGrUWq4leRUL/3Z5RWktKSvZlZ5iZnX3Tve7Stjwar24O2ZjLcZAhFBJOEgY6owwHllfaPOkj6DVJJ/JuQSLDs6NZmx0@0gygo55KG@tc6L1ElTE6jj/hdMHE0Q7rmtYAaEqsV3sJoq2L5MCqrC7MK6K73Up5grnjRYaKMQaR6yIzzbNpy7oAH2OkQkXxJ8dx/5A2dddUGauaAnJQSlBAO9rF8QZxv7mWY1L@LF5pnDg9Wp2TuGyxcHHhf2cmD18y87ZoyYgbPWvvT1Ys2VkXq1v8n5uB1YKLx7f7nl9veNf@9c@/8PdP4xc "JavaScript (Node.js) – Try It Online") Check sums of length squares of A-B-C, where A,B,C can be same [Answer] # [Haskell](https://www.haskell.org/), 139 bytes ``` import Data.List import Data.List.Ordered c p=has[(2^n,n*2^n)|n<-[0..]](length p,length$group(sort[sum$(^2)<$>zipWith(-)x y|x<-p,y<-p])!!1) ``` [Try it online!](https://tio.run/##XYw9C4MwFEX3/goFh6RE8St00U4dCx07hAhBxYRqDEkELf53G6pdyoN7D5fD48y82r7fNjGoUVvvxiyL7sLY0/8QPXTT6rY51Z4qOTMEpJVE8uwSrrIISRxFlIK@lZ3lnkI7BJ0eJwWMe0XMNASgSmERXN9CPYXlIISzt6xzESq0uKDQ9xO4DUzIUmkhbVATEiN3FLnOUP7tMEfZDgm6OMCHgQ8D/wy8G3T7AA "Haskell – Try It Online") ]
[Question] [ # Task Your task is to make the smallest function/program that can, when gives an number N, return/print: the number of possible choices `a, b` such that \$1 \leq a < b < N\$ and `a` and `b` have exactly one common digit in base 10 (there exists a digit, and only one digit, which appears both in `a` and `b`, for example 12 and 23, where 2 appears both in 23 and in 12) note - 1 and 11 count as having exactly one common digit, as 1 is a digit which appears in both of them, and it's the only one that appears in both of them. You function/program should work for all n from 1 to 1000. # Test Cases ``` 20 -> 63 40 -> 267 60 -> 575 80 -> 987 100 -> 1503 1000 -> 235431 ``` # Rules This is a code golf so the lowest score in bytes wins. Good luck! [Answer] # [J](http://jsoftware.com/), 39 bytes ``` 1#.[:,1=[:(</*([#@[[email protected]](/cdn-cgi/l/email-protection).)&":"0/)~1}.i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1oq10DG2jrTRs9LU0opUd6vQcdPV09TTVlKyUDPQ16wxr9TL1/mtycaUmZ@QrmBkr2CqkKRgZQLhGZuZgvgmUb2puCuabQfmWFhB5Cyjf0NQAYoChAcwEY1MTY0OYmAHXfwA "J – Try It Online") Interestingly, almost exactly the same as Adam's APL answer, though I arrived at it independently. A bit more verbose in J, though... ಥ\_ಥ [Answer] # APL (Dyalog [Extended](https://github.com/abrudz/dyalog-apl-extended) or 18.0), ~~24~~ 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Full program. ``` ≢⍸∘.(<∧1=∘≢∘∪∩⍥⍕)⍨1↓⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdoeD/o85Fj3p3POqYoadh86hjuaEtkAkSA5Idqx51rHzUu/RR71TNR70rHvVuftQ3VdcQpPG/AhgUcBkZKDzqnatrp2BmzAUTM4GJGZmZwwXNYIKm5qZwQQuYoKUFQqWhAUzU0NTAGFkYbq6xqYmxIQA "APL (Dyalog Extended) – Try It Online") `⎕` prompt for N from the console `⍳` first N integers `1↓` drop the first one (0)  `⍨` apply the following function using those integers as both left and right argument:   `∘.(`…`)` apply the following function between all combinations of left and right elements:    `⍥⍕` stringify (make into character list) both arguments, then:     `∩` find the intersection between the character lists    `∪` find the Unique elements of that    `∘` then:     `≢` count that    `∘` then:     `1=` check if that is equal to 1    `∧` and    `<` the left argument is less than the right argument `⍸` find the **ɩ**ndices of the trues `≢` count them [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L¨2.Æʒ`ÃÙg}g ``` -2 bytes thanks to *@Shaggy*. [Try it online](https://tio.run/##yy9OTMpM/f/f59AKI73DbacmJRxuPjwzvTb9/38jAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/n0MrjPQOt52alHC4@fDM9Nr0/zr/o40MdEwMdMwMdCwMdAwNwNggFgA). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] ¨ # Remove the last value to make the range [1, input) 2.Æ # Get all non-duplicated combinations of size 2 of this list ʒ # Filter this list of pairs by: ` # Push them separated to the stack à # Only keep the digits of the first number which are also in the second Ù # Uniquify those remaining digits g # Get the length of the remaining digits (only 1 is truthy in 05AB1E) }g # After the filter: get the amount of remaining items by taking the length # (which is output implicitly as result) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṖDŒcf/QLƊ€ċ1 ``` A monadic Link accepting a non-negative integer which yields a non-negative integer. **[Try it online!](https://tio.run/##y0rNyan8///hzmkuRyclp@kH@hzretS05ki34f///w0NDAA "Jelly – Try It Online")** ### How? ``` ṖDŒcf/QLƊ€ċ1 - Link: integer, N e.g. 1000 Ṗ - pop (implicit range) [1,2,3,...,999] D - to decimal (vectorises) [[1],[2],[3],...,[9,9,9]] Œc - unordered pairs [[[1],[2]],[[1],[3]],...,[[1],[1,9]],[[2],[3]],...,[[9,9,8],[9,9,9]]] € - for each: e.g. [[2,5,2],[2,7,0]] Ɗ - last three links as a monad: / - reduce by: f - filter keep [2,2] Q - de-duplicate [2] L - length 1 1 - literal one ċ - count occurrences 235431 ``` [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` lambda n:sum(len(set(`a`)&set(`b`))==1for a in range(1,n)for b in range(1,a)) ``` [Try it online!](https://tio.run/##TYvNDoMgEAbvPMWmhwYSNaL1pyb4JD2IVlsSXQnQg09vgV6a7GEy36w@3HvH4lzE41zlNj4lYGc/G11npHZ2dJADu0YYB8aE4MtuQIJCMBJfM@UJsqDGfyUZO9Wmd@PAHpaQEKwK59B4kVn3VNgRwGQCAZvUVKFLYpJZvSpHL2l/YYyA8ftC0ZM2vvEfEKYEjD8hprPIIe2hLsktQlE3pI5UNRVpI93bhvA8Iq/yMvCvLatbyb8 "Python 2 – Try It Online") Thanks to @SurculoseSputum for translating my Python 3 program into Python 2, helping me golf the v3 and creating a shorter one in Python 2. ## [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~99~~ 79 bytes ``` lambda n:sum(len({*str(a)}&{*str(b)})==1for a in range(1,n)for b in range(1,a)) ``` [Try it online!](https://tio.run/##TY3LasMwEEX3@opBi6IpSbCi@FGD@yXZyNRuDY4sJHkRjL7d1cgEsjtz73CufYa/xajGun2EDu77rB/9jwbT@vUh5sGI7dMHJzTGj4N6jNh1clwcaJgMOG1@ByFPBinq3yONuIfBB5/MnPNrAedvqBS7ZbhWNasylXXJmkxfTc1kkVGWhSI@flV5UzI5GKMVktJQll@8nacg@N1wbBmk3J5gWUMapf5Vk4bj0adqMkEkosA6Oka@pTvS2zbmKoLYkicix/0f "Python 3.8 (pre-release) – Try It Online") [Answer] # JavaScript (ES6), 83 bytes ``` f=(a,b=--a)=>a?--b?!~-new Set((a+[,b]).match(/(.)(?=.*,.*\1)/g)).size+f(a,b):f(a):0 ``` [Try it online!](https://tio.run/##FczBCoIwHIDxe0@xwMP@us0ZEWFMTz1BRxOctplhW6gUJPrqax1@fLfvId9ybIbuNVFjb8o5LbAktaBUgshkTmmdb1dq1Add1ISxjApSl8CecmruOMYMcC5YSFh4TSBuAdjYfVWk/xNIfSDl7lTsOEF77@AdvYTzcsO0Hc7SbwwSGWqsGW2vWG9bXAWzWdCaoWDW2MBSAbgf "JavaScript (Node.js) – Try It Online") ### How? To test how many distinct digits the integers \$a\$ and \$b\$ have in common, we concatenate them with a comma in between and apply the following regular expression: ``` /(.)(?=.*,.*\1)/g (.) // a digit in the first integer (?= // followed by: .* // some optional digits , // a comma (the separator between the 2 integers) .* // some optional digits \1 // the same digit in the 2nd integer ) // end of lookahead ``` We then turn all matches into a set and test whether its size is exactly \$1\$. For golfing reasons, we actually decrement the size and test whether the result is \$0\$: ``` !~-new Set(...).size ``` When nothing is matched, `match()` returns *null* rather than an empty array, which is usually painful to deal with if we want to apply some array method or property to the result. But we don't have to worry about that here because `new Set(null)` simply generates an empty set, which is what we want. --- # Non-recursive, 93 bytes ``` n=>{for(t=0;--n;)for(b=n;--b;)t+=new Set((n+[,b]).match(/(.)(?=.*,.*\1)/g)).size==1;return t} ``` [Try it online!](https://tio.run/##JY3LDoIwEEX3fkUXLDo8ChhjTJrBlV/gEkl4WBCDU1OqJhL8daxxcW5yNudeq2c1Nqa/24j0WS0tLoTZ1GrDLSYyikjCT2okJ7UEGyCpFzsqyzkFeVgXIG6VbS485gL4HoUfCv@UQtwBiLF/K8RUGmUfhpidF5mvk5BtHFvHzpEm/0mKlXBXh8q1iGHGGk2jHpQYdMdLb6KZfTLmTS0nmEuA5Qs "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~16~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` oì à2 Ërf â ʶ1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=b%2bwg4DIgy3JmIOIgyrYx&input=NDA) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 83 bytes ``` (t=0;Do[If[Tr[1^Intersection@@IntegerDigits@{i,j}]==1,t++],{i,#-1},{j,i+1,#-1}];t)& ``` [Try it online!](https://tio.run/##HcexCsIwEIDhVxEKYslJLyIilECGLt0c3EKEUGK8QlNIbwt59qgdfvi/xfHHL45pcjWoemKF/bCa8W2eycjXGNmnzU9Ma9T6r@DTQIF405lgLlYpCSyEhR@bsyyQZyAh97c9t8f6SBT50OnQ6XxBuCLcEO4IEvew1PoF "Wolfram Language (Mathematica) – Try It Online") [Answer] # Java 8, ~~166~~ 156 bytes ``` n->{int r=0,a=n,b,i;for(;a-->2;)for(b=a;b-->1;){var s="";for(var t:(a+s).split(s))if((b+"").contains(t)&!s.contains(t))s+=t;r+=s.length()==1?1:0;}return r;} ``` [Try it online.](https://tio.run/##TZDBboMwDIbvfQqPwxSLgEI1TRNRuidYLz1WPQQKXToaUGI6TYhnZwnrYQdb/i3b@n5f9V1n1/PXUnfae/jQxk4bAGOpca2uG9hHuTagZjFblKEzb0LypMnUsAcLChab7aY44JTgWllecSPb3jGps2y3lRjrSmlZBVlInO7agVdJsg5FQSXTqcfcD50h5hFNy1iVJgnmdW8poHlG@Pzk/0v0qSLpUuXzrrEX@mSoVPFelELOrqHRWXByXmTkHcaqC7wP7HtvznALZ9iBnLGX4wk0/rmNRNGKgRJs8x3dH0/TVvAXwV8FfxO8EGuIGdcFgMOPp@aW9yPlQ7hGnWUmTUpIUpuHx@Hja/PyCw) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int r=0, // Result-counter, starting at 0 a=n,b,i; // Integers a,b,i for(;a-->2;) // Loop `a` in the range (n, 2]: for(b=a;b-->1;){ // Inner loop `b` in the range (a, 1]: var s=""; // Create an empty String for(var t:(a+s).split(s)) // Loop over the digits of `a`: if((b+"").contains(t) // If `b` contains this digit &!s.contains(t)) // and the String doesn't contain this digit yet: s+=t; // Append this digit to the String r+= // Increase the counter by: s.length()==1? // If the length of the String is 1: 1 // Increment the counter by 1 : // Else: 0;} // Leave the counter the same by increasing with 0 return r;} // After the loops, return the counter-integer as result ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` IΣENLΦι∧λ⁼¹LΦχ∧№IιIν№IλIν ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDM6@gtMSvNDcptUhDU0fBJzUvvSRDwy0zpwQokKmj4JiXopGjo@BaWJqYU6xhiK7C0ACixDm/FGZyJtAYMCNPE8RCSOQgSSAB6///jQz@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input `n` as a number E Loop `0<=b<n` ι `b` Φ Loop `0<=a<n` λ `a` ∧ Is non-zero and LΦχ Count of digits where №IιIν Digit present in `b` ∧ And №IλIν Digit present in `a` ⁼¹ Equals `1` L Number of matching values Σ Sum of numbers I Cast to string for implicit print ``` ]
[Question] [ Convert a hexadecimal number (of any size) into a binary number. **Input** A *POSITIVE* hexadecimal number with a `0x` in the beginning. A valid input will always match the following regex: `0x[0-9a-fA-F]+`. If the input is *not* a valid hexadecimal number, that is, anything not matching this regex, the output should be `0`. **Output** The hexadecimal converted to binary. **Winning** Original Code-Golf Rules, Lowest amount of bites `(bytes)`. **Examples** ``` IN: 0x12 OUT: 10010 IN: 0xFF OUT: 11111111 IN: 0XFF OUT: 0 IN: #0ac4 OUT: 0 IN: 0x00101011 OUT: 100000001000000010001 IN: 0x525600 OUT: 10100100101011000000000 IN: 0x58f70555118ec400 OUT: 101100011110111000001010101010100010001100011101100010000000000 IN: 0x6669795966AF3000 OUT: 110011001101001011110010101100101100110101011110011000000000000 IN: 0b018474 OUT: 0 IN: 9577383 OUT: 0 IN: -483355 OUT: 0 IN: -0xf9ad92 OUT: 0 ``` [Answer] # Python 2, ~~67~~ ~~62~~ ~~60~~ 59 bytes ``` n=input() try:print bin(int(n,n[1]<'x'))[2:] except:print 0 ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioclVUlRpVVCUmVeikJSZpwGkNfJ08qINY23UK9Q1NaONrGK5UiuSUwtKoKoM/v9XN6hISU1MSUpNTVMHAA) Version that errors on invalid input (27 bytes): ``` lambda n:bin(int(n,16))[2:] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ5WUmaeRmVeikadjaKapGW1kFfu/oAgooJCmoW5QkZKamJKUmpqmrvkfAA) [Answer] # Pyth, 15 bytes ``` .B&qr0<z2"0x"vz ``` Explanation: ``` vz Evaluate the input as a literal, to get a number (casts to integer for hexadecimal input) <z2 Select the first two characters of (string) input r0 cast to lowercase (0X -> 0x) q "0x" check whether the text starts with "0x" or "0X" (negative numbers don't) & If it does, return the casted number .B and convert to binary string ``` [Test Suite](http://pyth.herokuapp.com/?code=.B%26qr0<z2"0x"vz&input=0101&test_suite=1&test_suite_input=0x12%0A0XFF%0A11111111%0A%230ac4%0A0x00101011%0A0x525600%0A0x58f70555118ec400%0A0x6669795966AF3000%0A0b018474%0A9577383%0A-483355%0A-0xf9ad92&debug=0) With a rules clarification (that `0x` must be lowercase) in the OP, you can remove `r0` for 13 bytes. ``` .B&q<z2"0x"vz ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` Î2£„0xQi¹Hb ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4z@jQ4kcN8wwqAjMP7fRI@v/foMLMzMzS3NLU0szM0c3YwMAAAA "05AB1E – TIO Nexus") **Explanation** ``` Î # initialize stack with 0 and push input 2£ # get the first 2 chars of input „0xQ # compare to "0x" i # if equal ¹H # convert input from base-16 to base-10 b # convert to binary ``` [Answer] ## Batch, 402 bytes ``` @echo off set/ps= set r=0 if not %s:~0,2%==0x goto g if %s%==0x goto g if %s:0=%==x goto g set t=%s% for %%h in (0 1 2 3 4 5 6 7 8 9 a b c d e f)do call set t=%%t:%%h=%% if not %t%==x goto g set s=%s:~2% for %%h in (0.0000 1.0001 2.0010 3.0011 4.0100 5.0101 6.0110 7.0111 8.1000 9.1001 a.1010 b.1011 c.1100 d.1101 e.1110 f.1111)do call set s=%%s:%%~nh=%%~xh%% set r=%s:.=% :g echo %r:*1=1% ``` Takes input on STDIN. 8 lines are then mostly wasted on input validation, so the interesting lines are line 11, which replaces each hex digit with its binary equivalent, but due to Batch limitations, with a leading `.`, line 12, which deletes all the `.`s, and line 14, which removes leading 0s. However this fails for inputs like `0x0` so I "invalidate" those which means 0 is output instead. [Answer] # PHP, ~~66 65~~ 63 bytes ``` <?=decbin(hexdec(preg_filter("#^0x([a-f\d]+$)#i","$1",$argn))); ``` run as pipe with `-F`. Without the `0x`, the worst problem would be that both `hexdec` and `base_convert` simply ignore characters that are not hex; but with it, there has to be an explicit validity check anyway. --- 45 bytes without the `0x`: ``` <?=decbin(ctype_xdigit($argn)*hexdec($argn)); ``` [Answer] ## JavaScript (ES6), ~~109~~ 108 bytes Works for any input size. ``` s=>/1.*|0$/.exec((/^0x([\da-f]+)$/i.exec(s)||'_0')[1].replace(/./g,d=>(+`0x1${d}`).toString(2).slice(1)))[0] ``` ### Test cases ``` let f = s=>/1.*|0$/.exec((/^0x([\da-f]+)$/i.exec(s)||'_0')[1].replace(/./g,d=>(+`0x1${d}`).toString(2).slice(1)))[0] console.log(f('0x12')); // OUT: 10010 console.log(f('0XFF')); // OUT: 11111111 console.log(f('#0ac4')); // OUT: 0 console.log(f('0x00101011')); // OUT: 100000001000000010001 console.log(f('0x525600')); // OUT: 10100100101011000000000 console.log(f('0x58f70555118ec400')); // OUT: 101100011110111000001010101010100010001100011101100010000000000 console.log(f('0x6669795966AF3000')); // OUT: 110011001101001011110010101100101100110101011110011000000000000 console.log(f('0b018474')); // OUT: 0 console.log(f('9577383')); // OUT: 0 console.log(f('-483355')); // OUT: 0 console.log(f('-0xf9ad92')); // OUT: 0 ``` [Answer] ## REXX, 45 bytes ``` arg '0X' n if n>'' then say x2b(n) else say 0 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 149 bytes ``` . ;$& T`L`l f 71 e 70 d 61 c 60 b 51 a 50 9 41 8 40 7 31 6 30 5 21 4 20 3 11 2 10 ;(\d{4}) $1 ;(\d{3}) 0$1 ;(\d\d) 00$1 ; 000 ^(?!0{7}x).* 0 0{7}x0* ``` (note the trailing newline) [Try it online!](https://tio.run/nexus/retina#Lc27asNAEIXh/n@LECfIBpuZ3Z294CKkUZqUKVKYIFmyKj@AwPjZlbUSppjvHBjmpfnolgPHzStf3Wd3ZSIpF5IwEpWBKJwxpceEQlAyQUh4JeIFwykBJ3hUcahwbE7jLdy3bPTPvlr@w2msXkNdwk/z9iS3dJ@3hx3CStmxLDKrQ77blmfph4DMIvoYrTRnsR5X5CmJmanmyxDWKsZYUrES43vrHy/kLJpDChRLyWfPPmTvzdjLPJV@LO4X "Retina – TIO Nexus") Here is an alternate solution at the cost of 7 bytes: [Try it!](https://tio.run/nexus/retina#LY25agNBEETz@gtj2awEEt0z03OwgXGyThw6MOhgj9FG/oABjb593VqbDt6rgqJfmo9@OaDdvOKr/@x/MNcrgqZcJ3jlWAeIMtUIpwzVwyqlOhilrQasPM55TEHsGYzjhUt7BqFtTvnm7lts@M@tOv2HU1Zfg4Jwad6e6BbuZXvY6XRV2mFZqLABfXcdnmmYHKgQ8eNYVYx4HavEOZCIMMfr5NbKe59CkuT9e2cfL2gkji44JAnBRou9i9aKYE9lTkNO5hc "Retina – TIO Nexus") [Answer] ## perl, 25 (code 24 + 1 flag -n) ``` printf"%8b",/^0x/i?hex:0 ``` [Answer] ## JavaScript (ES6), ~~116~~ 111 bytes ``` f= s=>/^0x[\da-f]+$/i.test(s)?s.replace(/./g,c=>parseInt(4+c,36).toString(2).slice(-4)).replace(/0+10*(.)/,'$1'):0 ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o>0 ``` Not limited to 53 bits of precision. Edit: Saved 5 bytes by rewriting my digit conversion, which also reduces my language requirements to ES6. [Answer] # 8086 machine code - 63 bytes Works for any input up to 125 chars (the maximum command line length in DOS) ``` 00000000 be 82 00 bf 3f 01 89 fa ad 3d 30 78 75 24 ac 3c |....?....=0xu$.<| 00000010 0d 74 22 2c 30 3c 09 76 08 24 df 2c 07 3c 0f 77 |.t",0<.v.$.,.<.w| 00000020 11 b1 04 c1 e0 0c d0 e4 0f 92 c0 0c 30 aa e2 f6 |............0...| 00000030 eb dc ba 3d 01 b0 24 aa b4 09 cd 21 c3 30 24 |...=..$....!.0$| 0000003f ``` [Answer] # JavaScript (ES6), ~~53~~ ~~52~~ ~~49~~ ~~50~~ ~~52~~ 45 bytes (Non-competing as it doesn't handle inputs of *any* size; I just got lucky with the sample inputs) ``` f= h=>+/^0x[\da-f]+$/i.test(h)&&(+h).toString(2) console.log(f`0x12`); console.log(f`0XFF`); console.log(f`#0ac4`); console.log(f`0x00101011`); console.log(f`0x525600`); console.log(f`0x58f70555118ec400`); console.log(f`0x6669795966AF3000`); console.log(f`0b018474`); console.log(f`9577383`); console.log(f`-483355`); console.log(f`-0xf9ad92`); ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 24 bytes ``` q2/("0x"={seu:~Gb2bo}&;0 ``` [Try it online!](https://tio.run/nexus/cjam#@19opK@hZFChZFtdnFpqVeeeZJSUX6tmbfD/v0GFqYWbuYGpqamhoUVqsomBAQA "CJam – TIO Nexus") **Explanation** ``` q e# Read the input 2/ e# Split it into 2-length segments ( e# Pull out the first segment "0x"= e# Check if it equals "0x" { e# If it does, run this block: s e# Join the segments back together eu e# Make the string uppercase :~ e# Eval each character (A-K are 10-20) Gb e# Convert from base 16 to base 10 2b e# Convert to base 2 o e# Output the binary number }& e# (end of block) ;0 e# Delete the top stack element and push 0. If the block was run, nothing is left e# on the stack, so the program terminates with an error before pushing 0. ``` [Answer] ## JavaScript (ES6), 107 characters ``` f= b=>/0x[\da-f]+$/i.test(b)&&b.match(/[\da-f](?!x)/gi).map(x=>((+('0x1'+x)).toString(2)).slice(-4)).join('')||0 console.log(f('0x1f')) console.log(f('0x6669795966AF3000')) ``` [Answer] # [Perl 6](http://perl6.org/), 35 bytes ``` {(m/^0x(.+)/&&:16(~$0)//0).base(2)} ``` [Answer] ## Javascript, 63 bytes ``` f= x=>0|/^0x[A-Fa-f0-9]+$/.test(x)&&Number.parseInt(x).toString(2) ``` ]
[Question] [ Your task is to calculate the expected chance of winning for 2 players in some game, each with their own **[ELO Rating](https://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details)**. Player A has ELO Ra and player B has ELO Rb The expected score for Player A (Ea) is: 1 / (1 + 10(Rb - Ra) / 400). There is a similar equation for Player B (Eb): 1 / (1 + 10(Ra - Rb) / 400). If you want a more copiable version: `1 / (1 + 10^((a-b) / 400))` Ea + Eb should be equal to 1. Therefore, the score for a player is their expected chance of winning some match, in decimal. Your program/function should take 2 inputs, Player A's ELO, and Player B's ELO, and print/return their respective chance to win in decimal format. The output *must* add up to one, and you must be accurate to at least 5 decimal places (`0.00000`). After 5 decimal places, you may have inaccurate digits, provided the two outputs still add up to one. ### Examples: ``` 1200 2100 -> 0.005591967 0.994408033 1 1 -> 0.5 0.5 60 20 -> 0.557312 0.442688 9999 9998 -> 0.501439 0.498561 9999 1 -> 0.999999 0.000001 ``` In the final test case, some answers use scientific exponentiation to represent the value. This is not valid. You can see in test case 3 here that `0.557312` is not quite accurate, because the `2` should be a `1`, but this is fine because it is after five decimal places and the outputs still add up to one. This is an example of invalid output: ``` 9999 9998 -> 0.5014391117091516, 0.49856088829084844 ``` This looks like it satisfies the requirements at first glance, but the numbers add up to `1.00000000000000004` and therefore the output is not valid. Trailing zeroes in the output is fine. You may assume a player's ELO will always be greater than 0, and nobody will have an ELO higher than 9999. The input and output format is flexible, but the input and output must still be in base 10. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the lowest byte count will win! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ÷400⁵*÷S$ ``` [Try it online!](https://tio.run/nexus/jelly#@394u4mBwaPGrVqHtwer/P//P9rQyMBAR8HI0MAgFgA "Jelly – TIO Nexus") or [View all test cases.](https://tio.run/nexus/jelly#@394u4mBwaPGrVqHtwer/D/c/qhpjfv//9HRhkYGBjoKRoYGBrE6CtGGOgqGINoMJAYWsQQCHQUgYREbCwA) The input is an array `[Ra, Rb]` and the output is an array `[Ea, Eb]`. ## Explanation ``` ÷400⁵*÷S$ Input: array [Ra, Rb] ÷400 Divide each by 400, makes [Ra/400, Rb/400] ⁵* Raise 10 to that power, makes [10^(Ra/400), 10^(Rb/400)] $ Monadic chain operating on previous result ÷ Divide each by S The sum of the whole Makes [10^(Ra/400)/(10^(Ra/400) + 10^(Rb/400)), 10^(Rb/400)/(10^(Ra/400) + 10^(Rb/400))] = [1/(1 + 10^((Rb-Ra)/400)), 1/(1 + 10^((Ra-Rb)/400))] ``` [Answer] # Python 3, ~~55~~ 47 bytes ``` lambda a,b:[1/(1+10**(x/400))for x in[b-a,a-b]] ``` -8 bytes thanks to @math\_junkie [Answer] # MATL, 11 bytes ``` 10i400/^ts/ ``` Takes input as a list and outputs a list. ``` 10 % push number literal i % push input 400 % push number literal / % divide the list (by 400) ^ % power (10^list, element wise) t % duplicate the list s % sum the second one / % divide by the sum % (implicit) convert to string and display ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` XAq~_W%\.m400df/f#:)f/p ``` Some other 23 byte solutions: ``` q~_W%\.m400df{/A\#)W#}p Aq~_W%\.m400df/f{#)W#}p ``` [Try it online!](https://tio.run/nexus/cjam#@x/hWFgXH64ao5drYmCQkqafpmylmaZf8P9/tKGRgYGCkaGBQSwA "CJam – TIO Nexus") **Explanation** ``` X Push 1 A Push 10 q~ Push an eval the input, a list containing 2 numbers _W% Duplicate the list and reverse it \ Swap top stack elements, so the order of answers matches the input .m Vectorized subtraction: computes Ra - Rb and Rb - Ra 400d Push 400.0 (must be a double, otherwise / performs integer division) f/ Divide both values by 400 f# Raise 10 to the power of both numbers :) Increment both numbers f/ Divide 1 by both numbers p Output the list nicely ``` [Answer] # C, 63 bytes ``` #define M(a,b)1/(1+pow(10,(a-b)/400.)),1/(1+pow(10,(b-a)/400.)) ``` Defines a (rather naive) parameterized macro `M`, the shortest working approach I could think of but probably still not the shortest. As such, any golfing suggestions are greatly appreciated. Anyways, this returns 2 floating point values, `E_b` and `E_a`, respectively. [Try it online!](https://tio.run/nexus/c-gcc#@6@ckpqWmZeq4KuRqJOkaaivYahdkF@uYWigo5Gom6Spb2JgoKepqYMikaSbCJP4n5lXopCbmJmnoalQzaUABAVFQKE0DSXVNAXVtJg8JR1fDUMjAwMdI0MDA01Na67a/wA "C (gcc) – TIO Nexus") [Answer] # JavaScript (ES7), ~~41~~ 35 bytes *Saved 6 bytes thanks to @Neil* ``` a=>b=>[b=1/(1+10**((b-a)/400)),1-b] ``` [Answer] # SAS Macro Language, 70 bytes ``` %macro e(a,b);data t;p=1/(1+10**((&b-&a)/400));q=1-p;proc print%mend; ``` Output is a SAS data set where variables `p` and `q` are the players' chance of winning. 11 bytes can be saved by removing the `print` procedure. [Answer] # C#, 92 bytes Not the shortest, but it's C#, never the shortest.. # Golfed ``` static double[]f(int a,double b){b=1/(1+System.Math.Pow(10,(a-b)/400d));return new[]{1-b,b}; ``` ## Ungolfed ``` static double[] f(int a, double b) { b = 1/(1 + System.Math.Pow(10, (a - b)/400d)); return new[] {1 - b, b}; } ``` [Answer] # q, 26 bytes ``` {1%1+10 xexp(y-x;x-y)%400} ``` Example ``` q){1%1+10 xexp(y-x;x-y)%400}[1200;2100] 0.0055919673088347735 0.99440803269116518 ``` ]
[Question] [ Lets create a system of numbers where the biggest digit in the nth place value (counting from right to left) of a number length m is always equal to m - n + 1. To give an example the largest 5 digit number expressible in this system is written 12345. Apart from the number of digits available to be used in a particular place being restricted, all other incrementation is standard. Namely when a digit is to surpass its digit limit we add one to the next digit. Here is how counting would be represented in this system: ``` 1; 10; 11; 12; 100; 101; 102; 103; 110; 111; 112; 113; 120; 121; 122; 123; 1000; 1001 ... ``` Your task is to write a function that takes a standard base 10 number and converts it to my numbering system. Shorter code is preferable. Bonne Chance! \*\*If you need digits after 9 (you should) you can choose to use letters, or you can you return a 2 digit number as an element of a list. Test Cases ``` 10 -> 111 20 -> 1003 30 -> 1023 50 -> 1123 100 -> 10035 23116 -> 1234567 21977356 -> 123456789A ``` Last case may be incredibly slow to run depending on how you implemented. You don't need to run it if it takes too long or uses too much memory. However note that there exist ways to have it run quickly and using little memory. [Answer] # Mathematica, 64 bytes ``` Part[Join@@Array[Tuples@Join[{{1}},Array[Range,#-1,3]-1]&,#],#]& ``` Unnamed function taking a positive integer argument and returning a list of integers. `Join[{{1}},Array[Range,#-1,3]-1]` returns the nested list `{ {1}, {0,1,2}, {0,1,2,3}, ..., {0,1,...,#} }`. Then `Tuples` returns the (sorted) set of all tuples whose first element lies in `{1}`, whose second element lies in `{0,1,2}`, and so on; these are the `#`-digit numbers in this numbering system. `Join@@Array[...,#]` returns an array of all the numbers in this numbering system with at most `#` digits, and `Part[...,#]` extracts the `#`th such number. This is hopelessly slow! It runs fine for the input up to 9. For larger input, test it by replacing the end `,#],#]&` with `,Ceiling[0.9Log[#]]],#]&`; this puts a more realistic cap on the number of digits necessary to go far enough in the numbering system to find the one we want. [Answer] ## Mathematica, 93 bytes ``` Nest[#/.{x___,y_}:>{x,y+1}//.x:{y___,z_:0,w_,v___}/;w>Tr[1^x]-Tr[1^{v}]:>{y,z+1,0,v}&,{0},#]& ``` Pure function with first argument `#`. If a nonnegative integer is given, it will output the correct list of digits (even handles `0` correctly!). ## Explanation `Nest[f,expr,n]` gives the result of applying `f` to `expr` `n` times. In this case, `expr` is the list `{0}` and `n` is the input integer `#`. The function `f` is complicated: ``` # (* Starting with the input # *) /. (* Apply the following rule *) {x___,y_} (* If you see a list of the form {x___,y} *) :> (* replace it with *) {x,y+1} (* this *) //. (* Now apply the following rule repeatedly until nothing changes *) x:{y___,z_:0,w_,v___} (* If you see a list x starting with a sequence y of 0 or more elements, followed by an optional element z (default value of 0), followed by an element w, followed by a sequence v of 0 or more elements *) /; (* such that *) w>Tr[1^x]-Tr[1^{v}] (* w is greater than the length of x minus the length of {v} *) :> (* replace it with *) {y,z+1,0,v}& (* this *) ``` [Answer] # [Perl 6](http://perl6.org/), 38 bytes ``` {map({|[X] 1,|map ^*,3..$_},1..*)[$_]} ``` Takes a positive integer, and outputs a list of integers representing the digits. ### Explanation: ``` { } # a lambda map({ },1..*) # for each number length from 0 to infinity, # offset by 1 to avoid a +1 in next step... 1,|map ^*,3..$_ # generate the digit ranges, e.g.: # length 0 -> (1) # bogus, but irrelevant # length 1 -> (1) # length 2 -> (1, 0..2) # length 3 -> (1, 0..2, 0..3) # length 4 -> (1, 0..2, 0..3, 0..4) [X] # take the cartesian product | # slip the results into the outer sequence [$_] # Index the sequence generated this way ``` [Answer] # Pyth - 14 bytes Simply returns the `nth` value that fits the "less than place value pattern". ``` e.f.A.eghkbjZT ``` [Test Suite](http://pyth.herokuapp.com/?code=e.f.A.eghkbjZT&test_suite=1&test_suite_input=10%0A20%0A30%0A50%0A100&debug=0). [Answer] ## Haskell, 65 bytes ``` i(x:r)|x>length r=0:i r|1<2=1+x:r i[]=[1] reverse.(iterate i[]!!) ``` `i` increases numbers in the number system with the digits in reversed order. `iterate` creates the infinite list of all these numbers starting with zero which is represented by `[]`. Then all that is left to do is take (`!!`) the demanded number and `reverse` it. The last line is a function, not a function definition, so it can not appear as is in a source code file. Instead, only put the other lines in the source code and use the last line at the interpreter (or bind the function to a name by prepending `f=` to the last line). Example use: ``` *Main> reverse.(iterate i[]!!) $ 100 [1,0,0,3,5] ``` (8 bytes could be saved if `[5,3,0,0,1]` were an allowed representation of the result.) [Answer] ## Haskell, 49 bytes ``` x=[1]:[n++[d]|n<-x,d<-[0..length n+1]] (x!!).pred ``` The first line is an auxiliary definition, and the second evaluates to a function. It takes an integer and returns a list of integers. [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoyswrUVBRSFMwNfhfYRttGGsVnaetHZ0SW5Nno1uhk2KjG22gp5eTmpdekqGQp20YG8uVZqtRoaioqVdQlJry/z8A) ## Explanation I define `x` as the infinite list of representations mentioned in the challenge text; the main function just decrements its argument and indexes into `x`. The first line works like this: ``` x= -- The list of lists x contains [1]: -- the list [1], followed by [n++[d]| -- integer d appended to list n, where n<-x, -- n is drawn from x, and d<-[0..length n+1]] -- the new "digit" d is drawn from this range. ``` You see that `x` is defined in terms of itself, but Haskell is lazy, so this is not an issue. ]