text
stringlengths 180
608k
|
---|
[Question]
[
The [International Standard Atmosphere](https://en.wikipedia.org/wiki/International_Standard_Atmosphere) (ISA) is a model of the Earth's atmosphere at "reference" conditions. It includes information on pressure, temperature, and density change vs. altitude.
The ISA tabulates these properties at various layers, and an estimation of the value of interest can by found by the following procedure:
1. Find the highest layer `A` which has a base altitude lower than or equal to the altitude of interest.
2. [Linearly interpolate](https://en.wikipedia.org/wiki/Linear_interpolation) between layers `A` and `A+1` to find the properties at the altitude of interest.
For example, suppose you want to find the temperature at a geometric altitude above [MSL](https://en.wikipedia.org/wiki/Sea_level) of `40000m`. Thus, `A=3`, and the temperature is (in degrees `C`):
```
T = (-2.5+44.5)*(40000-32000)/(47000-32000)-44.5 = -22.1
```
The goal of this challenge is given a geometric altitude above MSL, find the standard temperature, pressure, and density at that altitude.
For the purposes of this challenge, use the table of the 1976 ISA model (presented on Wikipedia). Here is a link a [Gist containing the data in CSV format](https://gist.github.com/helloworld922/f657186dd110ed87e3c39bcbb314c068). Note that the CSV file includes the missing density values from Wikipedia's page.
# Input
The input is a single finite real number representing the geometric altitude above MSL in meters. This number is guaranteed to be between `[-611,86000)` (i.e. it is greater than or equal to `-611`, and is strictly less than `86000`).
The input may come from any source desired (function input, stdio, etc.)
# Output
The output are the 3 real numbers representing the standard temperature, pressure, and density at the input altitude. The answer should be accurate to within `0.1%`. The answer may be in order desired, as long as it is obvious which value represents which quantity (ex.: the first number is always temperature, the second number is always density, and the third number is always pressure). Note that the magnitude of the quantity does not count as make it obvious what the value represents.
You are welcome to choose any units to output your answers in as long as they properly describe the quantity of interest. Ex.: you may output temperature in degrees Fahrenheit, Celsius, Kelvin, etc., but you can't output the temperature in meters. Your code does **not** need to output the units abbreviation if it is always the same for a given quantity, but you should specify in your answer what units your answer uses.
The output may be to any sink desired (stdio, return value, output parameter, etc.).
# Examples
All examples use meters for input, and output in the order temperature (C), pressure (Pa), density (kg/m^3).
```
-611
19, 108900, 1.2985
0
15.0335, 104368, 1.24943
12000
-56.5, 20771, 0.333986
47350
-2.5, 110.91, 0.0014276
71803
-58.502, 3.95614764, 6.42055e-5
```
# Scoring
This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You may use any built-ins desired. If you are using any external resources to store the tabulated data, you must include the size of the resource (in bytes) as read into your program as part of your score.
Ex.: Say you read in a compressed version of the CSV table I linked which is `100` bytes long (uncompressed is `333` bytes), and your code is `126` bytes long. Then your net score is `100+126=226`.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 152 bytes
```
'!Q%:5-aeo\!=XBf=H]3|X"Pj7#UGj{r_DH&!+.eFc;u4 kG9Q[rQA(^D1dW- @[E8{Ul0!AXC|MDi8}:&D(j&1_zMU.`[^HQvWoi5}*1UApz %Ld3A)N<$A*7!wBgm'F4Y2'- .;e'hZaU1&Z)i&1Yn
```
Output is in the same order as described in the challenge
[Try it online!](http://matl.tryitonline.net/#code=JyFRJTo1LWFlb1whPVhCZj1IXTN8WCJQajcjVUdqe3JfREgmISsuZUZjO3U0IGtHOVFbclFBKF5EMWRXLSBAW0U4e1VsMCFBWEN8TURpOH06JkQoaiYxX3pNVS5gW15IUXZXb2k1fSoxVUFweiAlTGQzQSlOPCRBKjchd0JnbSdGNFkyJy0gLjtlJ2haYVUxJlopaSYxWW4&input=MTIwMDA) Or [verify all test cases](http://matl.tryitonline.net/#code=JyFRJTo1LWFlb1whPVhCZj1IXTN8WCJQajcjVUdqe3JfREgmISsuZUZjO3U0IGtHOVFbclFBKF5EMWRXLSBAW0U4e1VsMCFBWEN8TURpOH06JkQoaiYxX3pNVS5gW15IUXZXb2k1fSoxVUFweiAlTGQzQSlOPCRBKjchd0JnbSdGNFkyJy0gLjtlJ2haYVUxJlopaSYxWW4&input=Wy02MTE7IDA7IDEyMDAwOyA0NzM1MDsgNzE4MDNd).
### Explanation
Most of the code, `'!Q%:5...!wBgm'`, is a compressed string containing the table. `F4Y2'- .;e'hZa` decompresses this into the string `-611 19 ... 6.961e-6`. Note that some decimals have been removed, as they are not needed to fulfill the 0.1% accuracy criterion.
The decompressed string is interpreted as an array with `U`. This produces the 8×4 table with the required data. The first column shown in the challenge is not needed. Then `1&Z)` separates the first column from the rest.
`i` takes a number as input, and `&1Yn` applies linear interpolation using the three types of data: first column of the table, remaining columns, input. The result of the interpolation is implicitly displayed.
The input can also be a column vector, and then each row of the output refers to one of the input values. This is used for verifying all test cases at once.
[Answer]
# [Python 2](https://docs.python.org/2/), 372 bytes
```
h=-611,11019,20063,32162,47350,51413,71802,86000
i=input()
p=sum(x<=i for x in h)-1
a,b=h[p:p+2]
d=i-a+.0
d/=b-a
for e,f in[x[p:p+2]for x in[(19,-56.5,-56.5,-44.5,-2.5,-2.5,-58.5,-86.28),(108900,22632,5474.9,868.02,110.91,66.939,3.9564,0.3734),(1.29853103694,0.3639105,0.0880334745,0.0132247926,0.00142755556,0.000862248191,6.42095529e-05,6.96089485e-06)]]:print e+f*d-e*d
```
[Try it online!](https://tio.run/##PVHLbsMgELzzFSgnO8F0H4AhKn/RW5RDEhPZUutYaaK6X5@C25TDaBdmd4ed6fvWX0Z6nC5diqvV6tHHxiEqRMCgCMCxYkJHyrRsQVk0yKpFD6S8AwAxxGGc7reqFlP8vH9U82sc5PlylbMcRtnXDYqDOsZ@N22nDe1FF4fmsNEgupd4bA6iUJM6Z/Ju/uM8q3dV1tBYp@0TjSlI/2B9Qe80@VpVCD4AKCLHpKxpjQ5ZpNdZa/6PDqic04GDYh2sMwo0t2xKoabgLSOwC8u144BgcwTeA3NutSTIRKYN5EoCaKi1@fxm4F1@9FimaEMQrKWQmtwlz3RZmfE2p67e77fTdRhvMm3O665J6@6RFy@@@uE9ybfrPW2FlGlOJ1lMyfHCfhRbBAiksvTFDFFs4B8 "Python 2 – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Recognise Stack Exchange Sites by Their Icon](/questions/42242/recognise-stack-exchange-sites-by-their-icon)
(5 answers)
Closed 8 years ago.
Currently, the Stack Exchange network has nearly 150 sites. These sites are as follows:
```
Computer Graphics
Portuguese Language
elementary OS
Open Source
Law
Русский язык
Mythology
Health
Stack Overflow на русском
CiviCRM
Woodworking
Music Fans
Vi and Vim
Coffee
Engineering
Lifehacks
Economics
History of Science and Mathematics
Emacs
スタック・オーバーフロー
Worldbuilding
Startups
Community Building
Hinduism
Buddhism
Craft CMS
Puzzling
Data Science
Joomla
Earth Science
Mathematics Educators
Expatriates
Arduino
Software Recommendations
Beer
Ebooks
Aviation
Stack Overflow em Português
Italian Language
Amateur Radio
Pets
Tor
Astronomy
Space Exploration
Blender
Freelancing
Open Data
Network Engineering
Reverse Engineering
Tridion
Sustainable Living
English Language Learners
Magento
Anime & Manga
Politics
ExpressionEngine® Answers
Robotics
Genealogy & Family History
Ask Patents
Salesforce
Islam
Russian Language
Raspberry Pi
Chess
Chemistry
Windows Phone
The Workplace
Computer Science
Academia
Sports
Martial Arts
The Great Outdoors
Cognitive Sciences
Mathematica
Poker
Biology
Chinese Language
Movies & TV
Computational Science
Spanish Language
LEGO® Answers
History
Biblical Hermeneutics
Linguistics
Bitcoin
Christianity
French Language
Signal Processing
Cryptography
Personal Productivity
Travel
Gardening & Landscaping
Philosophy
Japanese Language
German Language
Mi Yodeya
Software Quality Assurance & Testing
Music: Practice & Theory
SharePoint
Parenting
Motor Vehicle Maintenance & Repair
Drupal Answers
Physical Fitness
Skeptics
Project Management
Quantitative Finance
Programming Puzzles & Code Golf
Code Review
Science Fiction & Fantasy
Graphic Design
Database Administrators
Video Production
Writers
Information Security
Sound Design
Homebrewing
Physics
Board & Card Games
Electrical Engineering
Android Enthusiasts
Programmers
Bicycles
Role-playing Games
Ask Different
Theoretical Computer Science
WordPress Development
Unix & Linux
User Experience
English Language & Usage
Personal Finance & Money
Ask Ubuntu
TeX - LaTeX
Geographic Information Systems
Home Improvement
Mathematics
Cross Validated
Photography
Game Development
Seasoned Advice
Webmasters
Arqade
Web Applications
Stack Apps
MathOverflow
Super User
Meta Stack Exchange
Server Fault
Stack Overflow
```
## Your Task:
* Write a program that prints out all of the sites in Stack Exchange, including those with non-ASCII characters (It doesn't need to be in any specific order).
* The program must accept no input, and must output each site on its own line (optional leading/trailing newlines).
* No standard loopholes.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program, measured in bytes, wins.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~1227~~ 1197 bytes
```
0000000: 65 55 37 7a 2b 37 10 ee 71 0a 54 ee de 05 dc 29 4b fe eU7z+7..q.T....)K.
0000012: 44 8b 56 b4 cb e1 62 48 8e 85 05 d6 00 96 d4 be e6 05 D.V...bH..........
0000024: 75 ce b1 77 eb ec ca 39 fb 02 d4 19 78 11 ff 00 c3 47 u..w...9....x....G
0000036: fa 29 10 3f 06 33 98 f4 63 38 7f fe f3 fc f9 9f f3 fb .).?.3..c8........
0000048: fb f9 f3 ef e6 f7 bf ce 9f 7f 39 bf ff 6d 7e ff 61 f9 ..........9..m~.a.
000005a: fc 6c 7e ff 0d 80 da a9 c8 70 2d a4 76 6a 4a dc 06 7d .l~......p-.vjJ..}
000006c: 4e 46 bc da 71 26 78 31 fa c0 a5 71 1b 85 62 8a 90 49 NF..q&x1...q..b..I
000007e: cd fa 25 dd 23 37 82 7e 30 ad 38 8f f5 2d dc a0 76 e2 ..%.#7.~0.8..-..v.
0000090: ad de 97 e1 90 03 bb 54 76 7d 4a 80 b1 e0 ab 41 eb 52 .......Tv}J....A.R
00000a2: 0b 98 82 77 be ee d4 ce 44 28 89 77 6a 97 39 a8 5d 19 ...w....D(.wj.9.].
00000b4: 58 a9 c8 ea 63 0e 35 3b 6e 93 54 11 d2 aa ab 2c 67 e0 X...c.5;n.T....,g.
00000c6: ad 1f 75 58 53 e5 05 36 96 9d c9 66 9e 82 41 40 7b 79 ..uXS..6...f..A@{y
00000d8: 39 a2 3a ab b6 c6 8c 25 d6 6a 6f 8c ac e0 ae cb 28 46 9.:....%.jo.....(F
00000ea: 7c 8a e3 c8 fa 14 c1 b7 34 62 08 02 ce 85 9c 24 e8 c8 |.......4b.....$..
00000fc: 44 f6 ce 7b 6a cf 1b d6 e7 3c 11 9e 02 23 1b c6 32 82 D..{j....<...#..2.
000010e: 8a 4c 58 5f 54 c2 ae e2 08 51 5d b7 d9 4e ef b6 62 8d .LX_T....Q]..N..b.
0000120: b8 51 16 35 6d 2a 29 91 5d 69 2e a5 1c f4 51 a0 66 9c .Q.5m*).]i....Q.f.
0000132: 73 5a 4b d6 2a 81 86 49 ef f5 2e 80 7c 8c fa 9a ac 18 sZK.*..I....|.....
0000144: 4a 6c b0 ef 9a e4 47 d9 b2 53 fb 94 68 40 88 7f c7 d4 Jl....G..S..h@....
0000156: e2 72 62 94 7c 88 45 be be 6b 3f b4 0d bc ef b8 38 65 .rb.|.E..k?.....8e
0000168: 9c cd 3e 7f b8 7f 78 f6 f0 6c f6 cb ec a7 d9 cf fa e1 ..>...x..l........
000017a: 83 d9 8f 0f ef cc 7e 51 07 14 d2 78 6d 74 30 f0 fe 36 ......~Q...xmt0..6
000018c: aa 83 2a 37 46 2a 20 cb 55 0a a5 1d 07 6e 84 aa 71 c8 ..*7F* .U....n..q.
000019e: 19 b2 65 b4 26 51 e8 f4 d9 85 3a a8 09 aa 9b e7 c0 56 ..e.&Q....:......V
00001b0: e2 78 5d 60 7d ca 14 1c e2 78 e1 04 1d bb 8a 58 d5 c1 .x]`}....x.....X..
00001c2: 5d 43 f0 84 6c 63 c6 01 7d 42 fd 16 97 fe f3 ed 3a 8f ]C..lc..}B......:.
00001d4: c3 c0 6c c9 55 f0 92 b1 ab d6 57 b1 ca 5d d7 fb 3c 61 ..l.U.....W..]..<a
00001e6: eb 9b 1c 1e 04 c1 b0 83 2a bc 40 cb c4 8a 9a 6c 78 c4 ........*[[email protected]](/cdn-cgi/l/email-protection).
00001f8: 8e 29 b3 08 f2 43 aa c5 76 fa 18 65 f4 a1 c3 d1 a2 ca .)...C..v..e......
000020a: 52 e9 13 37 f4 a1 2e 6d d4 17 5d 4c 5c 47 1c 43 e2 36 R..7...m..]L\G.C.6
000021c: 5c 2e 74 e1 35 ca c8 a9 63 5c 9b c6 ea 58 9c 69 33 f1 \.t.5...c\...X.i3.
000022e: 96 b7 ae 56 ed 87 ab 52 6b 84 83 c7 93 c0 4c 2a 04 3f ...V...Rk.....L*.?
0000240: f6 35 0f 02 4f 11 5f c1 fa a4 6e 82 9f 70 49 64 2b 14 .5..O._...n..pId+.
0000252: ae da 90 79 7a 12 2d d5 ea 24 91 95 cd 90 5e a1 86 36 ...yz.-..$....^..6
0000264: d9 0d 89 f7 b5 25 75 4a 53 75 7a 70 74 b6 51 cd 53 19 .....%uJSuzpt.Q.S.
0000276: f2 98 aa db 8c a0 2c b1 84 d2 83 91 4b 1e 6b 48 92 39 ......,.....K.kH.9
0000288: 14 12 84 eb 58 69 03 c7 4d ac 0f 4c 5b 15 2a 16 e9 d9 ....Xi..M..L[.*...
000029a: 84 c3 d0 fa a9 ea 71 e6 65 82 1f 7d 70 57 8d 11 16 ab ......q.e..}pW....
00002ac: 9e e8 37 bc e1 0e 97 79 58 e8 6b 46 19 2d a3 24 e2 12 ..7....yX.kF.-.$..
00002be: 3b 74 38 53 e3 9c 1b 92 00 95 89 70 c4 fe f2 5a f5 da ;t8S.......p...Z..
00002d0: 28 15 ba e6 e2 02 be ac fb 81 2a b8 e7 7c 3e e6 5c ee (.........*..|>.\.
00002e2: 5e 97 c6 8b 29 f1 2a a7 a9 0f b7 5b e4 3d 6b d8 e9 fc ^...).*....[.=k...
00002f4: 56 16 e8 c2 b7 01 d4 ef 53 1e 56 f9 bc cf 21 96 97 7b V.......S.V...!..{
0000306: 28 ab 38 7a de 71 b7 3e 80 47 8f 4c 31 07 24 65 29 aa (.8z.q.>.G.L1.$e).
0000318: d3 1f 8b f5 d1 e3 75 02 fa d5 4b 05 ee 10 62 b9 2a a1 ......u...K...b.*.
000032a: 27 71 29 c0 ea 6f 39 e0 d3 4a 5a 6c 43 6a 47 ed 56 d7 'q)..o9..JZlCjG.V.
000033c: e0 04 b7 d4 35 9c ae 71 a6 72 bf 7d fc d8 96 6a 94 01 ....5..q.r.}...j..
000034e: 75 e4 ed 30 9f bf c9 55 ca d3 18 a6 85 32 45 2d a7 f3 u..0...U.....2E-..
0000360: 5a 4b c8 2b 11 c2 e5 55 4a ea 9c 62 33 e0 00 4a f6 45 ZK.+...UJ..b3..J.E
0000372: 61 c6 c1 09 6f 15 e9 dc 0f 7c 0e 0d c0 f2 a3 c6 52 07 a...o....|......R.
0000384: 69 99 ab 10 b5 31 6e 51 ee 82 10 d0 d0 e7 32 2e e9 0d i....1nQ......2...
0000396: 47 55 66 6b 79 60 2e 51 ec d4 05 13 aa c7 06 53 6b 22 GUfky`.Q.......Sk"
00003a8: 59 93 03 dc e2 b8 b5 49 5d 8c 29 70 df 8b 03 94 d1 b2 Y......I].)p......
00003ba: c6 15 2a 96 63 b9 b8 e5 a6 c4 72 e1 87 69 0a 45 8d 9c ..*.c.....r..i.E..
00003cc: 6c 1e b9 3b 31 b6 61 d9 a3 4b 8e a5 7d 6b a5 73 ae 3c l..;1.a..K..}k.s.<
00003de: ca e7 4c 79 37 d9 ba 75 66 f5 52 2f 1a 82 15 06 8d f5 ..Ly7..uf.R/......
00003f0: a1 9c 67 89 db 9c 4c 10 f8 4c fc 05 71 77 9a 66 05 d7 ..g...L..L..qw.f..
0000402: bc de de ea d9 ef b3 ef f5 c3 d3 f5 9c fd 63 f6 db ff ..............c...
0000414: 55 b8 d6 cb 56 ff fb 65 b9 0e b8 01 68 1b 0e 98 83 1c U...V..e....h.....
0000426: 00 63 22 34 69 60 41 05 99 e4 84 2e f9 75 fd 08 61 61 .c"4i`A......u..aa
0000438: 55 20 b8 3e 0a 4c 49 9f b5 c9 f8 fc d4 0a e7 39 15 9a U .>.LI........9..
000044a: bd f0 8d 92 f5 6f f0 00 d0 c0 bc f3 41 5d 06 c2 80 c4 .....o......A]....
000045c: 22 26 67 7d e5 e4 2e 4f 47 71 ed 9d ca 11 e4 9a 70 58 "&g}...OGq......pX
000046e: 58 5f 4b 19 53 d7 52 03 1a f6 6b e2 c3 f0 86 07 b9 28 X_K.S.R...k......(
0000480: 56 aa 65 79 21 a8 29 c2 39 a0 38 e3 a7 51 e3 29 38 56 V.ey!.).9.8..Q.)8V
0000492: 37 de 9b fc 08 91 0b 70 30 fd 3c db b7 e6 34 a4 d6 0c 7......p0.<...4...
00004a4: 56 5f 9f 37 41 ca 2d ff 01 V_.7A.-..
```
Prints a sorted list of SE sites.
Compression has been done with [zopfli](https://github.com/google/zopfli), which uses the DEFLATE format but obtains a much better ratio than (g)zip.
[Answer]
# Python3, ~~1754~~ ~~1728~~ 1662 bytes
~~Python3 includes the `lzma` module, which allowed me to obtain a really decent compression ratio.~~ (I have switched to `gzip`.) I was originally going to use base64 to encode the output but realized I could squeeze some more bytes out using base85 (ascii85).
I avoided the issue with escaping `'` by using a triple-quoted string and avoided the issue with escaping `\` characters by using the `r""` prefix.
```
import base64,gzip
print(gzip.decompress(base64.a85decode(r'''+,^C)B/BZj!rlh3]9_20&FK!&W8.1RdSX2MG($0f,4;Ut&gBgi+qS,^:g1Gf=(R8b8Y=`"jO#8sSE-4$#Gc:bO5pd"a]c<M-kMcVF75Ychj%1^aigAZ<M?`A-I0YX;,\St;Kbp<"UQq`P)[UCng5)1'j6s9g1M[#C+ZkYm5DT.]@Ye]gHW,bjmN$5n%8%sn&2_mKemVoLau@M(*\_f>KWEMq71K\\c$=@S(rF=3rJaG^$+dImSCm_V/uIdq5(M-0s6/SjJB.JghWm*0(3p3qJJJE&d,bmQH8[;Oe,L&'L<-_B3iX@>j2e?E4`YS1JKd&2SrS8Jk?c'bFhgZmN:?S+91#42Z(O%pR=DAO)O`]p\W2GmISBsk%D=,Q8eW@egBR-W!?R-!EdLM[Q6=PGPlW\D-lO)MI)k:"i']CRRc$QVd`Q=H=_?MKo5.$9>#5H1eJ/fZT'P.iKSu-c4l-:ieL,pY>qA@&s#0+M:Bf1>'Z90aoI35N`-FXotZS)ba\bga\'%C+%nnr4Que%Rinl/10W?AqBnNn[?jgWCF:GCK=H&1,U%Kr\IiPP5V-:\kIUj[!sD/Bl%tA))40(rLMIZt;e1%4\U%0U)S#3_mFLU9Kj0>2ZrJma=2H0VKPa26iWN/>89p+!i+rG#3g!NMP'dJ9m6\Y@7X&l;<1ZEAfIkXf^W=?J24pDMR;;O*ahk?f/rj;=;O^,sN.dplEWS9Q84]#>0R):Xf>4C`9PXbpB5X_92'WV6::04$aNMmBYn61H4Q=pX:'tW*g_M0oY@V:\-!RBbbbGi79]\74^bqA9.XfghaFsT_fqBc.j\6b:`uaKW"WXLCFGpdVbf"TSTh\C-%GEI#`-KCah+CU2osaZ#.'9SlGJjU*m5b2U1`5)>EI$WGVe62?NP$GG=&Rie4G&6"O7p8bA*1-%#gY#Y)i8uQZa8kp??#UpG8Z;D"8%"?7CV3ce\IA4\AJNX$0pXq[pH2XLnXB"=e%c@#agB@<?,FFB]F^)o.Lg#H,@?.E6jdhC\a7=WDO`um>Dm2Ju2=1W4h3<!knpd*/E*XJ>3+Aqbe!sOVTo;6+p,hn7K;g%U@,&_?>V2a07T5G)/,S8nfq2HsO#4#C7ad'3\QmFgPtcF@fJ*-Q)WIZH0HZDP#Sa5`pgJKH2[f)k$GO]Wu'Sg54>Eh+*HFkfd;=DeMa;CN1>bQTAUqZsA7[+>i(sDo`:n:oKpu1Beh`*.cf*h8HnV3Ot>5kie@>8$:n+U4:>:>V`.Wp8f2c(X2)1a=C??bgX.%N2q\E*$f+&r%h:ubWRX.g:*<::QWNWhWZ"qZ%+)L`,M`HoCm@XJ91.,6dO/,%J.u$jAs%B\7ShidHX6,c1";KU2fc2Ntn=Bj]p@,IV8<UHVW>l6/2Y1a7',4p;eT`m$YKom'MtC%nc?t_gpr?ceY\2Ynjh@V0n;upk;YY/q=:)fPEmM1:6u$la$)!e[aZ:md#3)bkLT]Xp`B<YWMLlPOPB<PSAXF%WPR=Ml'V`6CGj3ItR:0.l+(RDYWYjl0]E?FjoMuiF&=2#K`3d1%?RBmMe9!"kZ)LPK-FcX>]UD]BXk\/OT09#QOi''')).decode())
```
] |
[Question]
[
When manufacturing chips, circular silicon wafers are cut into dies of needed size:

The goal of this challenge is maximizing the number of whole dies that can be cut from a wafer of a given diameter.
The machine puts the wafer into an angular compartment:
```
_____________________
| xxxxxx
| xxxxxxxxxxxx
| xxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
| xxxxxxxxxxxxxx
| xxxxxxxxxxxx
| xxxxxx (this ascii art is meant to be a perfect circle)
```
It measures a distance `dx` from the left edge, and makes a vertical cut. Then it makes the needed number of additional vertical cuts, with spacing of the needed `width`. It makes the horizontal cuts in the same way: first one at a distance `dy`, and then with spacing of `height`.
The material remains perfectly still during the cutting: it's not allowed to move some slices of material before making the perpendicular cuts.
The machine has a stepper motor that works at absolute accuracy but can only go integer-sized distances.
Make a program or a subroutine that gets (or reads) the following parameters:
* Wafer `diameter`
* Die `width`
* Die `height`
and outputs (or prints)
* `dx` - horizontal starting position
* `dy` - vertical starting position
such that the number of rectangular dies is maximal.
Some fine points:
* If a corner of a die lies exactly on the circumference of the circle, the die is considered usable (rectangular)
* No edge cases: you can assume that the wafer's diameter is even; at least one die can be cut out; also make other reasonable assumptions
* All sizes are integer numbers of millimeters; maximum wafer diameter is [450](https://en.wikipedia.org/wiki/Wafer_(electronics)#Proposed_450mm_transition)
Shortest code wins!
P.S. The code must finish running in a reasonable amount of time, e.g. over a weekend (2 days) - for wafer diameter equal to 300.
P.P.S. If there are several different output values that are optimal, the code must output one of them - no need to output all of them!
Test cases:
```
Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 9, dy = 3 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies) - a realistic example
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies) - a Pythagorean triple
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies) - full-frame sensors
```
Here is a visualization of the last test case:

[Answer]
## Python 2.7, 317
Here is my solution. Could be golfed a bit more, I think - but I like the solving better than the golfing. Suggestions are welcome.
I solve it using brute force, iterating over all dx and dy and then counting by column. It all runs pretty fast (<0,05 sec. on my Mac).
Code:
```
import math as m
def D(d,w,h):
r=d/2
s=[0,0,0]
for dx in range(0,w):
for dy in range(0,h):
t=0
for c in range(1,int(d/w)+1):
l=r-dx-(c-1)*w
if l<w/2:
l-=w
if abs(l)<=r:
f=r*m.sin(m.acos(1.0*l/r));t+=int((2.0*f-(dy+m.ceil((r-dy-f)/h)*h+f-r))/h)
if t>s[0]:
s=[t,dx,dy]
return s
```
A main to test and profile the given cases:
```
def runTestcases():
for d,w,h in [[8,2,2],[20,5,4],[100,12,12],[300,11,11],[340,15,8],[300,36,24]]:
S=D(d,w,h)
print "Wafer diameter {}, die size {} x {} => dx = {}, dy = {} ({} dies)".format(d,w,h,S[1],S[2],S[0])
def main():
import cProfile
cProfile.run("runTestcases()")
if __name__ == "__main__":
main()
```
And its output:
```
Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 0, dy = 8 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies)
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies)
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies)
55354 function calls in 0.049 seconds
```
[Answer]
# Java, 242
This is a method that takes the three input parameters and returns a string containing optimal values for dx and dy.
```
String k(int d,int w,int h){int m=0,f=0,g=0,r=d/2,s=r*r+1,a,b,p=-1;while(++p<w)for(int q=-1;++q<h;)for(int x=p-r,c=0;(a=x+w)<r;x=a)for(int y=q-r;(b=y+h)<r;y=b)if(x*x+y*y<s&&a*a+b*b<s&&x*x+b*b<s&&a*a+y*y<s&&++c>m){m=c;f=p;g=q;}return f+" "+g;}
```
Ungolfed:
```
String k(int diameter, int width, int height) {
int
maxDieCount = 0,
bestDx = 0,
bestDy = 0,
radius = diameter / 2,
radiusSquared = radius * radius;
for (int dx = 0; dx < width; ++dx) {
for (int dy = 0; dy < height; ++dy) {
int dieCount = 0;
for (int x1 = dx - radius; x1 + width < radius; x1 += width) {
int x2 = x1 + width;
for (int y1 = dy - radius; y1 + height < radius; y1 += height) {
int y2 = y1 + height;
if ( x1 * x1 + y1 * y1 <= radiusSquared &&
x2 * x2 + y2 * y2 <= radiusSquared &&
x1 * x1 + y2 * y2 <= radiusSquared &&
x2 * x2 + y1 * y1 <= radiusSquared )
++dieCount;
}
}
if (dieCount > maxDieCount) {
maxDieCount = dieCount;
bestDx = dx;
bestDy = dy;
}
}
}
return bestDx + " " + bestDy;
}
```
Pretty straightforward bruteforce approach - try every dx in [0, width) and every dy in [0, height), then loop through every rectangle in the resulting grid and check if all four corners are inside the circle (using basic pythagorean relations), count the number of such rectangles, and return the first dx and dy that produced the highest count for the given configuration.
Test with: (assuming both methods are placed in a class named CG52148)
```
public static void main(String[] args) {
CG52148 o = new CG52148();
System.out.println("8\t2\t2\t=> " + o.k(8, 2, 2));
System.out.println("20\t5\t4\t=> " + o.k(20, 5, 4));
System.out.println("100\t12\t12\t=> " + o.k(100, 12, 12));
System.out.println("300\t11\t11\t=> " + o.k(300, 11, 11));
System.out.println("340\t15\t8\t=> " + o.k(340, 15, 8));
System.out.println("300\t36\t24\t=> " + o.k(300, 36, 24));
}
```
The third test case produces `0 8` rather than `9 3`, but they are both valid, equally optimal, and are both found by my algorithm.
] |
[Question]
[
EDIT: I posted this question searching for a beautiful, original solution to this problem. Therefore, I accepted a user's edited category "popularity-contest". **Making this a search for optimal solutions (i.e. runtime, code size etc.) is not my intention**.
## Copy-paste master
John wants to write this phrase multiple times into a text document:
```
I am a copy-paste master.
```
He creates a new, empty text document, and types down the phrase. He wants to copy and paste this phrase on a new line until he reaches at least a certain number of lines. He figures out it would be quicker if, from time to time, he selected all the text written so far, copies again and then resumes pasting.
Assume the following:
* At time `t = 0` the phrase has been typed for the first time and John begins the copy-paste process.
* It takes `T1` to Select All (Ctrl+A), Copy (Ctrl+C) and Clear Selection (End) => **Operation 1**
* It takes `T2` to press Enter and then Paste (Ctrl+V) => **Operation 2**
* After he has copied the phrase the first time, let `N1` be the number of Operations 2 until he does Operation 1 again; then follows `N2` times Operation 2, etc., the last set of Operation 2 being done `Nk`.
* Let `L` be the target (**minimum**) number of lines.
* A *solution* of the problem consists of the collection: (`k`, `N1`, `N2`, ..., `Nk`)
A quick example: for `L` = 10, possible solutions are:
* (1, 9)
* (2, 4, 1)
* (3, 1, 2, 1)
## Problem
Given (`L`, `T1`, `T2`), find the solution (`k`, `N1`, `N2`, ..., `Nk`) that **minimizes** the total time to reach at least `L` lines.
P.S.
Obviously the total time is:
`T = k * T1 + T2 * SUM(Nj; j=1..k)`
And the total number of lines at the end of `T` is:
`L' = PRODUCT(1 + Nj; j=1..k)` with the condition `L' >= L`
EDIT:
At `Optimizer`'s suggestion, I will break down the (3, 1, 2, 1) solution for L = 10:
* step 1: copy 1 line, then 1 paste => 2 lines
* step 2: copy 2 lines, then 2 pastes => 6 lines
* step 3: copy 6 lines, then 1 paste => 12 lines
[Answer]
### Python, optimal solution
Note that this problem boils down to this optimization problem (as noted in the question):
```
Minimize T1*k + T2*sum(N_i)
with prod(1+N_i) >= L
```
(which interestingly means you can swap the values while still getting the same number of total lines)
When `k` is fixed, the first term `T1*k` is constant, and the `T2` in second term is immaterial, and the problem becomes:
```
Minimize sum(N_i)
with prod(1+N_i) >= L
```
which is equivalent to (by substituting `N_i` with `N_i-1`:
```
Minimize sum(N_i)
with prod(N_i) >= L
```
for which it is well known that the minimum will be achieved when `N_i` are equal to `k`-th root of `L`. Since the `N_i`s need to be integers, we take the closest value which still give us product greater than `L`.
So the following code does just that, checking each possible `k` (at the total complexity of `log_2(L)`), and taking the solution with minimum total time. Note that this will also give the solution with the lowest `k` if there are multiple solutions.
Hope the comments in the code will explain further confusion that may arise.
Some sample runs:
```
Enter L, T1, T2: 10 1 2
(3, 1, 1, 2) with score 11
Enter L, T1, T2: 10 10 10
(2, 2, 3) with score 70
Enter L, T1, T2: 10 10 2
(1, 9) with score 28
Enter L, T1, T2: 10 10 20
(3, 1, 1, 2) with score 110
Enter L, T1, T2: 10 5 0
(1, 9) with score 5
Enter L, T1, T2: 10 0 5
(3, 1, 1, 2) with score 20
```
Note that the last example has another solution `(4, 1, 1, 1, 1) with score 20`.
Code:
```
import math
def compute_score(k, L, T1, T2):
""" Compute the best possible score given k
Best score is achieved when the values are as close as possible to the
k-th root of L, since we are only minimizing the sum of the values.
"""
# k-th root of L
k_root = math.ceil(pow(L, 1.0/k))
# Find out how many of those k values can be reduced by 1,
# while still maintaining product >= L
k_pow = float(pow(k_root, k))
reduction = int(math.floor(math.log(k_pow/L, k_root/(k_root-1.0))))
# Generate the values
k_root = int(k_root)
vals = [k_root-2 if i<reduction else k_root-1 for i in xrange(k)]
# Compute the score
score = k*T1 + T2*sum(vals)
return (score, vals)
def find_min_score(L, T1, T2):
""" Find minimum possible total time, given L, T1, and T2
Works by finding minimum possible total time on each possible k.
Note that k <= ceil(log_2(L)) since N_i >= 1 and so (1+N_i) >= 2, so at
k = ceil(log_2(L)), N_i = 1 for all i, which is the minimum sum
"""
# k_max = ceil(log_2(L))
k_max = int(math.ceil(math.log(L, 2)))
# Trivial score when k=1
min_score = T1 + T2*(L-1)
min_vals = [L-1]
min_k = 1
# Find minimum
for k in xrange(2, k_max+1):
(score, vals) = compute_score(k, L, T1, T2)
if score < min_score:
min_score = score
min_vals = vals
min_k = k
return (min_score, min_k, min_vals)
def main():
while True:
L, T1, T2 = map(int, raw_input('Enter L, T1, T2: ').split())
(score, k, vals) = find_min_score(L, T1, T2)
print '(%d, %s) with score %d' % (k, ', '.join(map(str, vals)), score)
if __name__ == '__main__':
main()
```
[Answer]
## CJam, WTH
I thought that I will give it a shot in CJam. I had to write my own minimizing and combination routines as CJam is just a stack operations language.
Here goes the code:
```
ri:Lri:T;ri:Y;2mLm],:){L,a*{m*{(\+}%}*}%({aa}%+:~{:):*L<!},W%_0=_{_,T*\:+Y*+}:R~@{_R@>@@?_R}/;_,S@S*
```
Its a bit brute force so for high values of input `L` it takes a while before finishing.
Input goes like:
```
10 2 2
```
Where `10` is the target lines (`L`), first `2` is `T1` and second `2` is `T2`. For the above input, output is:
```
2 1 4
```
Say if you had given input as
```
10 2 4
```
i.e. for the same target lines, `T2` is more than `T1`, the output will be
```
3 1 1 2
```
[Try it online here](http://cjam.aditsu.net/) , but I will recommend the Java way of running the code as mentioned [here](https://sourceforge.net/p/cjam/wiki/Home/)
] |
[Question]
[
This question is from a programming challenge (not DARPA) which has ended. A sheet of paper consists of message, which has been shredded into vertical strips. Given the vertical strips and a dictionary of valid words, the goal is to put together the original message.
The vertical strips contain only one character from a line. The input to the program is the number of vertical strips (N), number of lines in the original message (K) and a string containing the characters in each vertical strip. Then the number of words in the dictionary and the list of valid words.
**EXAMPLE INPUT**
```
10
3
"MrM"
"ak "
"Gaa"
"oM "
" d "
"t 3"
" aP"
"nt "
"ont"
"ie "
15
1
2
3
4
5
AND
AM
AT
GO
IN
Main
Market
ON
PM
TO
```
**OUTPUT**
```
Go to Main
and Market
at 3 PM
```
**Description of the input above**
`10` - number of vertical strips
`3` - number of lines in the original message corresponds to number of characters in each string of the veritcal strips
*{actual strings}* - pay careful attention to spaces in strings
`15` - number of words in the dictionary
*{valid words}*
I was able to create a map of characters -> count of each character, for each line from the vertical strips. Then parsing the dictionary and looking at the character map, you can recreate words in each line. Looks like finding the order of words is the difficult problem. What is the best approach to finding the correct message?
[Answer]
## Python 3 - Trie and DFS
[Trie](http://en.wikipedia.org/wiki/Trie) is a tree shape data structure. If we build a trie from a collection of words, then each path from the root to a leaf node will represent a word from the collection.
To solve this problem, first we build a trie using the valid words. Suppose the original text has `n` rows and `m` columns, then we will have `m` strips to put together. We try to reconstruct the original text from left to right, column by column, using a recursive depth-first search. To perform branch elimination, we also maintain a list of heads on the trie, name it `heads`. Each head points to a node on the trie and point to the root at first. We will need `n` heads, each correspond to a row. Each time after a column(`strip`) is appended, `heads[i]` will be moved according to the character `strip[i]`. If we found any head that cannot be moved, then we know the column just appended is incorrect. After putting `m` columns, we get the original text.
I implemented this algorithm using Python. It is fast enough to solve a 40x80 case with 10000 valid word in instant.
I use [this python 3 script](http://pastebin.com/qvmSMEEm) to generate test cases. Run it with:
```
python3 make_script.py {dict path} {n rows} {n cols} > intput.txt
```
The following is a 40 x 80 case. The dictionary file can be found [here](http://pastebin.com/raw.php?i=KeJLY958), which has 10000 words.
```
80
40
c el efp e otl desaiweseeme jomp ebc g
synwds irnsatseityl rkutpsiysei ssraat
gvmjewrell fclpadrll nbsvwiwteqdeniditba
uet criderndm eesih dalbrcra d iacnnoi e
lbipoeivedrwddivensne aeihrpaa eicangpni
gontgtulvcbatdo glunsniiguoleu eigtbelh
xmsyyu ereio edvrttdonure tpselriniipnxs
ssdieop bgkg wu eloyr dllrhza t hic af
rttruminetnt rcu rasa ogosrywrnietvldgod
lpe aritour alolt yeomlpimmxryftenen sn
cneregsc igodbsigeca r kbhiiisoss eagglp
crm nhdreh raokdtr rcfiotpsfgtjanotaaiaf
s pntenpnmv plemiaaxeeittgtg ncnaooaou a
srrganeu ut toaantetedccnr seiise eur ni
xpndg psafl ooemlusof nba pauosina esnb
ge du tbfe spuoeuesen o s um ldsted w
eto rs l nhuc caexr bsoptwcrrnaennrasary
e maldneg nep nmaid isie ko ctedh necaa
esoeisi u ifran rgirrts ntipuneccnvftrp
gui oeriwraisc og vsepharn latotts aenra
eenylorobneyrem nwtefrasdeoeet ot osdsr
abia e i iwrcneaaiaeeu lie oihotgdicntdi
euugmjsdfcamazndei e yoagaserxatrultoaio
tamdfesgtitc xseuegs fene thatfueo l ut
ocn sdrtn mai aerwmimoss te oceorrit el
netbu wymsrfobelltemetrisioao uri l ce
deaa ee e aadrgcoln cnto semroi ofdnanu
aeaunrmvonirieaxapicnaioxaoromeviiuaeoou
oaodtb hpretdarie n e recei etunsrsedal
ejht n jy ees tnr gsegr s e jhb ayegup
ohids bi g iesiogs rytimtorrsab pnirwlc
ieuereaklieapeatlan sdeeg e lasedaob be
rihbegaisvdtrprnatservaraco na imtcgplna
denrdnnelymisenimi gnfw bssalupcnansu et
itsrwnbeclwfmstasg craaim ei atrifvpr
ubksogxernu auletinieo krte cgmltiliioir
atnhndcutigiasuir ntsaiauem usiireg idms
yniis ssle aisicsngqseazdifiertercaauvoc
ds prcatnoiaafsiopiratdrrmksnfidakr gon
p ngaoolyeolg nep oae dnsnln srfcontsrve
boges massscgss arsobod ierseh rnivtagsp
nlstadhndnroieecntc slhoucbrcouo uohtiis
ltainnpif nfrn tinrdoi ninsanteu n aeb
oun htoioaftupedsmowtmeatanyi sltnh ftto
a emgrasancass oelrefddy alacinsut n s
kgttnltednrmea t yhug welentn tu fsneeah
yia bilgwybnisgfrmidlh t rssnaiultgagk a
iaeeorega sdbhc otadiresdagcipcuet rde
tygui artnsot le wtes etrracm pde oev e
cvrpsabemddamylpeiscdmktpnnolbsesardlwro
rnirmestiwntlrfresosedlvshydrsrrucnntr a
nans hinslmoxenfeolo cxeeneosgrphantiuyg
m dans llnrtlav ensptun acfaev s gtesfad
litl gonungirgk pioeutvinsstgintpsmbrdsu
altpjretooode rtnseeyepdrotllxric s rice
aikaunnskdoh agtnl cuegoacwhnsx esrurgg
ef drant rsaaeymreleiiessmniesdoeeroeer
eereozurmoicueeegtcolbeioteodocrsnaeaatt
h cre g snsihssatlunisi odeelcpminoeba
oisstnirhpmnaybaertcnenhdnondsunaaprlipr
vetou egriemerpicacb ygmiaw rrrocnisecm
ibs tara neeiaqlbbtsgegcs sooeoeuel ten
blrkqaiacortqmn ien ylrrrnecieircs qeind
en s e ieu cnaiscikuirocnr hlnpfjooimohs
dctlehtr ntlgpddeoipmog elllrnncnkgcseeu
o aaet henyaue mbntgeeselsws mmawnwve
lns e xoorail yn eesnee uctaud nrasenha
swydiecacaefolsenmttnsoer ohmahttpt radc
yvltaxin pgrauluktystkmot mrf aluuiepl
b sea usksoim hr idhtttd e owrn cnferevc
lstsibaocesfsmbejsdaellmepmbdedoffdbrtmq
axou nlnae ise gn esse ihbstgsfmeteestf
yeaasra oopaeaildkiynteteidilnuenec vral
msylcdecsy lkgr icdkxrmie strle fei sz
rdae gde al ngswsc soaru tlsrtg durfne
rrpodl i asg essvuo aeaaheenaloe geru
grus nbrls eqme ydioradhsoolmdiouoggnssv
tfirotrkdnnnrtmwenan abs cfcigscmpsed
a soteiicdero nsaeuisrmisntau iirammlyi
anroiim tsiiaarrhoyaimdo oera dblogysmr
```
Solved:
```
lacerated deliberateness canvas gould scold sexually piggyback obey agrimony moe
seventy except fixates warble shrubbery instrumenting beveling convolute hairs j
tarring aptness homotopy misted unkindness frustrations marketing latitudinary h
superhumanly redbud bends atomics sprawls piggy oiling djakarta estop reads plat
insomnia delaware fruition auger hooded terramycin statuesqueness adjourns boca
brazed leghorn agnes seethed roentgen sen conjuring goa wrangled extremes hidden
ambuscade tribunals winced heap boxing fixates impostor rainstorm iberia billet
overturn protestingly pairings grieved protruded insulate ascertain tinkling c j
committees bock sat muncie drab lorelei honk fretfully block dense howell swishy
endowing annuls veins machining sandy reproducers neve flooding supportingly ye
sidings afterword thrived wrecks furman maintaining cone programs groaner mba ne
fractionally fisticuff ferromagnet wilsonian modifiable fathom accreditations ye
simulated grammars corporacies squads atalanta marriage ceq designates plexiglas
meyers propels apex ballooners impudently froze angst islamabad saud creases ku
baleful godmother scenes keep wheelings bystander kidnappings basilar caving get
experienced laryngeal mendacious devise animadvert coequal tithe surtout offer n
jaeger moments manuel instance systemwide ownerships plodding cracking legers mr
spits wallow girt extramarital administer petitioning berkeley writes ransoms b
discontinuity desegregate accretions cysteine thyroglobulin chomsky evans living
accosted speechless mixture bellowing lacerated adequately cautiousness products
endless comforters berenices fourteens insane odiousness nyu gambit yeasty lodge
lambda informative stressful dynamo forwent dynamites gentler doorkeep dutch keg
likeliest galatia fortiori hydride awakened could vandenberg wisdom phoenix axer
motivation spider epistemology shake rusher carbonizing strokers cordage meters
exposure bedim saints tritium distributed ranger indiscoverable interrogate ames
panther salem eschewing special oaths penumbra consigns winchester cons conrail
moneymake lome mob cottons ballooners smocks stressful sidewinder met refreshes
brood complexion straightforwardly patients separations wichita shrilly arose we
doldrum rarer winthrop magic chemically dancers angel outlining elf lawlessness
emboss county reagan unauthorized gauss suffixed tiresomeness cohn extravagant j
description fans staunch journalism prejudicial denture quixotic patrons briar h
override scott differentiators collection distribute folder superfluities pull b
fissured intercommunicating outputting managerial precedences conjuncted phloem
fiance honk nineteen coproduct monica sparks unconsciousness furious stagnate ma
durango fag effector notation highlands parceling magnetic reservoirs voting fay
baden end converge alva machining insurers mutiny battled quantities alberta ewe
relativeness propels formants configurable propos rubs diverge tampered swigging
toward cased reels actualities estop facings animadvert trigger golding fluke wu
mort meanness venturer dyadic abstinent phoenix resolve bangladesh acrobacy rsvp
quotas auburn crafty pacifism favorite grandiose buchenwald phelps leaded gauze
```
### Code
```
def build_trie(words):
root = {}
for word in words:
node = root
for c in word:
if c in node:
node1 = node[c]
else:
node1 = node[c] = {}
node = node1
return root
def search_origins(root, strips):
n_rows = len(strips[0])
n_cols = len(strips)
ordered = [None] * n_cols
heads = [root] * n_rows
used = set()
def get_next(node, c):
if c == ' ':
return root
return node.get(c, None)
def search(col_id, heads):
if col_id == n_cols:
yield transpose(ordered)
return
for i in range(n_cols):
if i in used:
continue
heads1 = [get_next(head, c) for c, head in zip(strips[i].lower(), heads)]
if any(x is None for x in heads1):
continue
used.add(i)
ordered[col_id] = strips[i]
yield from search(col_id + 1, heads1)
used.remove(i)
yield from search(0, heads)
def transpose(cols):
return '\n'.join(map(''.join, zip(*cols)))
def parse():
m = int(input())
n = int(input())
strips = []
for i in range(m):
strip = input()
if strip[0] == '"':
strip = strip[1:1 + n]
strips.append(strip)
n_words = input()
if n_words:
words = [input() for _ in range(int(n_words))]
else:
dict_path = input()
words = list(map(str.rstrip, open(dict_path)))
return words, strips
def main():
words, strips = parse()
words = list(map(str.lower, words))
# print(words, strips)
root = build_trie(words)
for i, result in enumerate(search_origins(root, strips)):
print('#{}{}'.format(i, '-' * 80))
print(result)
# Uncomment next line if you want only one result
# break
if __name__ == '__main__':
main()
```
[Answer]
**Groovy 311**
```
i=(args[0]as File).readLines()
(a,b)=i[0..1]*.toShort()
j=2
s=[]
a.times{s<<i[j++]-'"'-'"'}
d=[]
i[j++].toLong().times{d<<i[j++].toLowerCase()}
f={(0..<b).collect{c->it.collect{it[c]}.join()}.join("\n")}
o=0;l=0
z=s.permutations().each{x=f(it);c=d.count{x.toLowerCase().contains(it)};if(c>l){l=c;o=x}}
print o
```
let's start the bidding and just go brute force; return the first result with the most matches against the dictionary by checking all permutations
Here is a shorter example `helloworld.txt`
```
5
2
"HW"
"eo"
"lr"
"ll"
"od"
2
hello
world
```
run as
```
% groovy destriper.groovy helloworld.txt
```
] |
[Question]
[
Imagine bytes in memory for an RGB image--R and G and B represented by bytes in sequence. If an image is NxM then the memory layout will be M repetitions for vertical scanlines of 3\*N bytes in sequence for the horizontal pixels. (As one might expect.)
A mandate has come down from on high that you need to be able to isolate contiguous color planes. You might be asked for the R, G, or B plane. When you give back the plane it must be the N\*M bytes in sequence for that color.
Yet there is a twist: You cannot use additional memory proportional to the size of the image. Thus you must shuffle the bytes somewhere inside of the existing RGB data to provide the contiguous plane for the requested color. *And* you must be able to recover the original image when processing of that color plane is finished.
The image size is actually not relevant to the problem as it operates on the buffer as a whole. Input is bytes *(expressed as hexadecimal ASCII)* followed by which plane to extract:
```
00112233445566778899AABBCCDDEE
G
```
Output is the extracted color plane, then the original input \*(also in hexadecimal ASCII):
```
114477AADD
00112233445566778899AABBCCDDEE
```
Where you shuffle the memory is up to you. But you must actually shuffle the data to produce contiguous bytes *(requiring the client to use an iterator is cheating)*. And you must be able to reverse the operation to restore the original information.
Lowest big-O implementation wins. Between two implementations with equal big-O performance... winner decided by code golf rules.
[Answer]
# C
only shuffle, not print
lenght in bytes, not pixels
plane: 0,1,2 for R,G,B
not checked!
```
void deplane(unsigned char *data, int length, int plane) {
unsigned char *t = data;
unsigned char *s = data + plane;
unsigned char p;
while (s < data + length) {
p = *s; *s = *t; *t = p;
t++; s += 3;
}
// now plane start at data
while (t > data) {
s -= 3; t--;
p = *s; *s = *t; *t = p;
}
// back to original
}
```
[Answer]
# Javascript (E6)
I don't like the I/O format, these should be byte arrays or the like. Anyway.
Source not golfed.
```
S=(a,p)=>{
b = a.match(/../g); // String to array
l = b.length/3; // Plane size
s = p<'G'?2:p>'G'?0:1; // Which plane
for (j=0, i=s; b[i]; j++, i+=3) // Shuffle
[b[i],b[j]] = [b[j],b[i]];
console.log(b.slice(0,l).join('')); // Output plane
for (; i-=3, j--; ) // Unshuffle
[b[i],b[j]] = [b[j],b[i]];
console.log(b.join('')) // Original is back
}
```
**Usage**
In firefox console:
```
S('00112233445566778899AABBCCDDEE','G')
```
**Output**
```
114477AADD
00112233445566778899AABBCCDDEE
```
] |
[Question]
[
What general tips do you have for golfing in [LiveScript](http://livescript.net/)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to LiveScript (e.g. "remove comments" is not an answer). Please post one tip per answer.
[Answer]
# Take advantage of curried functions and Prelude.ls
If the function is already curried, it can be much shorter overall. Also, Prelude.ls is the ***standard library***, and its functions are often very useful. This means, unless otherwise specified, this library is 100% allowed. Examples:
```
f=->[1 to &0].reduce (*) # space required
f=->product [1 to &0]
s=(.reduce (+))
s=sum # better yet, avoid defining this when possible
d=(.map (*2))
d=map (*2) # Sometimes even shorter than native methods
r=->&0.reduce (-&1-)
r=->fold1 (-&1-),&0 # Equal if starting value is required.
a.=sort!
a=sort a # sometimes the same length
a.=sort ->&1.length-&0.length # space before arrow required
a.=sort over (-),(.length) # slightly more functional
a=sortBy (.length) # specific builtin, always prefer CamelCase
```
[Answer]
# Positional function arguments
In LiveScript, `&` is a shorthand for `arguments`. `arguments[0]` can be shortened to `&[0]`, which can be shortened to `&.0`, which in turn can be shortened to `&0`.
**Before:**
```
f=(x,y)->x+y
```
**After:**
```
f=->&0+&1
```
[Answer]
# `.n` over `[n]`, `\n` over `['n']`, etc.
This won't work for computed indices and members, but with static ones, it shaves bytes. Examples:
```
f[0]
f.0
f['str']
f\str
f['str with spaces']
f'str with spaces'
```
This will not work with other literals, such as RegExps, booleans, `null`, `void`, etc.
[Answer]
# Use partial functions when possible (with discretion)
Partial functions can drastically shorten many operations. Examples:
```
f=->it^2
f=(^2)
s=->&0.length==&1.length
s=over(==),(.length)
```
It isn't always better, though. Example:
```
# [[a, b], [c, d], [e, f]] -> (a+b)*(c+d)*(e*f)
f=(|>map sum|>product)
f=product map sum # these are actually curried
```
[Answer]
# `it` instead of explicit function argument
If you have a function with a single argument and you only refer to it at most twice, use `it` instead.
**Before:**
```
f=(x)->x+x
```
**After:**
```
f=->it+it
```
[Answer]
# Short form of `switch`
Use `|` instead of `case` and `|_` instead of `default`. Also, pipes themselves terminate statements.
**Before:**
```
switch x;case 1=>f;case 2=>g;default=>h
```
**After:**
```
switch x|1=>f|2=>g|_=>h
```
[Answer]
Avoid explicit commas and dots
This:
```
foo(1, 2, 3).bar
```
can be just:
```
foo(1 2 3)bar
```
[Answer]
Use the shortest function syntax possible
this:
```
->&0+&1
```
can be written:
```
(+)
```
and this:
```
->it.foo - it.bar
```
can be written:
```
(.foo- it.bar) # notice the dash position
```
] |
[Question]
[
Your task is to hide a small message or string inside a larger block of text. To do so, you must hide the message as capital letters inside the larger
For the quoted test:
>
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut convallis porta varius. Donec lo**B**ortis adipiscing dolor ac **E**uismod. Ut **M**incidunt e**Y** cursus nunc pul**V**inar, eu m**A**ttis nibh tincidunt. Phase**L**lus s**E**d molestie sapie**N**. In**T**eger congue maur**I**s in **N**isi faucibus, at aliquam ligula cons**E**ctetur. Quisque laoreet turpis at est cursus, in consequat.
>
>
>
(Emboldened text only to highlight where the letters are)
The secret text reads:
**BE MY VALENTINE**
You choose how to spread the words out, and should error if you try to hide a string inside another that won't fit either from length or lack of required characters.
Assume the input is plain text, where the first letter of each sentence may be capitalised or not (those can be lower cased or ignored, but should not be part of the secret message, for clarity).
You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.
E.g. If the Message hiding code is 73 characters, and the recovery one is 80, your score is:
```
(73+80)/2-10=66.5
```
[Answer]
## Ruby, (69+35)/2-10 = 42
```
a=gets
$><<gets.gsub(/./){a[0]!=$&?$&:a.slice!(0).upcase}
1/0if a>?\n
```
Takes input on STDIN, first line is the message to hide, second line is the text block. Assumes the secret message is lower-case. Example input:
```
codegolf
You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.
```
Example output:
```
You'll get -10 points for writing a seCOnD program that rEcovers the hidden messaGe frOm a bLock oF text. In this eventuality your score is the average of the two, minus the 10 bonus points.
```
Here's the program to obtain the secret back from the output (again, provided on STDIN):
```
$><<gets.scan(/(?<!^|\. )[A-Z]/)*''
```
One caveat here is that Ruby's lookbehind expressions have to be fixed width, so this code only works for text where the periods are followed by exactly one space. Suggestions welcome!
[Answer]
## Python 3, (136 + 74) / 2 - 10 = 95
Encoder (message must be lowercase):
```
t,m=input(),list(input().replace(' ', ''))
print([''.join(map(lambda c:m.pop(0).upper()if c.islower()and c in m[:1]else c,t))][bool(m)])
```
Decoder:
```
import re
print(filter(str.isupper, re.sub(r'(^|\. )[A-Z]', '', input())))
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Closed 10 years ago.
* **General programming questions** are off-topic here, but can be asked on [Stack Overflow](http://stackoverflow.com/about).
* Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
[Improve this question](/posts/15292/edit)
You are given a deck containing n cards. While holding the deck:
1. Take the top card off the deck and set it on the table
2. Take the next card off the top and put it on the bottom of the deck in your hand.
3. Continue steps 1 and 2 until all cards are on the table. This is a round.
4. Pick up the deck from the table and repeat steps 1-3 until the deck is in the original order.
Write a program to determine how many rounds it will take to put a deck back into the original order.
I found some answers online that had answers online for comparing and I cannot get the same answers. Either they are wrong or I am completely wrong. I went through a few examples of my own got these answers:
5 cards:
order: 12345
```
1: 24531
2: 43152
3: 35214
4: 51423
5: 12345 <-- 5 rounds
```
6 cards:
order: 123456
```
1: 462531
2: 516324
3: 341265
4: 254613
5: 635142
6: 123456 <-- 6 rounds
```
Answers I found online were:
Problem: <http://www.velocityreviews.com/forums/t641157-solution-needed-urgent.html>
```
Answer: http://www.velocityreviews.com/forums/t641157-p2-solution-needed-urgent.html <-- last post
```
I found another solution that has the same solution as mine but not sure on any solutions credibility:
```
http://entrepidea.com/algorithm/algo/shuffleCards.pdf
```
I was wondering if anyone has done this problem before and would be able to confirm which answers are correct. I need something to test against to see if my program is giving the correct output. THANKS!
[Answer]
# Python
```
def game(a):
deck = range(1,a+1)
#store the deck
origDeck = []
#copy the deck
origDeck.extend(deck)
table =[]
ans = 0
while 1:
while len(deck) > 0:
table.append(deck.pop(0))
if len(deck) == 0:
break
deck.append(deck.pop(0))
table.reverse()
deck,table=table,deck
ans+=1
#this is the condition that exits the infinite loop
if deck==origDeck:
break
print ans
```
Calling `game(n)` prints the number of rounds for n cards. The code can be easily changed to allow for printing the deck between rounds (add `print deck` before `if deck==origDeck`).
---
Tests (1 through 50):
```
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20
21: 21
22: 14
23: 24
24: 90
25: 63
26: 26
27: 27
28: 18
29: 66
30: 12
31: 210
32: 12
33: 33
34: 90
35: 35
36: 30
37: 110
38: 120
39: 120
40: 26
41: 41
42: 42
43: 105
44: 30
45: 45
46: 30
47: 60
48: 48
49: 120
50: 50
```
31 produces a peculiar output; it goes through 210 rounds.
It appears that primes have large cycles. For example, 97 has the largest cycle under 100: 6435.
[Answer]
# Pure Bash
It is not clear in your question (unless I missed it) if when you put a card on the table you put it *above* or *below* the cards already there. Here are two versions, and you'll see that the answer differs:
## Cards above
```
orig="12345"
deck=$orig
table=
nb=0
play() {
((++nb))
while [[ -n $deck ]]; do table=${deck:0:1}$table; deck=${deck:2}${deck:1:1}; done
deck=$table
table=
echo "$nb: $deck"
}
while ((nb==0)) || [[ $deck != $orig ]]; do play; done
```
this yields:
```
1: 24531
2: 43152
3: 35214
4: 51423
5: 12345
```
## Cards below
Replace `play` with:
```
play() {
((++nb))
while [[ -n $deck ]]; do table+=${deck:0:1}; deck=${deck:2}${deck:1:1}; done
deck=$table
table=
echo "$nb: $deck"
}
```
which yields:
```
1: 13542
2: 15243
3: 12345
```
## Golfed versions, reading input on stdin
* Below:
```
read o;d=$o;t=;n=0;p(){((++n));while [[ $d ]];do t+=${d:0:1};d=${d:2}${d:1:1};done;d=$t;t=;echo $d;[[ $d = $o ]]||p; };p;echo $n
```
* Above:
```
read o;d=$o;t=;n=0;p(){((++n));while [[ $d ]];do t=${d:0:1}$t;d=${d:2}${d:1:1};done;d=$t;t=;echo $d;[[ $d = $o ]]||p; };p;echo $n
```
[Answer]
# Mathematica
`shuffleTillUnshuffled[
n]` takes a deck of n cards and shuffles it until it returns to the
original order.
`playRound` takes a deck and returns the reordered deck of cards
after one round of shuffling.
`rule1` places the top card on the table and the second card at the
bottom of the deck.
`rule2` places the last card of the deck onto the table.
`[[2]]`, that is, `Part[{inHand,onTable},2]` removes the deck from the table so that it can be used, if
still unordered, in the next round.
```
rule1={{s_,m1_,e___},{l___}}:> {{e,m1},{s,l}};
rule2={{s_},{e__}}:> {{},{s,e}};
playRound[deck_]:=({deck,{}}//.{rule1,rule2})[[2]]
shuffleTillUnshuffled[nCards_]:= {rr=RotateRight[NestWhileList[playRound[#]&,playRound@Range@nCards,!OrderedQ[#]&]];
"Deck size: "<>ToString@nCards<>" cards; Rounds: "<>ToString@Length[rr],rr//Grid}
shuffleTillUnshuffled[4]
shuffleTillUnshuffled[5]
shuffleTillUnshuffled[13]
```

[Answer]
## Haskell
The way of handling cards is somewhat problematic, the code for `turn` became rather complex.
But finally both the cases for 5 and 6 match.
```
import Data.List
import Control.Arrow
spl :: [a] -> ([a],[a])
spl = (map snd***map snd) . partition ((==1).(`mod`2).fst) . zip [1..]
turn :: [a] -> [a]
turn' :: [a] -> [a] -> [a]
turn x = reverse $ turn' x []
turn' [] [] = []
turn' [] ls = turn' (reverse ls) []
turn' [x] [] = [x]
turn' [x] ls = turn' (x:(reverse ls)) []
turn' (x:y:ys) ls = x : (turn' ys (y:ls))
cardCycle x = first : (takeWhile (/=first) $ iterate turn (turn first))
where first = [1..x]
ans = length . cardCycle
main = mapM_ (\x -> putStrLn ((show x) ++ ": " ++ (show (ans x)))) [1..20]
```
.
```
1: 1
2: 2
3: 3
4: 2
5: 5
6: 6
7: 5
8: 4
9: 6
10: 6
11: 15
12: 12
13: 12
14: 30
15: 15
16: 4
17: 17
18: 18
19: 10
20: 20
```
16 seems to be an interesting one so here's the cycle (layout added):
```
> cardCycle 16
[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
,[16,8,12,4,14,10,6,2,15,13,11,9,7,5,3,1]
,[1,2,9,4,5,13,10,8,3,7,11,15,6,14,12,16]
,[16,8,15,4,14,7,13,2,12,6,11,3,10,5,9,1]]
```
] |
[Question]
[
Given a file named `hello_world` that contains 2-100 bytes of printable ASCII, create a Turing-complete language in which `hello_world` is a valid program that prints "Hello World!". The output should be two files: a compiler or interpreter, and a text file with the language spec.
**Rules**
* Shortest code wins. Length of (any of the) output doesn't matter.
* The generated compiler/interpreter must tokenize `hello_world` into at least two tokens, neither of which are ignored, and can't care about the filename.
* Your program can't use external resources (no cloning its own compiler).
* The generated code can be in any language, and can compile to any language.
[Answer]
Let's give it a try (and let everyone else copy it)
## Tcl
```
set f [open hello_world rb]
set h [split [read $f] {}]
for {set i 0} {$i<256} {incr i} {if {[set c [format %c $i]] ni $h} break}
set f [open i w]
puts $f [string map [list @1 [lindex $h 0] @2 [lindex $h 1] @3 $c] {set s 0;set i 0
set f [open [lindex $argv0] rb]
set c [split [read $f] {}]
foreach d $c {incr i
if {$d eq @1 && $s==0} {puts -nonewline "Hello ";incr s}
if {$d eq @2 && $s==1} {puts "World!"}
if {$d eq @3} {eval [join [lrange $c $i end] {}];break}}}]
puts [open d wb] [string map [list @1 [list [lindex $h 0]] @2 [list [lindex $h 1]] @3 [list $c]] {At the beginning the state is 0. Commands:
@1: If the state is 0, prints "Hello " without newline, increment the state.
@2: If the state is 1, prints "World!" with newline, flushes stdout and increases the state.
@3: Treats the rest of the file as Tcl.}]
```
[Answer]
## Perl, 271 chars
```
@e=qw'die"Hello\x20World!\n" $i-- $i++ $a[$i]-- $a[$i]++ push@s,$p $a[$i]?$p=$s[-1]:pop@s print+chr$a[$i] $a[$i]=ord<>';
$/=\1;@k=(<>..Z,A..Z);
say"# $k[$_]: $e[$_]"for 0..8;say;
say"\$e{\"\Q$k[$_]\E\"}=sub{$e[$_]};"for 0..8;
say'$/=\1;@c=<>;&{$e{$c[$p++]}||sub{}}while$p<@c'
```
(The code above has some non-essential line breaks inserted for readability. All line breaks may be removed without affecting the behavior, and should not be counted for scoring purposes.)
Run with `perl -M5.010` to enable the `say` feature. Reads the input program from standard input (or from a file given as a command line argument), prints an interpreter to standard output. The output is also a Perl script, and should be executed the same way.
The (rudimentary) language spec is included as comments at the beginning of the interpreter, and is formatted as a list of characters and the Perl commands each of them will execute. In the spec, `$p` stands for the program counter (which points to the next instruction to execute), `@s` for the loop stack, `$i` for the tape index and `@a` for the tape.
---
Basically, the language executed by the interpreter is exactly what ugoren suggested in the comments: a simple variant of Brainf\*ck, with an extra command that prints `Hello World!` and ends the program. This extra command is mapped to the first character of the input program, while the other commands are mapped to subsequent letters. All unrecognized characters are ignored.
For example, using the input `AAAAAA`, the output will look like this:
```
# A: die"Hello\x20World!\n"
# B: $i--
# C: $i++
# D: $a[$i]--
# E: $a[$i]++
# F: push@s,$p
# G: $a[$i]?$p=$s[-1]:pop@s
# H: print+chr$a[$i]
# I: $a[$i]=ord<>
$e{"A"}=sub{die"Hello\x20World!\n"};
$e{"B"}=sub{$i--};
$e{"C"}=sub{$i++};
$e{"D"}=sub{$a[$i]--};
$e{"E"}=sub{$a[$i]++};
$e{"F"}=sub{push@s,$p};
$e{"G"}=sub{$a[$i]?$p=$s[-1]:pop@s};
$e{"H"}=sub{print+chr$a[$i]};
$e{"I"}=sub{$a[$i]=ord<>};
$/=\1;@c=<>;&{$e{$c[$p++]}||sub{}}while$p<@c
```
Running the resulting code above with the same input produces the expected output:
```
Hello World!
```
whereas running the same code with the input `EEEEEEFDCEEEEBGCFDCECEEEEBBGCEEFDCEHBG` (transliterated from [this answer](https://codegolf.stackexchange.com/a/5627)) prints:
```
abcdefghijklmnopqrstuvwxyz
```
Ps. To convert normal Brainf\*ck code to the variant understood by this interpreter, you can use the transliteration:
```
tr/<>\-+[].,/B-I/
```
where `B-I` should be replaced by the appropriate range of command letters as per the generated spec.
Notes on the BF implementation:
* The tape is single-ended, with the read/write head starting at cell 0. Moving the head to a negative position might not cause an error, but will produce weird effects related to Perl's array indexing and should be considered undefined behavior.
* Cell values do *not* wrap around. Technically, each cell is stored as a double, meaning that at some point the value will saturate and further inc/decrements will have no effect. You'll die of boredom before that happens, though.
* Character I/O depends on Perl's I/O layers. By default, input values are unsigned bytes, and attempting to output values outside the range 0 – 255 gives a warning message. Passing the `-CS` switch to Perl will enable Unicode I/O (encoded as UTF-8), though. Input at EOF yields a zero. To supply both a program and its input on stdin, separate them with a `Ctrl`+`D` character (`"\cD"` or `"\x05"`).
**Edit:** I later realized that there's a major difference between the language I implement above and real Brainf\*ck: in my language, the loop condition is checked at the *end* of the loop, rather than at the beginning, which means that every loop executes at least once. In effect, loops in my language behave like `do`–`while` loops in C-ish languages, whereas those in normal BF behave like plain `while` loops.
As it happens, the difference doesn't matter for the example program above, since all its loops run at least once anyway. What I'm not quite sure about is whether the proof of BF's Turing-completeness can still be made to apply to my variant of the language or not. It might be possible, but it's going to be tricky without any easy way to implement an `if` statement.
I suppose I could fix my program to behave more like normal BF, but it would be a pain in the ass to do without a major redesign of the execution model. :(
] |
[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/6820/edit).
Closed 4 years ago.
[Improve this question](/posts/6820/edit)
AKA: the most complex way to return a string I could think of.
**Requirements:**
\**Edit: \** @Griffin, You are correct, the goal is to use crossover/mutation of characters in a string to eventually come up with the same as input, although, "Hello World" was simply an example. Really, I just like to see what the others on the site can come up with.
Golf. Try to keep it short.
Have fun, dag nabbit!
**Preferences (not required):**
-Using a fixed seed on a random number generator would help others reproduce your results.
-Bonus if you test for 'properties' of the string, such as the number of L's in "Hello World", instead of only correct characters (like mine).
Shortest code, or highest voted, wins.
One exception: if you manage to create a working version in BrainF\*\*\*, you win.
**My take using Java:**
```
import static java.lang.Math.*;import java.util.Arrays;import static java.lang.System.out;import java.util.Random;class G{static char[]c;static Random r;public static void main(String[]a){c=a[0].toCharArray();r=new Random(6);P w=new P(9);int n=0;while(!w.f){w.s();if(w.f)out.println(w.g[w.p].x()+"@gen "+n);n++;}}static class P{boolean f=false;int p=0;M[]g=null;P(int s){if(s>=9)g=new M[s];else g=new M[9];for(int i=0;i<g.length;i++)g[i]=new M(c.length);}void s(){f();if(!f){h();j();}}void f(){for(int i=0;i<g.length;i++){g[i].f(c);if(g[i].l==0){f=true;p=i;}}}void h(){Arrays.sort(g);}void j(){M[]b=new M[g.length];for(int i=0;i<g.length-1;i++){float k=r.nextInt(100);if(k<40)b[i]=new M(g[0],g[1]);else if((k<60)&&(k>40))b[i]=new M(g[0],g[2]);else if((k<80)&&(k>60))b[i]=new M(g[1],g[2]);else if((k<90)&&(k>80))b[i]=new M(g[2],g[3]);else if((k<95)&&(k>90))b[i]=new M(g[2],g[4]);else if((k<99)&&(k>95))b[i]=new M(g[0],g[r.nextInt(g.length)]);else b[i]=new M(g[0],new M(c.length));b[g.length-1]=g[0];}g=b;}}static class M implements Comparable {char[]a=null;int l=0;int q=0;int u=8;int o=20;public int compareTo(Object o){M t=(M)o;if(this.l<t.l)return-1;else if(this.l>t.l)return 1;return 0;}M(int s){a=new char[s];for(int i=0;i<a.length;i++)a[i]=(char)r.nextInt(255);}M(M m,M p){a=new char[m.a.length];for(int i=0;i<m.a.length;i++){a[i]=(r.nextInt(100)>2)?m.a[i]:p.a[i];int z=r.nextInt(100);if(z<u)a[i]=(char)r.nextInt(255);else if(z<o){int b=r.nextInt(6);a[i]=(char)(a[i]^(1<<b));}}}void f(char[]v){l=0;for(int i=0;i<a.length;i++){int d=abs(a[i]-v[i]);l+=d;}}String x(){return new String(a);}}}
```
Example output from my code:
```
Hello World!@gen 3352
```
[Answer]
## APL (98)
```
L←⍴T←⎕UCS'Hello World!'⋄F←{+/2*⍨⍵-T}⋄0{0=F ⍵:⍺,⎕UCS⍵⋄(⍺+1)∇{(F⍵)≤F⊢C←⍵+(2-?3)×(⍳L)=?⍴⍵:⍵⋄C}⍵}L?255
```
Can be shortened, at the expense of easy configurability and of result, I'll do so when this one is beaten.
Output:
```
5940 Hello World!
(or another number between ~4000-~9000).
```
Credit for the algorithm: <http://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/>
Explanation:
* `L←⍴T←⎕UCS'Hello World!'`: The target is the ASCII values (`⎕UCS`) of 'Hello World'. (You can change the string.) `L` is its length.
* `F←{+/2*⍨⍵-T}`: F measures the 'distance' between a candidate and a target. This is the sum of the squares of the difference between each character.
* `0{0=F ⍵:⍺,⎕UCS⍵⋄(⍺+1)∇`...`⍵}L?255`: Starting with a random string (`L?255`), if the distance between the target and the candidate is 0 (i.e. we have it) (`0=F ⍵:`), then output the generation and the string (`⍺,⎕UCS⍵`). Otherwise, mutate the candidate and proceed to the next generation.
* `(F⍵)≤F⊢C←⍵+(2-?3)×(⍳L)=?⍴⍵:⍵⋄C`: Generate a new candidate by selecting a random position and mutating it by one. If the distance to the target is less than the old candidate, return the new candidate, otherwise keep the old candidate.
[Answer]
# pdfTeX, 2663
```
\RequirePackage{xparse}
\ExplSyntaxOn
\tl_new:N \l_my_base_tl
\int_new:N \l_my_len_int
\prop_new:N \l_my_base_prop
\prop_new:N \l_my_trial_a_prop
\prop_new:N \l_my_trial_b_prop
\int_new:N \l_my_diff_a_int
\int_new:N \l_my_diff_b_int
\cs_generate_variant:Nn \tl_replace_all:Nnn { Nno }
\DeclareDocumentCommand{\do}{v}
{
\tl_set:Nx \l_my_base_tl { \tl_to_str:n {#1} }
\tl_replace_all:Nno \l_my_base_tl { ~ } { \c_catcode_other_space_tl }
\int_zero:N \l_my_len_int
\tl_map_inline:Nn \l_my_base_tl
{
\int_incr:N \l_my_len_int
\prop_put:NVn \l_my_base_prop \l_my_len_int {##1}
}
\my_get_diff:NN \l_my_base_prop \l_tmpa_int
\int_step_inline:nnnn { 1 } { 1 } { \l_my_len_int }
{ \prop_put:Nnn \l_my_trial_a_prop {##1} { O } }
\my_term:
\my_get_diff:NN \l_my_trial_a_prop \l_my_diff_a_int
\bool_set_false:N \l_tmpa_bool
\bool_until_do:Nn \l_tmpa_bool
{
\prop_set_eq:NN \l_my_trial_b_prop \l_my_trial_a_prop
\prop_map_inline:Nn \l_my_trial_b_prop
{
\prop_get:NnN \l_my_trial_b_prop {##1} \l_tmpa_tl
\prop_get:NnN \l_my_base_prop {##1} \l_tmpb_tl
\exp_args:Noo \token_if_eq_charcode:NNF \l_tmpa_tl \l_tmpb_tl
{
\int_set:Nn \l_tmpa_int
{ \exp_after:wN `\l_tmpa_tl + \pdfuniformdeviate 7 - 3 }
\char_set_lccode:nn { `* }
{ \int_max:nn { 32 } { \int_min:nn { 127 } { \l_tmpa_int } } }
\tl_to_lowercase:n
{ \prop_put:Nnn \l_my_trial_b_prop {##1} { * } }
}
}
\my_get_diff:NN \l_my_trial_b_prop \l_my_diff_b_int
\int_compare:nT { \l_my_diff_b_int < \l_my_diff_a_int }
{
\prop_set_eq:NN \l_my_trial_a_prop \l_my_trial_b_prop
\int_set_eq:NN \l_my_diff_a_int \l_my_diff_b_int
\int_compare:nT { \l_my_diff_b_int = 0 }
{ \bool_set_true:N \l_tmpa_bool }
\my_term:
}
}
\tex_end:D
}
\cs_new_protected:Npn \my_get_diff:NN #1#2
{
\int_zero:N #2
\prop_map_inline:Nn #1
{
\prop_get:NnN \l_my_base_prop {##1} \l_tmpa_tl
\int_add:Nn #2
{
( \my_char_value:o \l_tmpa_tl - \my_char_value:n {##2} )
* ( \my_char_value:o \l_tmpa_tl - \my_char_value:n {##2} )
}
}
}
\cs_new:Npn \my_char_value:n #1 { \int_eval:n { `#1 } }
\cs_generate_variant:Nn \my_char_value:n { o }
\cs_new_protected_nopar:Npn \my_term:
{ \iow_term:x { \prop_map_function:NN \l_my_trial_a_prop \use_ii:nn } }
\ExplSyntaxOff
\expandafter\do\noexpand
```
Call as
```
pdflatex Experiment573.tex +Hello, World+
```
where the `+` delimiters are arbitrary (identical). I chose `+` here because many more conventional delimiters have a meaning on the command line. This could be shortened quite a bit: I initially thought I'd need floating point computations, which are not available without the `expl3` programming language, so I loaded and used that, which is quite verbose.
[Answer]
# Python, ~~289~~ 286
```
from random import randint as r
s=map(ord,raw_input()[:-1])
L=len(s)
d=lambda x:sum((a-b)**2 for a,b in zip(x,s))
p=map(list,[(64,)*L]*500)
n=0
while 1:
n+=1
for b in p:b[r(0,L-1)]+=r(-5,5)
if any(i==s for i in p):break
p=sorted(p,key=d)[:100]
p+=[i[:]for i in p][:500-100]
print n
```
Starting population is a list of strings: `"@" * length_of_input`. Uses the squared sum of the distance for each character and corresponding target character as the fitness function.
[Answer]
# C# - 432
```
using System;using System.Linq;class M{static void Main(string[] a){var g=a[0];int l=g.Length,P=182,S=P/2,k=0,I=0;var r=new Random();Func<int,string>z=null;z=A=>A==0?"":(char)(r.Next(S)+32)+z(A-1);var p=new string[P];while(k<P)p[k++]=z(l);while(p[k=0]!=g){p=p.OrderBy(s=>s.Select((t,i)=>t==g[i]?0:1).Sum()).ToArray();I++;while(k<S){var Q=p[k].ToCharArray();Q[r.Next(l)]=z(1)[0];p[S+k++]=new string(Q);}}Console.WriteLine(I+" "+g);}}
```
Example output:
171 Hello there :)
Better formatted (character count is higher...)
```
using System;
using System.Linq;
class M
{
static void Main (string[] a)
{
var g = a [0];
int l = g.Length, P = 182, S = P / 2, k = 0, I = 0;
var r = new Random ();
Func<int,string> z = null;
z = A => A == 0 ? "" : (char)(r.Next (S) + 32) + z (A - 1);
var p = new string[P];
while (k<P)
p [k++] = z (l);
while (p[k=0]!=g) {
p = p.OrderBy (s => s.Select ((t,i) => t == g [i] ? 0 : 1).Sum ()). ToArray ();
I++;
while (k<S) {
var Q = p [k].ToCharArray ();
Q [r.Next (l)] = z (1) [0];
p [S + k++] = new string (Q);
}
}
Console.WriteLine (I + " " + g);
}
}
```
*Initialization*
An array of 198 random candidates is created (by use of the recursive random string generation function z)
*Main Loop*
The array is (re)sorted by the number of mismatches within the string (this used less characters than power or absolute value). The bottom half of the population is replaced with mutations (by one char) on the first half (the fitter part of the population).
*Termination*
Once the fittest member is equal to the goal, the number of iterations is printed along with the output string.
This is my first golf submission and likely the last one done with C#. I may also try to regolf this in a terser language later.
] |
[Question]
[
Interpret a triple of 32-bit integers as a vector of 32 integers modulo 5. Write an addition routine for these vectors.
**Example**:
```
def add32((a0,a1,a2),(b0,b1,b2)):
c0 = c1 = c2 = 0
m = 1
for i in range(32):
a = ((a0//m)&1) + 2*((a1//m)&1) + 4*((a2//m)&1)
b = ((b0//m)&1) + 2*((b1//m)&1) + 4*((b2//m)&1)
c = (a+b)%5
c0+= m*(c&1)
c1+= m*((c&2)//2)
c2+= m*((c&4)//4)
m += m
return c0,c1,c2
```
**Note**:
You only need to be internally consistent, not consistent with my sample code. If you use a different representation of the integers mod 5, that's fine as long as you provide a translation table of the form:
```
0 = 000 or 101
1 = 001 or 110
2 = 010 or 111
3 = 011
4 = 100
```
**Scoring**:
Characters + number of arithmetic operations required. The sample code takes 331 characters and 34 operations per bit (note that I'm not counting the function call or iteration, nor interpreter overhead); hence gets a score of 331+1056=1686.
**Clarification**:
This is a trick called *bitslicing*. It's natural to pack integers mod 5 directly into words (spaces added for clarity:
```
0 1 2 3 4 -> 000 001 010 001 101
```
but you end up sacrificing a few bits at the end of each word. To keep your data aligned but pack the most in, store the data in *slices*
```
0 0 0 0 1 = a2
a = 0 1 2 3 4 -> 0 0 1 1 0 = a1
0 1 0 1 0 = a0
```
**Example 2**
A language-agnostic example was requested, so here it is. Suppose we use the representation
```
0 = 100
1 = 001
2 = 010 or 101
3 = 110
4 = 011
```
and `111` and `000` are meaningless. Then, the following sum is valid according to our representation:
```
1 0 0 1 1 0 1 0
0 1 2 2 3 4 0 2 = 0 0 1 0 1 1 0 1
0 1 0 1 0 1 0 0
+
0 1 0 0 1 0 1 1
1 2 1 2 0 1 0 3 = 0 0 0 1 0 0 0 1
1 1 1 0 0 1 0 0
---------------------------------
0 1 1 0 1 1 1 1
1 3 3 4 3 0 0 0 = 0 1 1 1 1 0 0 0
1 0 0 1 0 0 0 0
```
**Remark**
As [Keith Randall](https://codegolf.stackexchange.com/questions/3083/add-two-vectors-modulo-5/3087#3087) has demonstrated, this can be done with all bits in parallel using logical operators. We can view such a solution as a circuit with a certain number of gates. Perhaps I should call this "circuit golf". I chose 5 instead of 3 because it's too easy to brute-force (optimal is 6 gates/trit).
[Answer]
## Python, score=215 166 (167 118 chars, at most 48 ops)
```
def A(x,y,z,p,q,r):
u,c=x^p,x&p;v,d=y^q^c,y&q|y&c|q&c;w,e=z^r^d,z&r|z&d|r&d
if e:u,v,w=A(e,e,0,u,v,w)
return u,v,w
```
Does addition in bit-parallel. The `c,d,e` are the 32 carries from one position to the next. `e` represents multiples of 8 that carry out of the vector, so if `e` has any bits set in it, we add 8%5=3 back in using a recursive call.
The translation table is the same as the one given in the question.
] |
[Question]
[
## Background
Often, when storing a number in binary with some maximum, we simply round the maximum to the next power of two then allocate the number of bits nececairy to store the whole range. Lets call the result of this method \$S(x, m)\$ where x is the number and m is the maximum.
While not bad, the naive has a few bits of redundancy since some bit patterns could only lead to a number beyond the max. You can exploit this to create a slightly shorter variable-length representation for numbers.
## The format
I will define such a format as follows:
* Let x be the number we want to represent and m be the max
* Let d the the difference between `m` and the next smaller power of 2. (in other words with the first 1 chopped of the binary representation)
* If m is 0, return the empty string
* If x is less than or equal to d:
+ Output "0" followed by f(x, m)
* Otherwise:
+ Output "1" followed by the log2(m)-bit binary representation of `x-d-1`.
Python translation:
```
def d(x): return x-(1<<x.bit_length()-1)
def f(x, m):
if m==0:
return ''
if m==1: # edge cases needed to deal with the fact that binary coding in python produces at least one 0 even if you specify 0 digits
return f'{x}'
if x<=d(m):
return '0'+f(x,d(m))
else:
return f'1{x-d(m)-1:0>{m.bit_length()-1}b}')
```
## Challenge
Output a pair of functions `f(x,m)` and `f'(y,m)` that convert to and from compressed binary representation for a given maximum.
You may assume `m>3` and `x<=m`.
The binary representation can be as a string, integer, list of ints, decimal coded binary, or anything else reasonable.
If you prefer you can take `m+1` as input instead of `m`. (exclusive maximum)
## Test Cases
Rows are X, columns are M
```
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
0 00 00 000 0 00 00 000 00 000 000 0000 0 00 00 000 00 000 000 0000
1 01 010 001 1000 01 010 001 0100 001 0010 0001 10000 01 010 001 0100 001 0010 0001
2 100 011 010 1001 1000 011 010 0101 0100 0011 0010 10001 10000 011 010 0101 0100 0011 0010
3 101 100 011 1010 1001 1000 011 0110 0101 0100 0011 10010 10001 10000 011 0110 0101 0100 0011
4 110 101 100 1011 1010 1001 1000 0111 0110 0101 0100 10011 10010 10001 10000 0111 0110 0101 0100
5 111 110 101 1100 1011 1010 1001 1000 0111 0110 0101 10100 10011 10010 10001 10000 0111 0110 0101
6 111 110 1101 1100 1011 1010 1001 1000 0111 0110 10101 10100 10011 10010 10001 10000 0111 0110
7 111 1110 1101 1100 1011 1010 1001 1000 0111 10110 10101 10100 10011 10010 10001 10000 0111
8 1111 1110 1101 1100 1011 1010 1001 1000 10111 10110 10101 10100 10011 10010 10001 10000
9 1111 1110 1101 1100 1011 1010 1001 11000 10111 10110 10101 10100 10011 10010 10001
10 1111 1110 1101 1100 1011 1010 11001 11000 10111 10110 10101 10100 10011 10010
11 1111 1110 1101 1100 1011 11010 11001 11000 10111 10110 10101 10100 10011
12 1111 1110 1101 1100 11011 11010 11001 11000 10111 10110 10101 10100
13 1111 1110 1101 11100 11011 11010 11001 11000 10111 10110 10101
14 1111 1110 11101 11100 11011 11010 11001 11000 10111 10110
15 1111 11110 11101 11100 11011 11010 11001 11000 10111
16 11111 11110 11101 11100 11011 11010 11001 11000
17 11111 11110 11101 11100 11011 11010 11001
18 11111 11110 11101 11100 11011 11010
19 11111 11110 11101 11100 11011
20 11111 11110 11101 11100
21 11111 11110 11101
22 11111 11110
23 11111
```
[Answer]
# JavaScript (ES6), 65 + 67 = 132 bytes
## Encoder (65 bytes)
Expects `(x)(m)` and returns a binary string.
```
x=>g=m=>m?x>(m-=q=1<<Math.log2(m))?(q|x+~m).toString(2):0+g(m):""
```
[Try it online!](https://tio.run/##XZDbasMwDIbv@xTCVzYmIXZPaxInV7vcVZ/ANId1xEmamBHYulfPZI2yMYE/gaX/t@Q3@27ny3QdfdQPVb02Zl1M0RpnClcuBXeRuRmV5y/Wv8bd0GruhCj57XORX07Efjj76dq3XIs0kS0WU8bWy9DPQ1eHfs4AYA8hDsQj8Yl4IqqEqIiauCXuiCRWJFYkViRWJNak1aTVpNVbJrLN/wkYSGBRCGDxVI@19VydBHY2w8S72sMCBpIMUw56h1lKAR8bgFCbsbb87iri0VZnbyePawdjYBl2Ppwcdu8zTD9O7uEE6CMNcHzCYLWEhi8CfwxSHI2R6XNf8YMIZnc8f5eY8fa@fgM "JavaScript (Node.js) – Try It Online")
### Commented
```
x => // outer function taking x
g = m => // inner recursive function taking m
m ? // if m is not zero:
x > ( // if x is greater than
m -= // the updated value of m defined as
q = // m - q, where q is the highest
1 << Math.log2(m) // power of 2 less than or equal to m,
) ? // then:
(q | // use q for the leading 1
x + ~m) // use x - m - 1 for the payload data
.toString(2) // convert to binary
: // else:
0 + // append a 0 and
g(m) // do a recursive call with the updated m
: // else:
"" // stop
```
## Decoder (67 bytes)
Expects `(x,m)`, where `x` is a binary string. Returns an integer.
```
f=([c,...x],m)=>c?[f(x,m-=1<<Math.log2(m)),m-~`0b${x.join``}`][c]:0
```
[Try it online!](https://tio.run/##ZVDLbsIwELzzFSurB1sBKwmFlgQnpx574oiQkuZVEE4gsSpLFH493SygotaSZyV7ZjzjXfqVdlm7PZhJ3eRF35eKr7OxlNJuxlqoKIvXJbdjPVHecvmemk@5byqfayHw7JK4H08nK3fNtk6Sc7JZZ5vA7bOm7pp9MTA5A4AZDGtO@EL4Srgg9FxCj9AnnBI@E5LYI7FHYo/EHol90vqk9UnrT5kIR38TMHCATYYFTLbFoUgN9xYCmfvCQFFn2L0FBVZFldIq0rGNOHY@/msd8@O3dS5aSNOsTLutK@6LwHUqvAwYC0dl0/LB1KKdG@JYgv@M03EEnEYAw103PPVrIOQhzVcmbQ16DUkBfQDuThrZsxDH1Unfna5e1/A5cm41uBWYJSRCB44CjhkUymMo@Y09hscCAgL8HUYx3uqcz0l9xv34jx2envsf "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[c, // c = next character in the binary string
...x], // x[] = array of remaining characters
m // m = maximum
) => //
c ? // if c is defined:
[ // return either:
f( // the result of this recursive call (*):
x, // pass x unchanged
m -= // subtract from m the highest
1 << Math.log2(m) // power of 2 less than or equal to m
), // end of recursive call
m - ~`0b${x.join``}` // or m + x[] parsed as binary + 1
][c] // according to c
: // else:
0 // stop
```
*\* Because this call is enclosed in an array, it is always executed regardless of whether the result is actually used or ignored. Since each recursion is guaranteed to stop as soon as the input string is fully consumed, this has no harmful side effects other than performance degradation.*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 + 35 = 75 bytes
## Encoder, 40 bytes
```
NθNηWθ«≔↨²E↨θ²∧λκζ¿›ηζ«1≧⁻⊕ζη≧⁻⊕ζθ»«0≔ζθ
```
[Try it online!](https://tio.run/##lY/BDoIwEETP5SsaTiWpiRATD57wYjhgjH9QYaWNpUJbNMHw7bUVY7h629mdfZOpONPVnUnnCtUN9ji0F9CkT3bRUnOvn1xIwP6EXxHKjRGNIntmgGQUl6yb557iLKE4VzWRFN@SxIvRPyNxxeSggdlAC7sPBp20UJbEaRw8yGNm8Fk03JJSqMFQXKhKQwvKQk1Gz@N/eEMRNEUIpIFl4HoO/NYYf8bJuXQTbd3qId8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `m` and `x`.
```
Wθ«
```
Repeat until `m=0`.
```
≔↨²E↨θ²∧λκζ
```
Calculate `d` by setting the most significant bit of `m` to zero.
```
¿›ηζ«
```
If `x` is greater than `d`, then...
```
1≧⁻⊕ζη≧⁻⊕ζθ
```
... output a `1` and subtract `d+1` from `x` and `m`. This causes the rest of the bits to be encoded as binary.
```
»«0≔ζθ
```
Otherwise output a `0` and set `m` equal to `d`.
## Decoder, ~~36~~ 35 bytes
```
≔⍘N²θI∧Ση⊕⁺⍘⁺0Φθ›Σ…θκ⌕η1²⍘⁺0ΦηΣ…ηκ²
```
[Try it online!](https://tio.run/##fY3NCsIwEITvPkXIaQMRUvHWUy0ovUihTxDT0BTTtM2P4NPHpHrQiwsLO8zMt0JxK2auY6ycGwcDJ@5k5@1oBmjMEvw1TDdpgVB0SLuSctcm00PNnYfK9NCFCVSyGiOsnKTxsodWB/dN2jRmmKLzqH3CrRRdrOT5zP36KbSs1bxk405IziW0oggXmBDy@f6PmLK/JLWR3tVtyhiL465gjMX9Q78A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Converts `m` to binary. If the value to be decoded contains any `1` bits, then a number of leading `1` bits is removed from the binary representation of `m`, and the first `1` bit is removed from the value to be decoded, and the two are then converted from binary, summed and incremented. Otherwise the output is simply zero.
Previous 36-byte decoder used a method similar to that of the encoder:
```
NθFS«≔↨²E↨θ²∧λκζ¿Iι«M⊕ζ→≧⁻⊕ζθ»≔ζθ»Iⅈ
```
[Try it online!](https://tio.run/##XY6xDoIwEIbn9iluvCY1AeIkEzo5YIwurhUKNkLRtjhgfPZaqJPb3Z//vvuqmzDVIDrv9/oxusPYX6XBJ8tpMxjAJTw7o3SLjMGbksJa1WrcCisx41CKR5yfHDLGodA1dhzujIVlChiiGsCdsA5VBJByeMkArozspXayxilUNyfV3tzcJwEZnywRlkqPlsP/waxIPpTIzkr4SU0x/tBjEHbx6yV4596na5omSeJXr@4L "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `m`.
```
FS«
```
Loop over the bits to be decoded.
```
≔↨²E↨θ²∧λκζ
```
Calculate `d` by setting the most significant bit of `m` to zero.
```
¿Iι«
```
If the next bit is a `1`, then...
```
M⊕ζ→≧⁻⊕ζθ
```
... add `d+1` to `x` and subtract it from `m`. This causes the rest of the bits to be decoded as binary.
```
»≔ζθ
```
Otherwise set `m` equal to `d`.
```
»Iⅈ
```
Output the final value of `x`.
] |
[Question]
[
Consider an \$n \times n\$ grid of integers. The task is to draw a straight line across the grid so that the part that includes the top left corner sums to the largest number possible. Here is a picture of an optimal solution with score 45:
[](https://i.stack.imgur.com/Oq6xh.png)
We include a square in the part that is to be summed if its middle is above or on the line. Above means in the part including the top left corner of the grid. (To make this definition clear, no line can start exactly in the top left corner of the grid.)
The task is to choose the line that maximizes the sum of the part that includes the top left square. The line must go straight from one side to another. The line can start or end anywhere on a side and not just at integer points.
The winning criterion is worst case time complexity as a function of \$n\$. That is using big Oh notation, e.g. \$O(n^4)\$.
# Test cases
I will add more test cases here as I can.
The easiest test cases are when the input matrix is made of positive (or negative) integers only. In that case a line that makes the part to sum the whole matrix (or the empty matrix if all the integers are negative) wins.
Only slightly less simple is if there is a line that clearly separates the negative integers from the non negative integers in the matrix.
Here is a slightly more difficult example with an optimal line shown. The optimal value is 14.
[](https://i.stack.imgur.com/XDsHL.png)
The grid in machine readable form is:
```
[[ 3 -1 -2 -1]
[ 0 1 -1 1]
[ 1 1 3 0]
[ 3 3 -1 -1]]
```
Here is an example with optimal value 0.
[](https://i.stack.imgur.com/kyQDM.png)
```
[[-3 -3 2 -3]
[ 0 -2 -1 0]
[ 1 0 2 0]
[-1 -2 1 -1]]
```
Posted a question to [cstheory](https://cstheory.stackexchange.com/questions/53674/is-there-a-lower-bound-for-the-problem-of-finding-the-best-straight-line-partiti) about lower bounds for this problem.
[Answer]
# Python3, O(n^4):
I'm not 100% sure this is correct, but I think at least the approach is solid and it seems to work OK.
```
import numpy as np
import fractions
def best_line(grid):
n, m = grid.shape
D = [(di, dj) for di in range(-(n - 1), n) for dj in range(-(n - 1), n)]
def slope(d):
di, dj = d
if dj == 0:
return float('inf') if di <= 0 else float('-inf'), -di
else:
return fractions.Fraction(di, dj), fractions.Fraction(-1, dj)
D.sort(key=slope)
D = np.array(D, dtype=np.int64)
s_max = grid.sum()
for grid in (grid, grid.T):
left_sum = 0
for j in range(grid.shape[1]):
left_sum += grid[:,j].sum()
for i in range(grid.shape[0]):
p = np.array([i, j], dtype=np.int64)
Q = p + D
Q = Q[np.all((0 <= Q) & (Q < np.array(grid.shape)), axis=1)]
s = left_sum
for q in Q:
if not np.any(q):
break
if q[1] <= j:
s -= grid[q[0],q[1]]
else:
s += grid[q[0],q[1]]
s_max = max(s_max, s)
return s_max
```
] |
[Question]
[
Digital sum, DR, Digit root is the iterative process of summing digits of a number until you end up with a single digit root number: e.g. digit root of 12345 is 6 since 1 + 2 + 3 + 4 + 5 = 15 = 1+5. Also look at [Digit root challenge](https://codegolf.stackexchange.com/questions/97713/print-the-digital-root).
### Input:
Given integers `m` and `n` which are the modular and multiplier for sequence.
### Output:
Return all cyclic sequences of length greater than one for [Digit roots](https://en.wikipedia.org/wiki/Digital_root) of `n` \* `i` in base `m` + 1.
* \$1\$ ≤ \$i\$ ≤ \$m\$
* \$1\$ ≤ \$DR(n\*i) \$ ≤ \$m\$
* \$DR(i) = i \$
* \$DR(-m) = 0 \$
* \$|DR(-x)| \equiv DR(x) \equiv -DR(x)\$ (mod \$ m) \$
* \$DR(a+b) = DR(DR(a)+DR(b))\$
* \$DR(a-b) \cong (DR(a)-DR(b))\$ (mod \$ m) \$
### Example Input:
```
9 4
```
### Example Output:
```
1 4 7
2 5 8
```
## More details:
```
m=9, n=4
DR(4*1) -> 4
DR(4*4) -> 7
DR(4*7) -> 1 = first i
```
A cycle happens when going through numbers 1 trough `m`
taking digit root of `n` \* `i` and then digit root of `n` \* result of previous call and so on until returns to the first `i`.
Note that if there is no cycle taking digit root of `n` \* `i` would simply result to `i`.
So we store this sequence in something like a hash set for all the `i`'s and then return all the sequences.
## Challenge
All the normal [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules are applied excepts the answer with smaller sum of digit roots of each individual byte wins.
Example program of how to calculate the Σ digit sums of your code:
```
from sys import stdin
score=lambda s:sum((ord(c)-1)%9+1for c in s if ord(c)>0)
bytes=lambda s:"".join(str([ord(c)for c in s]).replace(',','').replace(']','').replace('[',''))
dr_bytes=lambda s:"".join(str([(ord(c)-1)%9+1for c in s]).replace(',',' +').replace(']',' =').replace('[',''))
code="\n".join(stdin.readlines())
print(bytes(code))
print(dr_bytes(code), end=' ')
print(score(code))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score = 104
```
x⁹Sḃ³Ṛḷ/)ƬR1¦z7MṖ’ƊPḄƊoEƊÐḟQ€
```
A dyadic Link accepting `m` on the left and `n` on the right that yields a list of lists of integers (each integer being a "digit").
**[Try it online!](https://tio.run/##AUAAv/9qZWxsef//eOKBuVPhuIPCs@G5muG4ty8pxqxSMcKmejdN4bmW4oCZxoowZcaKxodR4oKsRcOQ4bif////Of80 "Jelly – Try It Online")**
The byte code is (see Jelly's code-page [here](https://github.com/DennisMitchell/jelly/wiki/Code-page)):
```
120 137 83 231 131 182 218 47 41 152 82 49 5 122 55 77 203 253 145 80 172 145 111 69 145 15 235 81 12
```
So the score is:
```
3+2+2+6+5+2+2+2+5+8+1+4+5+5+1+5+5+1+1+8+1+1+3+6+1+6+1+9+3 = 104
```
### How?
```
x⁹Sḃ³Ṛḷ/)ƬR1¦z7MṖ’ƊPḄƊoEƊÐḟQ€ - Link: m; n
Ƭ - collect inputs while unique, starting with m, applying:
) - for each d (where m is implicitly treated as [1..m]):
⁹ - n
x - d repeated n times |
S - sum -> n×d (cheaper than ×)|
³ - m
ḃ - n×d to bijective base m
Ṛ - reverse |
/ - reduce by: |
ḷ - left argument (cheaper than Ṫ)|
R1¦ - change the leading m to [1..m]
z7 - transpose with filler 7 (cheaper than Z)|
Ðḟ - discard those for which:
Ɗ - last three links as a monad:
Ɗ - last three links as a monad:
Ɗ - last three links as a monad:
M - maximal (1-indexed) indices
Ṗ - remove the last one
’ - decrement
P - product
Ḅ - from binary [cheap no-op to help use Ɗ]
E - all equal?
o - logical OR
Q€ - deduplicate each
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~139~~ [125](https://tio.run/##AV0Aov9vc2FiaWX//8W@xIZJU2s9Cs61zpRTT13CqScrw70nPcKuT0os//9MzrXCuM6UUsKsSSrCuUzCpNC4w6Z7w5nDqXPDqFLQvcWhUsOZXS7CoVdd4oKs0L3KkmfiiaA) (33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
Lε¸ΔR¬I*¹L¤иæ{ÙésèRнšRÙ].¡W]€нʒg≠
```
Inputs in the order \$m,n\$. Outputs as a list of lists.
[Try it online](https://tio.run/##AUQAu/9vc2FiaWX//0zOtcK4zpRSwqxJKsKvwrnGksK5TE7Do8KrfXPDqFLQvcWhUsOZXS7CoVdd4oKs0L3KkmfiiaD//zkKNA) (with `¹L¹иæ{Ùé` replaced with `¯¹ƒ¹LNã«}` so it won't timeout).
The codegolfed program would be **~~31~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**:
```
Lε¸Δ¤I*¹L¹иæêésèθªÙ].¡ß}€нʒg≠
```
[Try it online](https://tio.run/##AUIAvf9vc2FiaWX//0zOtcK4zpTCpEkqwq/CucaSwrlMTsOjwqt9c8OozrjCqsOZXS7CocOffeKCrNC9ypJn4omg//85CjQ) (with `¹L¹иæê` replaced with `¯¹ƒ¹LNã«}` so it won't timeout).
The bytes for this codegolfed program (in the [05AB1E codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) would result in a score of ~~`154`~~ `145`:
```
[76, 6, 184, 17, 164, 73, 42, 185, 76, 185, 12, 230, 234, 233, 115, 232, 9, 170, 217, 93, 46, 161, 223, 125, 128, 14, 1, 103, 22]
4+6+4+8+2+1+6+5+4+5+3+5+9+8+7+7+9+8+1+3+1+8+7+8+2+5+1+4+4=145
```
[Try it online.](https://tio.run/##AVoApf9vc2FiaWX//8W@xIZJU2s9Cs61zpRTT13CqScrw70nPcKuT0os//9MzrXCuM6UwqRJKsK5TMK50LjDpsOqw6lzw6jOuMKqw5ldLsKhw5994oKs0L3KkmfiiaA)
To improve this score, the following modifications have been made:
* -3 score: `θ` [pop and push last item] ([9] → 9) to `Rн` [reverse; pop and push first item] ([82,14] → 1+5=6)
* -1 score: `ß` [pop and push minimum] ([223] → 7) to `W` [push minimum without popping] ([87] → 6)
* -6 score: `¤ ... ª` [push last item without popping & append to list] ([164,170] → 2+8=10) to `R¬ ... šR` [reverse; push first item without popping & prepend to list; reverse] ([82,172,154,82] → 1+1+1+1=4)
* -5 score: `}` [close loop] ([125] → 8) to `]` [close all loops] ([93] → 3)
* -2 score: `ê` [sorted uniquify] ([234] → 9) to `{Ù` [sort; uniquify] ([123,217] → 6+1=7)
* -3 score: second `¹` [push first input] ([185] → 5) to `¤` [push last item without popping] ([164] → 2)
**Explanation (of the codegolfed program):**
For a language that's (almost) literally called [`Base`](https://tio.run/##ASUA2v9vc2FiaWX//0jFvmouxaHCqOKAnisvwqvDhdCySv//MDVBQjFF) (`05AB1E` converted from hexadecimal to a base-10 integer, and then to the [default base-64](https://en.wikipedia.org/wiki/Base64#Base64_table_from_RFC_4648) string), the lack of [bijective base](https://en.wikipedia.org/wiki/Bijective_numeration#Properties_of_bijective_base-k_numerals) builtins is pretty annoying.. This is now done manually (with portion `¹L¹иæêésè` - which will timeout for \$m\geq4\$).
```
L # Push a list in the range [1, (implicit) input `m`]
ε # Map each integer to:
¸ # Wrap it in a list
Δ # Continue looping until the list no longer changes:
¤ # Push the last item of the list (without popping)
I* # Multiply it by the second input `n`
¹L¹иæêésè # Convert it to bijective base-`m`:
¹L # Push a list in the range [1, input `m`]
¹и # Repeat it `m` amount of times
æ # Get the powerset of this list
ê # Uniquify and sort this list of lists
é # (Stable) sort again by length
s # Swap so the `i*n` is at the top
è # Index it into this list
θ # Pop and only leave the last value
ª # Append this to the list
Ù # Uniquify this list
] # Close both the inner fixed-point loop and map
.¡ } # Group the resulting lists by:
ß # Their minimum
€ # For each group:
н # Only leave the first list
ʒ # Filter the remaining lists by:
g # Where the length of the list
≠ # Is NOT 1
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](http://pypy.org/), score = 937 (228 bytes)
```
I=int(input())
R=int(input())
D=lambda v:v and~-v%I+1
J=lambda v:[D(R*m)for m in v]
d=list(range(1,I+1))
m=J(d)
v=[]
while m not in v:v+=[m];m=J(m)
exit([frozenset(m)for m in zip(*([d]+v))if max(m)in m[1:]!=m[0]==max(m)>min(m)])
```
[Try it online!](https://tio.run/##VYwxT8MwFIR3/wozVHpuqERgItVj6tKOXS0PRnbok/JerNQ1TQf@ejAwANPp7ru7NOfTKE@bNKd5WfZIkoEkXTIYo47/7Q4Hz6/B69IV7SV8bMpq37Tq8JvbHRzXbPpx0qxJdHEq4EDnDJOXtwjtfR3UK8YDBKMKWqfeTzTEWpcxf0@60qBlt/3qsFHxShlsP423KOeY4c/7jRKswQbXFGOo1@yvFVfAtu3cHbJ9cIg/6QuTVHFmWZ7V4yc "Python 3 (PyPy) – Try It Online")
Bytes:
```
73 61 105 110 116 40 105 110 112 117 116 40 41 41 10 10 82 61 105 110 116 40 105 110 112 117 116 40 41 41 10 10 68 61 108 97 109 98 100 97 32 118 58 118 32 97 110 100 126 45 118 37 73 43 49 10 10 74 61 108 97 109 98 100 97 32 118 58 91 68 40 82 42 109 41 102 111 114 32 109 32 105 110 32 118 93 10 10 100 61 108 105 115 116 40 114 97 110 103 101 40 49 44 73 43 49 41 41 10 10 109 61 74 40 100 41 10 10 118 61 91 93 10 10 119 104 105 108 101 32 109 32 110 111 116 32 105 110 32 118 58 118 43 61 91 109 93 59 109 61 74 40 109 41 10 10 101 120 105 116 40 91 102 114 111 122 101 110 115 101 116 40 109 41 102 111 114 32 109 32 105 110 32 122 105 112 40 42 40 91 100 93 43 118 41 41 105 102 32 109 97 120 40 109 41 105 110 32 109 91 49 58 93 33 61 109 91 48 93 61 61 109 97 120 40 109 41 62 109 105 110 40 109 41 93 41
```
Digit root of those bytes:
```
1 + 7 + 6 + 2 + 8 + 4 + 6 + 2 + 4 + 9 + 8 + 4 + 5 + 5 + 1 + 1 + 1 + 7 + 6 + 2 + 8 + 4 + 6 + 2 + 4 + 9 + 8 + 4 + 5 + 5 + 1 + 1 + 5 + 7 + 9 + 7 + 1 + 8 + 1 + 7 + 5 + 1 + 4 + 1 + 5 + 7 + 2 + 1 + 9 + 9 + 1 + 1 + 1 + 7 + 4 + 1 + 1 + 2 + 7 + 9 + 7 + 1 + 8 + 1 + 7 + 5 + 1 + 4 + 1 + 5 + 4 + 1 + 6 + 1 + 5 + 3 + 3 + 6 + 5 + 1 + 5 + 6 + 2 + 5 + 1 + 3 + 1 + 1 + 1 + 7 + 9 + 6 + 7 + 8 + 4 + 6 + 7 + 2 + 4 + 2 + 4 + 4 + 8 + 1 + 7 + 4 + 5 + 5 + 1 + 1 + 1 + 7 + 2 + 4 + 1 + 5 + 1 + 1 + 1 + 7 + 1 + 3 + 1 + 1 + 2 + 5 + 6 + 9 + 2 + 5 + 1 + 5 + 2 + 3 + 8 + 5 + 6 + 2 + 5 + 1 + 4 + 1 + 7 + 7 + 1 + 1 + 3 + 5 + 1 + 7 + 2 + 4 + 1 + 5 + 1 + 1 + 2 + 3 + 6 + 8 + 4 + 1 + 3 + 6 + 3 + 5 + 2 + 2 + 7 + 2 + 8 + 4 + 1 + 5 + 3 + 3 + 6 + 5 + 1 + 5 + 6 + 2 + 5 + 5 + 6 + 4 + 4 + 6 + 4 + 1 + 1 + 3 + 7 + 1 + 5 + 5 + 6 + 3 + 5 + 1 + 7 + 3 + 4 + 1 + 5 + 6 + 2 + 5 + 1 + 1 + 4 + 4 + 3 + 6 + 7 + 1 + 1 + 3 + 3 + 7 + 7 + 1 + 7 + 3 + 4 + 1 + 5 + 8 + 1 + 6 + 2 + 4 + 1 + 5 + 3 + 5 = 937
```
] |
[Question]
[
[Robbers thread](https://codegolf.stackexchange.com/questions/243504/hello-shue-robbers)
In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, your task is to write a program `h` that outputs "Hello Shue!". Next, you have to choose a string `i` and also write a [Shue](https://codegolf.stackexchange.com/questions/242897/golf-the-prime-numbers-in-shue) program `p`, so that `p(i)=h`. Your score is `len(p)+len(i)`. Your answer will contain the language of `h`, `i` and your score (please write the score as `len(p)+len(i)=score`). Robbers will try to find `p`. Note that any working `p`, that is as long as your `p` or shorter means that your answer is defeated, even if it wasn't the solution you intended. The undefeated cop answer with the smallest score wins (per language).
To understand this challenge let's look at an example submission in Python:
>
> Python 3, score 47+22=69
>
>
> `(rint?KH++lloooShu++K'`
>
>
>
Not included in the post is the following Shue program (`p`):
```
print("Hello Shue")
(=p
?=(
K="
++=e
ooo=o
'=)
```
Note that there is a trailing space after the `o`
The first line is the program `h`. Next are a series of replacement rules. Let's see how they work.
With the input `(rint?KH++lloooShu++K'` (`i`) we can get to `h` like so
```
(rint?KH++lloooShu++K'
(rint(KH++lloooShu++K' - ?=(
print(KH++lloooShu++K' - (=p
print("H++lloooShu++K' - K="
print("H++lloooShu++K) - '=)
print("H++lloooShu++") - K="
print("H++llo Shu++") - ooo=o
print("Hello Shu++") - ++=e
print("Hello Shue") - ++=e
```
If your code `h` contains equals signs, backslashes or newlines, escape them with `\=`,`\\` and `\n` respectively in the Shue program `p` (but not in the input `i`). If your code contains nulls or non-unicode bytes, don't worry, Shue is byte-oriented.
[Answer]
# Vyxal, score 28+19=47
```
\a:ȯ≤∨I:C‹C\Hp5‛ SṀṅ
```
[Try input online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXGE6yK/iiaTiiKhJOkPigLlDXFxIcDXigJsgU+G5gOG5hSIsIiIsIiJd)
I don't know if it'll be an easy crack, or if I forgot something.
[Answer]
# Python 3, score 163+563=726, Safe
>
> In this cops-and-robbers challenge, your task is to write a program h that outputs "Hello Shue!". Next, you have to choose a string i and also write a Shue program p, so that p(i)=h. Your score is len(p)+len(i). Your answer will contain the language of h, i and your score (please write the score as len(p)+len(i)=score). Robbers will try to find p. Note that any working p, that is as long as your p or shorter means that your answer is defeated, even if it wasn't the solution you intended. The undefeated cop answer with the smallest score wins (per language).
>
>
>
Not that fun though
```
print("Hello Shue")
I=
n=
=
t=
h=
i=
s=
c=
o=
-=
a=
d=
b=
e=
r=
l=
g=
,=
y=
u=
k=
w=
p=
m=
.=
N=
x=
v=
S=
(=
)=
\==
Y=
+=
f=
R=
'=
T=
=nt(
```
actually 140 bytes
] |
[Question]
[
### Background
This is a follow up question to the question: [Will the Hydra finally die?](https://codegolf.stackexchange.com/questions/230778/will-the-hydra-finally-die/230992#230992)
As before a dangerous A Medusa have released a dangerous Hydra which is revived unless the exact number of heads it have is removed. The knights can remove a certain number of heads with each type of attack, and each attack causes a specific amount of heads to regrow. This time the knights are more impatient and having seen your previous abilities want you to\*\* write a program or function that **returns a list of hits which will leave the hydra 1 hit from death**
Note that this is fundamentally different from [Become the Hydra Slayer](https://codegolf.stackexchange.com/questions/137980/become-the-hydra-slayer). in 2 aspects. 1: We are not asking for the optimal solution 2: each attack causes a *different* number of heads to grow back. this radically changes the approach needed.
*For example:*
```
input: heads = 2,
attacks = [1, 25, 62, 67],
growths = [15, 15, 34, 25],
output: [5, 1, 0, 0]
```
*Explanation:* The Hydra has 10 heads to start with, we have 4 different `attacks` and for each attack, `growth` gives us the number of heads that grows back. `hits` gives us the number of times each attack is applied. So the number of heads the Hydra has after each attack is
```
2 -> 16 -> 30 -> 44 -> 58 -> 72 -> 62
```
Since `62` is a valid attack value (It lies in the attack list), we return `True` since the Hydra will die on the next attack (be left with 0 heads). Note that the order for when the attacks are done is irrelevant.
```
2 -> 16 -> 6 -> 20 -> 34 -> 48 -> 62
```
---
### Input
Input should contain `heads` (an integer), `attacks` (a list of how many heads can be removed), `regrowths` (how many heads grow back per attack)
You may take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). This includes, but is not limited to
* A list of tuples `(1, 15, 5), (25, 15, 1), (62, 34, 0), (67, 25, 0)`
* Lists `2, [1, 25, 62, 67], [15, 15, 34, 25], [5, 1, 0, 0]`
* Reading values from STDIN `1 15 1 15 1 15 1 15 1 15 25 15`
* A file of values
---
### Output
* An array, or some way to easily indicate which hits the knights are to take. Example: `5 1 0 0`
**Note 1** Say that your input is `attacks = [1, 25, 62, 67]` and the hydra has 25 heads left, then you **cannot** output the answer as `[1,0,0,0]`, `[0,0,0,1]` etc. **Your output and input must be sorted similarly**. Otherwise it will be very confusing for the Knights.
**Note 2:** Your program can *never* leave the Hydra with a negative number of heads. Meaning if the Hydra has 15 heads, an attack removes 17 heads and regrows 38. You may not perform this attack.
* You may assume that any input is valid. E.g every input will not overkill the Hydra and either result in a number of heads that is an attack value, or not.
---
### Assumptions
* There will always be as many attacks as regrowths
* Every attack value will always correspond to one regrowth value which never changes. these are not required to be unique
* Every input value will be a non-negative integer
* You may assume that there always exists a solution (note that this is not neccecarily the case, but for our test data it is)
* How you handle non valid inputs is up to you
---
### Scoring
* This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") you will be scored as follows:
the total sum of hits your code produces from the test data + length of answer in bytes
* Note that how you input and parse the test data is not part of your code length. Your code should, as stated above simply take in some a headcount, attacks, regrowth's and return a list/representation of how many hits each attack has to be performed to leave the hydra *exactly* 1 hit from death.
**Lowest score wins!**
---
### Test data
```
attacks = [1, 25, 62, 67],
growths = [15, 15, 34, 25],
```
**use every integer from `1` to `200` as the number of heads.** An sample from the first 100 can be found below. Again your program does not have to return these values, it is merely an example of how the scoring would work. As seen below the total sum for each of these hits are `535` meaning my score would be `535 + length of code in bytes` (If we wanted to use 1-100 instead of 1-200 as the number of heads of course)
```
1 [0, 0, 0, 0]
2 [5, 1, 0, 0]
3 [3, 2, 0, 0]
4 [7, 4, 0, 0]
5 [5, 5, 0, 0]
6 [4, 0, 0, 0]
7 [2, 1, 0, 0]
8 [6, 3, 0, 0]
9 [4, 4, 0, 0]
10 [8, 6, 0, 0]
11 [1, 0, 0, 0]
12 [5, 2, 0, 0]
13 [3, 3, 0, 0]
14 [7, 5, 0, 0]
15 [5, 6, 0, 0]
16 [4, 1, 0, 0]
17 [2, 2, 0, 0]
18 [6, 4, 0, 0]
19 [4, 5, 0, 0]
20 [3, 0, 0, 0]
21 [1, 1, 0, 0]
22 [5, 3, 0, 0]
23 [3, 4, 0, 0]
24 [7, 6, 0, 0]
25 [0, 0, 0, 0]
26 [4, 2, 0, 0]
27 [2, 3, 0, 0]
28 [6, 5, 0, 0]
29 [4, 6, 0, 0]
30 [3, 1, 0, 0]
31 [1, 2, 0, 0]
32 [5, 4, 0, 0]
33 [3, 5, 0, 0]
34 [2, 0, 0, 0]
35 [0, 1, 0, 0]
36 [4, 3, 0, 0]
37 [2, 4, 0, 0]
38 [6, 6, 0, 0]
39 [2, 0, 0, 0]
40 [3, 2, 0, 0]
41 [1, 3, 0, 0]
42 [5, 5, 0, 0]
43 [3, 6, 0, 0]
44 [2, 1, 0, 0]
45 [0, 2, 0, 0]
46 [4, 4, 0, 0]
47 [2, 5, 0, 0]
48 [1, 0, 0, 0]
49 [2, 1, 0, 0]
50 [3, 3, 0, 0]
51 [1, 4, 0, 0]
52 [5, 6, 0, 0]
53 [1, 0, 0, 0]
54 [2, 2, 0, 0]
55 [0, 3, 0, 0]
56 [4, 5, 0, 0]
57 [2, 6, 0, 0]
58 [1, 1, 0, 0]
59 [2, 2, 0, 0]
60 [3, 4, 0, 0]
61 [1, 5, 0, 0]
62 [0, 0, 0, 0]
63 [1, 1, 0, 0]
64 [2, 3, 0, 0]
65 [0, 4, 0, 0]
66 [4, 6, 0, 0]
67 [0, 0, 0, 0]
68 [1, 2, 0, 0]
69 [2, 3, 0, 0]
70 [3, 5, 0, 0]
71 [1, 6, 0, 0]
72 [0, 1, 0, 0]
73 [1, 2, 0, 0]
74 [2, 4, 0, 0]
75 [0, 5, 0, 0]
76 [1, 0, 1, 0]
77 [0, 1, 0, 0]
78 [1, 3, 0, 0]
79 [2, 4, 0, 0]
80 [3, 6, 0, 0]
81 [1, 0, 1, 0]
82 [0, 2, 0, 0]
83 [1, 3, 0, 0]
84 [2, 5, 0, 0]
85 [0, 6, 0, 0]
86 [1, 1, 1, 0]
87 [0, 2, 0, 0]
88 [1, 4, 0, 0]
89 [2, 5, 0, 0]
90 [0, 0, 1, 0]
91 [1, 1, 1, 0]
92 [0, 3, 0, 0]
93 [1, 4, 0, 0]
94 [2, 6, 0, 0]
95 [0, 0, 1, 0]
96 [1, 2, 1, 0]
97 [0, 3, 0, 0]
98 [1, 5, 0, 0]
99 [2, 6, 0, 0]
100 [0, 1, 1, 0]
535
```
[Answer]
# [Python 3](https://docs.python.org/3/), 944 hits + 178 bytes = 1122
```
def f(t,s):
q=[[[0]*len(s),t]];f={0}
for p,t in q:
if any(x==t for x,_ in s):return p
for i,(k,y)in enumerate(s):n=t-k+y;q+=[[p[:i]+[p[i]+1]+p[i+1:],n]]*(n not in f);f|={n}
```
[Try it online!](https://tio.run/##LVHBbqMwED3jrxghRbKDW0G6aaVEHPa@0l5yo2jlLnaxSIxjD9qw3X57dky52HjezJv3Hn7GfnRP93unDRiOMooDy6510zRluz1rx6OQ2LZHU3@UnywzYwAvEayDKzVm1oByM7/VNULCbvJXwoglaJyCA09NCbCSD3IWhGk3XXRQqIn64Gp8GIr5eC1opW8Oti3oorNqC7qL6tBK17Zb7sCNy1ojjuZf/eE@7wPUVEBunZ@QC8EiFZqWsT@9PWs4hUmTRAxzEhoflffadfxsI/KL8jSGEtbZx@jPNnEQS6Zvv7XHNPQWtBoYO/08ff9B3CVji5UkIyj3rnklYYACqhSapw7DrSTz9AhJWb6Jr7iJOWwgAT6xJwYlgdKAWSSmv9Zzn6aWPKGogc/wAIOALSiWqRh1wK@UoSbHa86wBi0hN4r8doAjrKFjr6Gfu6BgdPRl6d@E8QKdVtjnLPvyQ4vidOFeMLaqXeqvmJOjiIEvTyHuu7JkFVR7ttun83kHT9/Y8wvs9v8B "Python 3 – Try It Online")
I can verify that 944 is the optimal solution; this is guaranteed to be optimal.
`;f={0}`, `n=t-k+y`, `*(n nt in f)`, and `f|={n}` are not necessary for golfing but like with ovs's solution, I have them here just so the solution will run within seconds rather than years.
Trivial BFS solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, 944 hits + 29 bytes = 973
The `²g∍` part is technically not necessary, but I wanted this to actually finish in seconds rather than years. I think this should return optimal solutions.
```
[NÅœε²gÅ0«²g∍œε³²-*O¹+²såiy,q
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/2u9w69HJ57Ye2pR@uNXg0Gog/aijFyyy@dAmXS3/Qzu1D20qPrw0s1Kn8P9/QwOuaEMdBSNTHQUzIyA2jwXygRwQNjYBScT@19XNy9fNSayqBAA "05AB1E – Try It Online")
```
# Inputs: ¹ - initial number of heads
# ² - list of attacks
# ³ - list of regrowths
[ # for N in 0, 1, 2, ...
NŜ # push integer partitions of N
ε # for each partition:
²gÅ0« # append as many 0's as there are attacks
²g∍ # take as many integers as there are attacks from the front
œ # take the permutations of this subset
ε # for each permutation y of a subset of the integer partition of N
³²- # regrowths - attacks element-wise
* # multiply with y element-wise
O # take the sum of this
¹+ # and add the initial number of heads
²såi # if this is in the list of attacks:
y,q # print y and exit the program
```
Here is my output for the 200 cases, generated with [this test suite](https://tio.run/##bVC7TsMwFN39FReTqgmNmzTlIaG2G4xkYSsdkiYlllq7xMlQHmMlFia@gYktiIE1ESsfwY@E6zTqxHB1fI7vPb7HYaCSuj48cEIunBAJieeJBCagO72qtt@vP59lcVtt3fId8ff5pVE@yoId@eVXryxU9cY39l0XJjCXUdwPwnhv4aOo8lWjETyMXUIWMgWRr8I4BS7gYdDve677RCJJZJ6NDdOR68yRKgh53MLeFxgTki2D@w3AaAQX/iUxdlZkOrDBO7Hh1MM6myFHomt4rC9mRDdbZJ1ykS2AdoYRsAl01I2g0HoANXADShKeKdyjyaAVeIR/dmpjWU0swzQRenrSsjCKwLh6fvcR9FpmwfIc8CXsQtB9tK7/AA) (finishes in 70 seconds locally):
```
1 -> [0, 0, 0, 0]
2 -> [5, 1, 0, 0]
3 -> [2, 3, 0, 0]
4 -> [7, 4, 0, 0]
5 -> [4, 6, 0, 0]
6 -> [4, 0, 0, 0]
7 -> [1, 2, 0, 0]
8 -> [6, 3, 0, 0]
9 -> [3, 5, 0, 0]
10 -> [8, 6, 0, 0]
11 -> [1, 0, 0, 0]
12 -> [5, 2, 0, 0]
13 -> [2, 4, 0, 0]
14 -> [7, 5, 0, 0]
15 -> [1, 0, 1, 0]
16 -> [4, 1, 0, 0]
17 -> [1, 3, 0, 0]
18 -> [6, 4, 0, 0]
19 -> [3, 6, 0, 0]
20 -> [3, 0, 0, 0]
21 -> [1, 1, 0, 0]
22 -> [5, 3, 0, 0]
23 -> [2, 5, 0, 0]
24 -> [7, 6, 0, 0]
25 -> [0, 0, 0, 0]
26 -> [4, 2, 0, 0]
27 -> [1, 4, 0, 0]
28 -> [6, 5, 0, 0]
29 -> [0, 0, 1, 0]
30 -> [3, 1, 0, 0]
31 -> [1, 2, 0, 0]
32 -> [5, 4, 0, 0]
33 -> [2, 6, 0, 0]
34 -> [2, 0, 0, 0]
35 -> [0, 1, 0, 0]
36 -> [4, 3, 0, 0]
37 -> [1, 5, 0, 0]
38 -> [6, 6, 0, 0]
39 -> [1, 0, 1, 0]
40 -> [3, 2, 0, 0]
41 -> [1, 3, 0, 0]
42 -> [5, 5, 0, 0]
43 -> [0, 0, 0, 1]
44 -> [2, 1, 0, 0]
45 -> [0, 2, 0, 0]
46 -> [4, 4, 0, 0]
47 -> [1, 6, 0, 0]
48 -> [1, 0, 0, 0]
49 -> [1, 1, 1, 0]
50 -> [3, 3, 0, 0]
51 -> [1, 4, 0, 0]
52 -> [5, 6, 0, 0]
53 -> [1, 0, 0, 0]
54 -> [2, 2, 0, 0]
55 -> [0, 3, 0, 0]
56 -> [4, 5, 0, 0]
57 -> [0, 0, 2, 0]
58 -> [1, 1, 0, 0]
59 -> [1, 2, 1, 0]
60 -> [3, 4, 0, 0]
61 -> [1, 5, 0, 0]
62 -> [0, 0, 0, 0]
63 -> [1, 1, 0, 0]
64 -> [2, 3, 0, 0]
65 -> [0, 4, 0, 0]
66 -> [4, 6, 0, 0]
67 -> [0, 0, 0, 0]
68 -> [1, 2, 0, 0]
69 -> [1, 3, 1, 0]
70 -> [3, 5, 0, 0]
71 -> [0, 0, 1, 1]
72 -> [0, 1, 0, 0]
73 -> [1, 2, 0, 0]
74 -> [2, 4, 0, 0]
75 -> [0, 5, 0, 0]
76 -> [1, 0, 1, 0]
77 -> [0, 1, 0, 0]
78 -> [1, 3, 0, 0]
79 -> [1, 4, 1, 0]
80 -> [3, 6, 0, 0]
81 -> [1, 0, 1, 0]
82 -> [0, 2, 0, 0]
83 -> [1, 3, 0, 0]
84 -> [2, 5, 0, 0]
85 -> [0, 0, 0, 2]
86 -> [1, 1, 1, 0]
87 -> [0, 2, 0, 0]
88 -> [1, 4, 0, 0]
89 -> [1, 5, 1, 0]
90 -> [0, 0, 1, 0]
91 -> [1, 1, 1, 0]
92 -> [0, 3, 0, 0]
93 -> [1, 4, 0, 0]
94 -> [2, 6, 0, 0]
95 -> [0, 0, 1, 0]
96 -> [1, 2, 1, 0]
97 -> [0, 3, 0, 0]
98 -> [1, 5, 0, 0]
99 -> [0, 0, 2, 1]
100 -> [0, 1, 1, 0]
101 -> [1, 2, 1, 0]
102 -> [0, 4, 0, 0]
103 -> [1, 5, 0, 0]
104 -> [0, 0, 0, 1]
105 -> [0, 1, 1, 0]
106 -> [1, 3, 1, 0]
107 -> [0, 4, 0, 0]
108 -> [1, 6, 0, 0]
109 -> [0, 0, 0, 1]
110 -> [0, 2, 1, 0]
111 -> [1, 3, 1, 0]
112 -> [0, 5, 0, 0]
113 -> [0, 0, 1, 2]
114 -> [0, 1, 0, 1]
115 -> [0, 2, 1, 0]
116 -> [1, 4, 1, 0]
117 -> [0, 5, 0, 0]
118 -> [0, 0, 2, 0]
119 -> [0, 1, 0, 1]
120 -> [0, 3, 1, 0]
121 -> [1, 4, 1, 0]
122 -> [0, 6, 0, 0]
123 -> [0, 0, 2, 0]
124 -> [0, 2, 0, 1]
125 -> [0, 3, 1, 0]
126 -> [1, 5, 1, 0]
127 -> [0, 0, 0, 3]
128 -> [0, 1, 2, 0]
129 -> [0, 2, 0, 1]
130 -> [0, 4, 1, 0]
131 -> [1, 5, 1, 0]
132 -> [0, 0, 1, 1]
133 -> [0, 1, 2, 0]
134 -> [0, 3, 0, 1]
135 -> [0, 4, 1, 0]
136 -> [1, 6, 1, 0]
137 -> [0, 0, 1, 1]
138 -> [0, 2, 2, 0]
139 -> [0, 3, 0, 1]
140 -> [0, 5, 1, 0]
141 -> [0, 0, 2, 2]
142 -> [0, 1, 1, 1]
143 -> [0, 2, 2, 0]
144 -> [0, 4, 0, 1]
145 -> [0, 5, 1, 0]
146 -> [0, 0, 0, 2]
147 -> [0, 1, 1, 1]
148 -> [0, 3, 2, 0]
149 -> [0, 4, 0, 1]
150 -> [0, 6, 1, 0]
151 -> [0, 0, 0, 2]
152 -> [0, 2, 1, 1]
153 -> [0, 3, 2, 0]
154 -> [0, 5, 0, 1]
155 -> [0, 0, 1, 3]
156 -> [0, 1, 0, 2]
157 -> [0, 2, 1, 1]
158 -> [0, 4, 2, 0]
159 -> [0, 5, 0, 1]
160 -> [0, 0, 2, 1]
161 -> [0, 1, 0, 2]
162 -> [0, 3, 1, 1]
163 -> [0, 4, 2, 0]
164 -> [0, 6, 0, 1]
165 -> [0, 0, 2, 1]
166 -> [0, 2, 0, 2]
167 -> [0, 3, 1, 1]
168 -> [0, 5, 2, 0]
169 -> [0, 0, 0, 4]
170 -> [0, 1, 2, 1]
171 -> [0, 2, 0, 2]
172 -> [0, 4, 1, 1]
173 -> [0, 5, 2, 0]
174 -> [0, 0, 1, 2]
175 -> [0, 1, 2, 1]
176 -> [0, 3, 0, 2]
177 -> [0, 4, 1, 1]
178 -> [0, 6, 2, 0]
179 -> [0, 0, 1, 2]
180 -> [0, 2, 2, 1]
181 -> [0, 3, 0, 2]
182 -> [0, 5, 1, 1]
183 -> [0, 0, 2, 3]
184 -> [0, 1, 1, 2]
185 -> [0, 2, 2, 1]
186 -> [0, 4, 0, 2]
187 -> [0, 5, 1, 1]
188 -> [0, 0, 0, 3]
189 -> [0, 1, 1, 2]
190 -> [0, 3, 2, 1]
191 -> [0, 4, 0, 2]
192 -> [0, 6, 1, 1]
193 -> [0, 0, 0, 3]
194 -> [0, 2, 1, 2]
195 -> [0, 3, 2, 1]
196 -> [0, 5, 0, 2]
197 -> [0, 0, 1, 4]
198 -> [0, 1, 0, 3]
199 -> [0, 2, 1, 2]
200 -> [0, 4, 2, 1]
Total: 944 hits
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes + 944 attacks = 970 score
```
_Ḣ0œċNƭ€Se¥Ƈ/©¥@1#ṛ®ƲḢċⱮḢƲ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@4Y5FBkcnH@n2O7b2UdOa4NRDS4@16x9aeWipg6Hyw52zD607tgmo5Ej3o43rgPSxTf@tD7dzWT9qmKOga6fwqGGu9eHlDg937ju0lMvIwODwcqAZD3dserhzlQqQFeYWfGyTtUokUHVIfklijhVYw///0YY6CkamOgpmRkBsHqujEG0I5IGwsQlIJhYA "Jelly – Try It Online")
A monadic link taking `[attack], [regrowth], heads` as its argument and returning a list of counts of attacks.
] |
[Question]
[
What tips do you have for code-golfing in the [V lang](https://vlang.io/)? I have been trying to find ways to shorten codegolfs on there but can't find any resources on it. Do you guys have any?
Please suggest tips that are at least somewhat specific to the V programming language (e.g. "remove comments" isn't helpful).
Please post one tip per answer.
[Answer]
When making an instance of a struct, you can omit argument names if they're in the right order.
```
Person{age:-1
name:"bar"}
Person{-1"bar"}
```
If the type is already known, you can omit `Person`, but you'll have to explicitly give the field names.
When making a change to an object, you can copy it by placing `...x` at the start (where `x` is the object to copy from).
[Answer]
# Remove unnecessary whitespace
Take the following code:
```
mut x:="foo"
println(x)
x+="bar"
println(x)
```
You can rewrite the code like so:
```
mut x:="foo"println(x)x+="bar"println(x)
```
This is still perfectly valid syntax. In general, any two statements can be combined if they are separated by a symbol (though this is not always the case).
] |
[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/223372/edit).
Closed 2 years ago.
[Improve this question](/posts/223372/edit)
**Program**
Write a program to display repeating terms of a given sentence.
**Explanation**
The program must output the repeating terms of two or more letters from the given input (input is a sentence separated by spaces without any punctuation except the full-stop indicating the end.) Repeated terms may not span across or include a space. For example, if input is the sentence "I **am** **an** **am**eture **ma**the**ma**gici**an**" the output must be am, ma, an. (note that "em" is not a valid output as it is separated by space).
Repeated terms may overlap with each other. For example if the input is "ababa", the output should include "aba", even though the two instances of it overlap.
```
ababa
aba
aba
```
**Example**
Input:
>
> International competitions are better than intercollege ones.
>
>
>
Output:
>
> Inter, ti, er, tion, io, on, ion, tio, co, on, .......etc
> (t, l must not be included as they are 1 letter.) (Upper lower Cases do not matter)
>
>
>
**Test cases**
```
aabcde cdec -> cde, cd, de
aab aacab -> aa, ab
aaa aabcaaa ababa -> aaa, aa, ab, aba, ba
abababa-> ab, aba, abab, ababa, ba, bab, baba
```
**Winning Criterion**
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
[Answer]
# JavaScript (ES10), 99 bytes
```
s=>new Set([...s].map((q,i,a,j=i)=>a.map(_=>s.lastIndexOf(q+=s[++i])>j&!/ /.test(q)?q:[])).flat(2))
```
[Try it online!](https://tio.run/##ZY0/C8IwEMV3P0XsIDkaU3AUUmcnB8dS5CVNpaX2jwnqt69NHBx6x7s7Hu/HtXjBmWcz@n0/VHau1exU3ts3u1rPCymlK@UDI@eTaAREqxpSOaJ1U7mTHZw/95X9XGo@pcoVadqUlLe7bcYy6a3zfKLTdCxKIll38PxANJuhd0NnZTfcec0TQJvKskUmIWK/yrJgiGUIVtnNGmGAgf4DEQEEg16nwcKTuPXSgYrpEI9I0HJozF8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
```
lambda s:{''.join(y) for x in range(2,len(s))for y in permutations(s,x)if s.count(''.join(y))>1}
from itertools import*
```
[Try it online!](https://tio.run/##RczBCsIwDIDhu08RdlkrY6DeBH0SL9lsNbImJc1gQ3z26k5eP37@vNpT@FTj5VYnTMMdoZzfbdu/hNitHqIoLEAMivwI7thNgV3xfvN18xw0zYZGwsWVbvEUofSjzGzu//HXw2cXVRKQBTWRqQClLGr7mpV@bXQN4gCIIw6N9/UL "Python 3 – Try It Online")
Extremely slow... Works by calculating permutations
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ã køS fÅü lÉ y
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=4yBr%2bFMgZsX8IGzJIHk&input=ImFhYSBhYWJjYWFhIGFiYWJhIgotUQ)
* saved 4 thanks to @Shaggy
```
ã - substrings
køS - remove if contains space
fÅ - take longer than 1
ü - sort and group
lÊ - take groups longer than 1
y - transpose
-g flag to return first element
```
] |
[Question]
[
**Challenge**
Given a 2D array, find the length and direction of all the longest consecutive characters.
* If there are ties, output *every* possible winning combination in any order, (winners can overlap with other winners)
* Zero "0" is a special padding character which cannot be a winner.
* Code golf rules apply, shortest code wins.
**Output:** n,m,d
(Where *n* is the identified character of length *m* in *d* direction)
Valid characters for *d*: `/|\-.` *See below examples to interpret meaning.*
**Input:** The 2D array input should be in either of the following format, (your preference):
Option 1:
```
123
456
789
```
Option 2\*:
```
[["123"],["456"],["789"]]
```
\*or any combination of "{[()]}" characters can be used, with whitespace characters ignored outside of quotes. Quotes can be single or double. The array must read left-to-right, top-to-bottom.
**Assumptions**
* The shape of the array will always be rectangular or square
* There will always be at least one non-zero character
* Array characters will only be alphanumeric
**Examples**
1.
```
0000000
0111100
0000000
```
>
> 1,4,-
>
>
>
2.
```
00000000
aaaa0000
00bbbbb0
```
>
> b,5,-
>
>
>
3.
```
0y00x000
aayxaaaz
00xy000z
0x00y00z
x0000y0z
```
>
> x,5,/
>
>
> y,5,\
>
>
>
\*(in any order)
4.
```
1111
1111
1111
```
>
> 1,4,-
>
>
> 1,4,-
>
>
> 1,4,-
>
>
>
5.
```
ccc
cwc
ccc
```
>
> c,3,-
>
>
> c,3,-
>
>
> c,3,|
>
>
> c,3,|
>
>
>
\*(in any order)
6.
```
9
```
>
> 9,1,.
>
>
>
7.
```
ab
cd
```
>
> a,1,.
>
>
> b,1,.
>
>
> c,1,.
>
>
> d,1,.
>
>
>
\*(in any order)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~52~~ 54 bytes
```
,UŒD€;,Z$ṣ€€”0ŒrẎ€⁺;€"“\/-|”Ẏ2ị$ÐṀ¹F}ḟ”0;€1,”.ʋؽœị’Ɗ?
```
[Try it online!](https://tio.run/##y0rNyan8/18n9Ogkl0dNa6x1olQe7lwMZIFQw1yDo5OKHu7qA3Ead1kDKaVHDXNi9HVrgHJAcaOHu7tVDk94uLPh0E632oc75oO0gJQZ6gBZeqe6D884tPfoZKCqRw0zj3XZ/3e3Buo/tK3m0LawQ9uASqwPtx@d9HDnDBXrR43buQ63A7VG/v8frWQAAUo6SgaGQABhQcVideDyIOFEIICpNUgCAaiSSgODCpiSygqgqiqwkgqguAGYCZSthDBB6oDsKrDG5ORkoFByOZgEskFilmAS5BSgIDIFEk5MAqlMQWEDLU1VigUA "Jelly – Try It Online")
A monadic link that takes a list of strings and returns. list of maximal outputs each in the order `n, m, d`. A third of the code is to deal with the requirement for dots (last example). Now handles Kevin Cruijssen’s edge case correctly.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 110 bytes
```
≔⪫A⸿θPθFθ«≔⟦⟧ηF∧¬№0⸿ι⟦→↘↓↙⟧«≔KDLθ✳κζW›Lζ№ζι≔⊟ζε⊞η⟦κιLζ⟧»¿⁼¹⌈Eη§κ²⊞υ⊟ηFη⊞υκι»⎚≔⌈Eυ§ι²εFΦυ⁼⊟ιε«⊟ι,Iε,P✳⊟ι⎇⊖ε¹.¦⸿
```
[Try it online!](https://tio.run/##ZZLBTsMwDIbP7VNYPaVSQMBxnKYN0NCGJsSt9BB13hK1S7s0ZWNoz16ctKOV6KFx8tvf71jJpDBZKYq2nda12mn2WirNFrpqLIs5RJ8mouUQP4arprCqMkpb5rbb0gAF8BMGfWWScpCkBF6a6g17Ky2blQ1VRHcE4qBigiWTd7WTlsNkXh71OO6XJW5tGnv0lb1GzOfKYGZVqdkS9c5KcucwHOaOfXb@wVGqAoG9GBQWzTX9THrXzdl3EsMVXlZeRF@8bmrJJLWZUxaHv@LUqZcwUFtgT4dGFDW757ASJ7Vv9mwlKlc0tQu9wROj2ofYfeBxDQdnImPHwKJG8DOSg5w7Ze2nqyi8hLMChWEU9k2OjZrBSHVGXfMe@qwKd2nK6bt0zspndDPtXLrTwTXi0bCZidoy/K@O3sAw@J7E4QONFuabzTEzuEdtcUMQDjSm6DYa09yroku2bZJEWZYRPTv6P8Vp2t58Fb8 "Charcoal – Try It Online") Link is to verbose version of code. Takes an array of strings as input. Explanation:
```
≔⪫A⸿θPθ
```
Join the strings with carriage returns (not newlines) and output them without moving the cursor.
```
Fθ«
```
Loop over each character in the string.
```
≔⟦⟧η
```
Collect all of the consecutive characters starting at this position in an array.
```
F∧¬№0⸿ι⟦→↘↓↙⟧«
```
If the current character is not a `0` or a carriage return, then check all four directions.
```
≔KDLθ✳κζ
```
Peek as much as possible in that direction.
```
W›Lζ№ζι≔⊟ζε
```
Shorten the string until all of the characters are the same.
```
⊞η⟦κιLζ⟧»
```
Save the results in the array.
```
¿⁼¹⌈Eη§κ²⊞υ⊟ηFη⊞υκ
```
If the maximum consecutive character was 1, then only push one of the results to the final array, otherwise push all of them.
```
ι»
```
Reprint the current character, this time allowing the cursor to move.
```
⎚
```
Clear the input from the canvas.
```
≔⌈Eυ§ι²ε
```
Find the longest consecutive length.
```
FΦυ⁼⊟ιε«
```
Loop over the entries with that length.
```
⊟ι,Iε,
```
Output the character and length.
```
P✳⊟ι⎇⊖ε¹.¦⸿
```
If the length is 1 then output a `.` otherwise output a direction character. Then move to the start of the next line for the next result.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 82 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
í‚εεygÅ0«NFÁ]€ø`IIø)εεγJ0K}˜D€gøNUε"/\-|"XèªćÙš]€`D€ÅsZQÏεDÅsi¤'.:]{γεÐнÅsig4÷∍]€`
```
Input as a matrix of characters. Outputs as a list of triples.
[Try it online](https://tio.run/##yy9OTMpM/f//8NpHDbPObT23tTL9cKvBodV@bocbYx81rTm8I8HT8/AOTZDUuc1eBt61p@e4AMXTD@/wCz23VUk/RrdGKeLwikOrjrQfnnl0IUhPAkjB4dbiqMDD/ee2ugBZmYeWqOtZxVaf23xu6@EJF/aChNJNDm9/1NEL1vD/f3S0koGSjlIlEBtAcQUS20ApVidaKRHISoSqqoCyYbgKrAJZbyWKfmQVyCZXYqioQNOHrAqoIhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaRTeWi3jpJ/aQmU5/L/8NpHDbPObT23tTL9cKvBodV@bocba2trHzWtObwjobLy8A5NkOS5zV4G3rWn57gAxdMP7/ALPbdVST9Gt0Yp4vCKQ6uOtB@eeXQhWFMCSMXh1uKowMP957a6AFmZh5ao61nV1laf23xu6@EJF/aCxNJNDm9/1NEL0fJf59A2@//R0dFKBko6OHCsDkTWEA2jyuLQG6ujgNdwmBGJQBYyxu4EEE7CglEsqkTSWoHTokqoLLKlVSgWVaCZZYCiAtnkSgwVFVg8WolQAXEsaoCCtBEUgWhMBnIgGKQExCpH4UHlIIotYYxEcGDB1KTgFAayUsEBEhsbCwA).
**Explanation:**
Generate all diagonals and anti-diagonals of the input-matrix:
```
í # Reverse each row of the (implicit) input-matrix
‚ # Pair it with the (implicit) input-matrix
ε # Map both matrices to:
ε # Map each row to:
yg # Get the length of the current row
Å0« # Append that many 0s at the end of the row
NFÁ # Rotate the row the 0-based index amount of times towards the right
] # Close the rotate-loop and nested maps
€ø # Transpose/zip (swapping rows/columns) for both matrices
` # And push both matrices to the stack
```
Put them in a list with the input-matrix itself, as well as all columns of the input-matrix:
```
I # Push the input-matrix
Iø # Push the input-matrix, and transpose/zip (swapping rows/columns)
) # Wrap everything on the stack into a list
```
Now that we have a list of all diagonals, all anti-diagonals, all rows, and all columns, we're going to extract chunks of the same characters, and transform them into the output triplets:
```
ε # Map each matrix to:
ε # Map each row to:
γ # Split into chunks of the same elements
J # Join them together to a string
0K # Remove all 0s
}˜ # After the map of the rows: deep-flatten all chunks
€g # Get the length of each chunk
D ø # And pair it with the chunk itself
NU # Store the current index in variable `X`
ε # Map over the chunk and length pairs:
"/\-|"Xè # Get the `X`'th character from the string "/\|-"
ª # And append it to the pair
ć # Extract head; push the length plus character pair and chunk
# separately to the stack
Ù # Uniquify the chunk so a single character remains
š # And prepend it back in front of the length & character pair
] # Close both maps
€` # And then flatten once
```
Now that we have all our triplets, we only leave the largest ones:
```
ہs # Get the middle element (the chunk-length) of each
Z # Get the maximum chunk-length (without popping the list itself)
Q # Check for each chunk-length if it's equal to this maximum
D Ï # And only leave the triplets at the truthy indices
```
And finally we have to fix all `.` edge cases, for chunk-lengths of size 1:
```
ε # Map each triplet:
DÅsi # If the middle element (the chunk-length) is exactly 1:
¤'.: '# Replace the trailing character of the triplet with a "."
] # Close the if-statement and map
{ # Sort the triplets
γ # And group them by the exact same triplets
ε # Map each chunk of the same triplets to:
Ð # Triplicate the chunk of triplets
нÅsi # If the middle element of each triplet is 1:
g # Get the amount of the same triplets in this chunk
4÷ # Integer-divide it by 4
∍ # And shorten the chunk of triplets to that size
] # Close the if-statement and map
€` # Flatten once
# (after which the result is output implicitly)
```
] |
[Question]
[
Here's yet another Steenrod algebra question. Summary of the algorithm: I have a procedure that replaces a list of positive integers with a list of lists of positive integers. You need to repeatedly map this procedure over a list of lists and flatten the output until you reach a fixed point. Then for each sublist, if it appears an odd number of times, delete all but one occurrence. If it appears an even number of times, delete all occurrences. There is reference code at the bottom. The procedure for replacing a list with a list of lists is determined by a formula called the "Adem relation."
In order to represent an algebra, we need to know a basis for the algebra and also how to multiply things. From my previous question, we know the basis of the Steenrod algebra. In this question we're going to learn how to multiply Steenrod squares. The Steenrod algebra is generated by Steenrod squares \$\mathrm{Sq}^{i}\$ for \$i\$ a positive integer. It has a basis consisting of "admissible monomials" in the Steenrod squares.
A sequence of positive integers is called *admissible* if each integer is at least twice the next one. So for instance `[7,2,1]` is admissible because \$7 \geq 2\*2\$ and \$2 \geq 2\*1\$. On the other hand, `[2,2]` is not admissible because \$2 < 2\*2\$. So \$\mathrm{Sq}^7\mathrm{Sq}^2\mathrm{Sq}^1\$ is an admissible monomial, but \$\mathrm{Sq}^2\mathrm{Sq}^2\$ is not.
Every inadmissible Steenrod monomial can be expressed as a sum of admissible Steenrod monomials. For example \$\mathrm{Sq}^2\mathrm{Sq}^2 = \mathrm{Sq}^3\mathrm{Sq}^1\$, where we see that the right hand side is admissible because \$3>2\*1\$. As another example, \$\mathrm{Sq}^2\mathrm{Sq}^3 = \mathrm{Sq}^5 + \mathrm{Sq}^4\mathrm{Sq}^1\$.
Our goal is to express inadmissible Steenrod monomials as sums of admissible ones. There is a formula to express an inadmissible product of two Steenrod squares as a sum of admissible monomials called the *Adem relation*:
\$\displaystyle\mathrm{Sq}^{a}\mathrm{Sq}^{b} = \sum\_{j=0}^{a/2} \binom{b-j-1}{a-2j} \mathrm{Sq}^{a+b-j}\mathrm{Sq}^{j} \quad\text{for a < 2\*b}\$
where it's understood that \$\mathrm{Sq}^{a+b}\mathrm{Sq}^0 = \mathrm{Sq}^{a+b}\$ and where the binomial coefficients are taken mod 2. In fact all arithmetic on Steenrod monomials is computed mod 2, so for instance \$\mathrm{Sq}^2\mathrm{Sq}^1 + \mathrm{Sq}^2\mathrm{Sq}^1 = 0\$.
The algorithm to express a Steenrod monomial as a sum of admissible ones is to repeatedly find the location of an inadmissible pair, apply the Adem relation and get a sum of monomials and recurse on the resulting sum.
## Goal:
Take as input a list representing a Steenrod monomial. Output the set of the admissible Steenrod monomials that appear in the reduced sum. This can be represented as a list without repeats or as any sort of set / dictionary / map, where presence of a key in the map determines whether a monomial is in the set. This is code golf so shortest code wins.
## Helpful Formulas for Mod 2 Binomial coefficients
\$\displaystyle\binom{n}{k} =\begin{cases} 1 & n | k = n\\ 0 & \text{else}\end{cases} = \begin{cases} 1 & (n-k) \& k = 0\\ 0 & \text{else}\end{cases}\$
where \$|\$ and \$\&\$ are bit-or and bit-and.
## Examples:
```
Input: [4,2]
Output: [[4,2]]
```
Since \$4 \geq 2\*2\$ the sequence is already admissible and nothing needs to be done.
```
Input: [2,4]
Ouput: [[6], [5,1]] (order doesn't matter)
```
\$2 < 2\*4\$ and the sequence has length 2 so we just need to apply the Adem relation once. We get
\$\mathrm{Sq}^2\mathrm{Sq}^4 = \displaystyle\sum\_{j=0}^{1} \binom{3-j}{2-2j} Sq^{6-j}Sq^j = \binom{3}{2}\mathrm{Sq}^6 + \binom{2}{0}\mathrm{Sq}^5\mathrm{Sq}^1 = \mathrm{Sq}^6 + \mathrm{Sq}^5\mathrm{Sq}^1\$ where we used \$3\%2=1\$.
```
Input: [2,4,2]
Output: [[6, 2]]
```
The pair `[2,4]` or \$\mathrm{Sq}^2\mathrm{Sq}^4\$ is inadmissible so applying the Adem relation there we get \$\mathrm{Sq}^2\mathrm{Sq}^4\mathrm{Sq}^2 = \mathrm{Sq}^6\mathrm{Sq}^2 + \mathrm{Sq}^5\mathrm{Sq}^1\mathrm{Sq}^2\$. Now \$6>2\*2\$ so \$\mathrm{Sq}^6\mathrm{Sq}^2\$ is admissible and can be left alone. On the other hand, \$1 < 2\*2\$ so there is more work to do on the other term. \$\mathrm{Sq}^1\mathrm{Sq}^2 = \mathrm{Sq}^3\$ so \$\mathrm{Sq}^5\mathrm{Sq}^1\mathrm{Sq}^2 = \mathrm{Sq}^5\mathrm{Sq}^3\$.
Since \$5<2\*3\$ this can be reduced again and in fact \$\mathrm{Sq}^5\mathrm{Sq}^3 = 0\$. So \$\mathrm{Sq}^2\mathrm{Sq}^4\mathrm{Sq}^2 = \mathrm{Sq}^6\mathrm{Sq}^2\$.
```
Input: [2, 3, 2]
Output: []
```
Both `[2,3]` and `[3,2]` are inadmisible pairs so we can start in either location here. \$\def\Sq{\mathrm{Sq}}\Sq^3\Sq^2=0\$, so if we start in the second position, we immediately see the output is empty. Starting in the first position, we have \$\Sq^2\Sq^3 = \Sq^5 + \Sq^4\Sq^1\$. Then \$\Sq^5\Sq^2\$ is admissible, but \$\Sq^4\Sq^1\Sq^2\$ isn't.
\$\Sq^4\Sq^1\Sq^2 = \Sq^4\Sq^3 = \Sq^5\Sq^2\$ so the answer is \$\Sq^5\Sq^2 + \Sq^5\Sq^2 = 0\$ (all of our arithmetic is reduced mod 2).
## Test cases:
```
Input: [1, 1]
Output: []
Input: [2,2]
Output: [[3,1]]
Input: [2, 2, 2]
Output: [[5,1]]
Input: [2,2,2,2]
Output: []
Input: [4, 2, 4, 2]
Output: [[8,3,1], [10,2]] (Again, order doesn't matter)
Input: [2, 4, 2, 4]
Output: [[8,3,1],[9,2,1],[9,3],[10,2],[11,1]]
Input: [6, 6, 6]
Output: [[12, 5, 1], [13, 4, 1], [13, 5]]
Input: [6,6,6,6]
Output: []
Input: [4, 2, 1, 4, 2, 1, 4, 2, 1]
Output: [[15,5,1],[17,3,1]]
Input: [4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1]
Output: []
```
## Reference Implementations:
There is a javascript calculator here, which is an easy way to get more test cases.
<https://math.berkeley.edu/~kruckman/adem/>
Here is a python implementation:
```
def make_mono_admissible(result, mono):
"""Reduce a Steenrod monomial into a linear combination of admissible Steenrod monomials
"mono" should be a tuple representing your Steenrod monomial.
Writes answer into "result" which should be an empty dictionary.
"""
inadmissible_indices = [j for j in range(len(mono) - 1) if mono[j] < 2*mono[j+1]]
if not inadmissible_indices:
if mono in result:
del result[mono]
else:
result[mono] = 1
return
i = inadmissible_indices[0]
a = mono[i]
b = mono[i + 1]
# Do adem relation for Sq^a Sq^b
for j in range(1 + a//2):
# check if binom(b - j - 1, a - 2j) % 2 == 1
if (b - a + j - 1) & (a-2*j) == 0:
new_pair = (a+b-j, j) if j>0 else (a+b,)
make_mono_admissible(result, mono[:i] + new_pair + mono[i+2:])
```
As I was trying to make a TLDR, I made the following Mathematica code:
```
makeMonoAdmissibleStep[{a___Integer}] := {{a}}
(* If a < 2b for consecutive entries we can apply Adem relation *)
makeMonoAdmissibleStep[{start___, {p___, a_, b_, q___}, rest___}] /; a < 2 b :=
{start,
Sequence@@
(* If the mod 2 binomial coefficient is 1,
add a new list with a, b replaced by a+b-#, # *)
If[Mod[Binomial[b - # - 1, a - 2 #], 2] == 1, {p, a + b - #, # , q}, 0]&
/@ Range[0, a/2],
rest}] /. 0 -> Sequence[]
(* If the same list appears twice, drop it *)
makeMonoAdmissibleStep[{a___, x_List, b___, x_List, c___}] := {a, c}
(*If we can't do anything else, we're done *)
makeMonoAdmissibleStep[x_] := x
makeMonoAdmissible[l_] := FixedPoint[makeMonoAdmissibleStep, l]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~225~~ ~~218~~ ~~206~~ ~~203~~ ~~200~~ 196 bytes
```
q=SetAttributes
{p,s}~q~Flat
s~q~Orderless
a_~s~a_:=s[]
p@0:=p[]
f=FixedPoint[#~Distribute~s&/@#/.a_~p~b_/;a<2b:>s@@(If[BitAnd[b+#-a-1,a-2#]<1,p[a+b-#,#],s[]]&)/@Range[0,a/2]&,s[p@@#]]/.s|p->List&
```
[Try it online!](https://tio.run/##bVFba9swFH7Xr9BiML0c15HTdFtWB6UMQ6HQ0O5NiCAn8mrm2q6lwECz/3p2HCdZHoZA5@jTdzlI78q@6Xdl87Xa7T7iV20X1jZ5urXaEFeDabuPLimUJQab52ajm0IbQ9SqM51azWIjJKn5eBbX2GRxkv/Wm2WVl1Z43ffcHLw644fcC29QVnfpKvym7qN0NjecXzxm4iG3i3Ij0msvUAEDFUSevGdQC3WdBh54EjBF@pchf1HlTy3GoMJI@ojWnHtShjfmTx3MnzDO3@Hg1tCYOuIYsJYGc@paIC6CW4iGo7vDrsemMDknRCfCFJUn7IieXOD2QPsCEySC@4rYUCe4szEqsLCDyR3gOihYBL03UMcmaHXspv@IR2oP9FkMzvajy3RwcezzfoL/cs8VLWkJubgitTJGZOVK0llMH4pq/UtQp9dvFT5YogqjcZ5FUfxotlrsHxLoa9VY/lJtyw3PSp7kjbHco3EcDzdPqj/7UpJlg7/OhwRJri7JgAj84D0zO5d5EdDRErkjrInKi08jSaVPOed0H7z7Cw "Wolfram Language (Mathematica) – Try It Online")
We represent the intermediate list as an expression with `[[15,5,1],[17,3,1]]` being `s[p[15,5,1], p[17,3,1]]`. In this format, Mathematica's expression engine does some heavy lifting, and allows us to use `Distribute`. However, it takes some work to convert between this format and lists.
] |
[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/184937/edit).
Closed 4 years ago.
[Improve this question](/posts/184937/edit)
### Introduction:
Aaron is a young game developer. He recently joined the development team of a game where the players select their character from a predefined set, aka "heroes". Unfortunately, the names of the existing heroes are not evenly distributed throughout the alphabet. For example, there are 6 heroes that have a name starting with C, but only 5 starting with A or B. Since the game will continue to add new heroes, and Aaron has a saying in how to name those, he is determined to try "smoothening" the distribution of hero names.
Of course, he cannot simply mathematically generate names as gap fillers, because those suggestions would be unpronounceable and thus rejected right away. Therefore, instead of calculating a name, Aaron opted to go with "just" a helper for his creative process that helps him to focus on the right things to do:
He will calculate the "distance" between each two names following each other in alphabetical order, and then print the top ten biggest gaps between two names. This way Aaron can try to focus on finding a name that comes in between those two, so he'll eventually create a smoother equidistant descend throughout the alphabet as the list of heroes continues to grow.
### The Challenge
For a given list of names, generate the entries' keys that consist of only the uppercase form of the letters `[A-Za-z]`. Calculate a distance between each two alphabetically adjacent keys.
The first key is additionally compared to the first possible key `"A"`, the last to the last possible key `"ZZZZZZZZZZZZ"`.
Print the **top ten (or all if there are less)** biggest gaps in descending order with both names as given by the input and a measurement for the size of the gap. The "given name" of the borders is an empty string.
### Input data
The list of names. Conditions as follows:
Entries:
* The entries are guaranteed to only contain printable ASCII characters (sorry `Björn NUL LF`)
* The characters may have any case (`"Tim"`, to be treated same as `"TIM"`)
* The entries have different lengths (`"Anna", "Jon"`)
* The entries are guaranteed to **not** contain commas, so you can use that as safe delimiter for your outputs
* The entries **do** contain other characters such as spaces or dots, which do not change the key as stated above (`"Mr. T"`, to be treated same as `"MRT"`)
* The entries **are** guaranteed to give keys within 1 to 12 (inclusive) letters (entries won't be `""` or `"-.-.-. -.--.-"` or `"Gandalf the White"`)
* The entries explicitly **may** contain single quotes `'` and double quotes `"`, in case this is important for escaping
List:
* The entries **are not** guaranteed to come in any particular order (e. g.
`"Eve", "Dr. Best", "Dracula"`, keys sorted `"DRACULA", "DRBEST", "EVE"`)
* The list is guaranteed to have at least one entry
* The list is guaranteed to have only entries with distinct keys
* The list will not (and must not!) contain any entries that will give the keys `"A"` or `"ZZZZZZZZZZZZ"`
### Example
This was done in Excel. I limited the maximum length of 7 letters though for practical reasons (see notes), but the point should be clear.
```
List: ["Tim", "Mr. T", "Anna", "Jon", "Eve", "Dr. Best", "Timo", "Dracula"]
Keys: ["TIM", "MRT", "ANNA", "JON", "EVE", "DRBEST", "TIMO", "DRACULA"]
Ordered: ["ANNA", "DRACULA", "DRBEST", "EVE", "JON", "MRT", "TIM", "TIMO"]
Values: [595765044, 1808568406, 1809137970, 2255435604, 4096878669, 5305375503, 7884458676, 7884753921]
Distances: [1212803362, 569564, 446297634, 1841443065, 1208496834, 2579083173, 295245]
Distance from "ANNA" to "A": 208344555
Distance from "TIMO" to "ZZZZZZZ": 2575894526
Output (padding added for clarity, see "Rules #4"):
[ Mr. T, Tim, 2579083173 ]
[ Timo, , 2575894526 ]
[ Eve, Jon, 1841443065 ]
[ Anna, Dracula, 1212803362 ]
[ Jon, Mr. T, 1208496834 ]
[ Dr. Best, Eve, 446297634 ]
[ , Anna, 208344555 ]
[ Dracula, Dr. Best, 569564 ]
[ Tim, Timo, 295245 ]
```
Interpretation: Aaron should focus on finding a name in the middle between "Mr. T" and "Tim". Welcome **Pyrion**, splitting `2579083173` into `1261829394 + 1317253779`, while sounding absolutely badass! This is not part of the challenge however, only the top ten pairs and their distance should be output.
### Rules
* *Ex falso sequitur quodlibet.* If the input data does not conform to the rules set above, the program may do whatever, including crashing.
* You are free to chose your method of measurement for the distance, but it has to ensure the following: `AAA` and `AAC` are further apart than `AAA` and `AAB`. `AAA` is closer to `AAB` than to `ABA`. `AA` comes after `A` (so basically: all possible names are ordered lexicographically). This means the distance in the output could differ per answer, but the order of the pairs are strict.
* Range and precision of the gaps is arbitrary, as long as you have a non-zero distance between `"AAAAA AAAAA AA"` and `"AAAAA AAAAA AB"`.
* The output has to contain the names as given (not the keys) and the distance. The precise formatting is up to you, as long as it's clear what belongs together. `Name1,Name2,Distance` is a safe bet.
* As mentioned earlier, if there are more than ten results, only output the top ten.
* The borders of `"A"` and `"ZZZZZZZZZZZZ"` are empty strings in the output.
### Winner
* Code golf, shortest code by bytes wins.
### Notes
* The example above was done in Excel and uses a base 27 number system. It was limited to 7 letters, because for 12, the upper bound would be `27^13 - 1 = 4,052,555,153,018,976,266` which exceeds Excel's internal number range. If you were to add a test-link for your code which times out for 12 letter keys, feel free to use a smaller value so your program can be verified in the test-link.
* I am aware that the "measurement of the gap size" may vary depending on the algorithm. Some might not even have "one number" to sum it up. Try your best to find something conveying that finding a name between `"Mr. T"` and `"Tim"` helps a lot more than between `"Mr. T"` and `"Jon"` on our road to more equidistant names.
* This is my first posting here, feel free to comment if I need to add or clarify something. I've been looking at other content and hope I did everything right.
* The problem is derived from an actual problem I had to solve lately and I thought it might be a fun one to post it here.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 136 bytes
```
{$!=$;$/=1;(|.sort(&h),'').map({~$!,~($!=$_),-$/+($/=(sort('A'..'Z'x 12)....&h||'Z'x 12))}).sort(-*[2])[lazy ^10]}
my&h={S:g/<:!L>//.uc}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pF0VbFWkXf1tBao0avOL@oREMtQ1NHXV1TLzexQKO6TkVRp04DpCheU0dXRV9bA6hWA6xO3VFdT089Sr1CwdBIUw8I1DJqamB8zVpNiGm6WtFGsZrROYlVlQpxhgaxtVy5lWoZttXBVun6NlaKPnb6@nqlybX//wMA "Perl 6 – Try It Online")
This is an anonymous code block that takes a list of strings and returns a list of lists. This uses a brute forcey method which takes *far* too long to attempt 12 letter names, so [here is a link](https://tio.run/##PczLDoIwEAXQvV9RkobpKLY@EhcgJu7duZOgKSJgIlHxWQF/HUs1zuJkJnNzT7viMGlyReyE@KQpqeVTjwp/6LGKX47FldkZOgDIc3li5Ztazpu1oQ06fSp6TGeZycEcOIcVPMkYuR47q6rfiTV@u/rdYBRicJAvRdbDQVh3cmVnfrl0UzF1rcVMCH7b1s1FKpKwACSX4ICMWqNtrH3FO@350VoYb@pqvnez77VpEkOIXuffYkq0ITYf) to a version with only 3 letter names.
### Explanation:
```
my&h={ } # Helper function.
S:g/<:!L>// # This removes non-alpha characters
.uc # Convert to uppercase
{ # Actual code block
$!=$; # Initialise the "first" element as an empty string
$/=1; # With value 1
(|.sort(&h) # Sort the input by the helper function
,'') # And add the last string as an empty string
.map({ # Map each value to
~$!, # The previous name
~($!=$_), # The current name
-$/ # The negative of the previous value
+($/=( # Plus the new value, which is:
sort('A'..'Z'x 12) # From the lexographically sorted list of names
... # Get the sublist up to
.&h # The current name
||'Z'x 12 # Or the last name if the current is empty
)) # And get the length of the list
}).sort( # Sort each list
*[2] # By the third element
)[lazy ^10] # And get the first 10 or less items
```
] |
[Question]
[
If you have any tips regarding golfing in [Sesos](https://github.com/DennisMitchell/sesos), a language made by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis), and nobody else has covered them yet, please post them here! Only one tip is allowed per answer. Your tip should be at least somewhat specific to Sesos itself, and not just brainfuck. If your tip is relevant to brainfuck in general, you should post it [here](https://codegolf.stackexchange.com/q/12973/41024) instead.
[Answer]
# What's different in Sesos?
Golfing in Sesos is similar to golfing in brainfuck in that it has limited control flow, and that you have to grapple with the specifics of memory layout.
However, this does *not* mean you should write brainfuck code first and then translate it instruction-by-instruction to Sesos!
Here are some things that are different:
* You barely pay for repeated commands. For example, `add 1` is a 1-byte Sesos program. `add 100` is a 3-byte Sesos program. `add 1000` is *still* a 3-byte Sesos program. This means that things that would have been prohibitively expensive in brainfuck (e.g. `++++++++++`) are fine in Sesos.
* Unless you have `set mask` on, cells are not 8-bit unsigned integers—they are signed bignums. This means that you can do things like store an offset into an array as a cell without having to worry about the possibility of the array being more than 256 elements and causing overflow.
* Control flow is a bit more flexible: you have do-while loops that are guaranteed to execute at least once (with the use of `nop`). You also have `jne`, which is the equivalent of `,]` in a single instruction.
[Answer]
# Omit what you can
In Sesos, you can omit some instructions, specifically:
* You can omit a `jmp` instruction at the start of the program, if its corresponding exit point is not omitted.
* You can omit a `jnz` instruction at the end of the program, if its corresponding entry point is not omitted.
This example program prints numbers from `10` to `1`:
```
set numout
add 10
jmp
sub 1
put
jnz
```
However, we can reduce the SBIN file's size by a triad, therefore potentially reducing it by 1 byte, by removing the `jnz`:
```
set numout
add 10
jmp
sub 1
put
```
] |
[Question]
[
Codegolf the [hamming code](https://oeis.org/A075926) (with distance equals 3)!
The sequence looks like this: 0, 7, 25, 30, 42, 45, 51, 52, 75, 76, 82, 85, 97, 102, 120, 127, 385, 390, 408, 415, 427, 428, 434, 437, 458, 461, 467, 468, 480, 487, 505, 510, 642, 645, 667, 668, 680...
## Task
Given `n` output the first `n` items in OEIS sequence A075926. Your program should work for any integer `n` where `0 <= n < 2^15`. This sequence is known as the sequence of hamming codewords with distance being 3.
**Rules:**
* Post both an ungolfed version of your code (or an explatation), and the golfed version, so that other people can understand how it works
* If your program is written in a language with a compiler, specify which compiler and the compiler settings you used. Non-standard language features are allowed as long as it compiles with the compiler you specified, and the compiler was created prior to this question
**Sequence Definition:**
Given a distance 3 hamming codeword `k`, the variants of `k` are `k` itself, and any nonnegative integer that can be produced by flipping one of `k`'s bits. The `n`th hamming codeword is the smallest nonnegative integer that doesn't share a variant with any preceeding distance 3 hamming codeword. Here are the first twenty d-3 hamming codewords in binary:
>
> 0,
> 111,
> 11001,
> 11110,
> 101010,
> 101101,
> 110011,
> 110100,
> 1001011,
> 1001100,
> 1010010,
> 1010101,
> 1100001,
> 1100110,
> 1111000,
> 1111111,
> 110000001,
> 110000110,
> 110011000,
> 110011111,
> 110101011
>
>
>
**Ungolfed C++ code to produce sequence:**
```
//Flips the nth bit
size_t flipN(size_t val, int bit) {
return val ^ (1ull << bit);
}
void Hamming(size_t n) {
int bits_to_use = 20;
//This vector keeps track of which numbers are crossed off
//As either hamming codewords or their variants.
std::vector<bool> vect(1ull << bits_to_use, false);
size_t pos = 0;
size_t val = 0;
while(val <= n) {
//Checks to see that pos hasn't been crossed off
if(vect[pos]) goto loopend;
for(int i=0; i < bits_to_use; ++i)
{
if(vect[flipN(pos, i)]) goto loopend;
//Checks to see that none of the variants
//of pos have been crossed off
}
//If both those conditions are satisfied, output pos
//As the next hamming codeword
cout << pos << endl;
//Here we cross off all the variants
vect[pos] = true;
for(int i=0; i < bits_to_use; ++i)
{
vect[flipN(pos, i)] = true;
}
++val;
loopend:
++pos;
}
}
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~34 21~~ 19 bytes
*Special Thanks to [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for golfing off **half of my solution!***
```
u+Gf.Am<2sjxdT2G0QY
```
**[Try it here](https://pyth.herokuapp.com/?code=u%2BGf.Am%3C2sjxdT2G0QY&input=10&debug=0)** or **[Check out the test Suite](https://pyth.herokuapp.com/?code=u%2BGf.Am%3C2sjxdT2G0QY&input=1%0A&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)**.
---
Alternative, 19-byte solutions ([Try one here](https://pyth.herokuapp.com/?code=u%2BGf-Zm%3C2sjxdT2GZQY&input=10&debug=0)):
```
u+Gf-Zm<2sjxdT2GZQY
u+Gf-0m<2sjxdT2G0QY
u+Gf.Am<2sjxdT2GZQY
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~98~~ 97 bytes
-1 byte thanks to Mr. Xcoder
```
x=input()
l=[]
i=0
while len(l)<x:s=any(bin(i^n).count('1')<3for n in l);i+=s;l+=[i]*-~-s
print l
```
[Try it online!](https://tio.run/##BcFBDoIwEAXQfU/RHTMSDMpOmJMQTNRgmGTy29ASYOPV63vxzEvAvZRDFHHLxM5knJxK6/ZFbfY2g4yH45HkhZPeCtIn@PoJGzJVt4qH7htWD6/wxr3WknqrZdTp0vya5OKqyN5K6do/ "Python 2 – Try It Online")
Straightforward implementation, using `xor` to calculate the hamming distance.
The inner loop is equivalent to :
```
if any(bin(i^n).count('1')<3 for n in l):
i+=1
else:
l.append(i)
```
] |
[Question]
[
*EDITS*:
* Added link to the plain-text (multiple strings) test data
* Added BLANK,EDGE and TIE2 test cases (see Test Data section) (11/25)
* Updated the JSON test cases (some lines were ill-formatted) (11/24)
[](https://i.stack.imgur.com/5AqId.jpg)
Renju match gone bad ! (well, technically these guys are playing Go, but who cares) [Wikisource](https://en.wikisource.org/wiki/The_Game_of_Go_(annotated)/Chapter_I)
# TL;DR
Take a 15x15 grid of characters (made of **'.'**, **'0'** and **'\*'**), as an input, replace one of **'.'** s with **'\*'**,
in such a way that an unbroken horizontal, vertical or diagonal line of exactly five '\*' chars is formed.
```
* * *
* * *
****** * * *
* * *
* * *
```
Output the coordinates of your **'\*'**, or string - **'T'** if there is no solution.
Creating a line of more than 5 **'\*'** long (directly or indirectly) is not allowed, this is called an "overline".
Some examples of overlines:
```
****.** - replacing . with * will result in a horizontal overline
*.*** - replacing . with * will result in a diagonal overline
*
*
*
*
*
```
# Full Version
**Abstract**
[Renju](https://en.wikipedia.org/wiki/Renju) - is an abstract strategy board game (a simpler version of it is also known as Gomoku).
The game is played with *black* and *white* stones on a 15×15 gridded *Go* board.
*Black* plays first if *white* did not just win, and players alternate in placing a stone of their color on an empty intersection.
The winner is the first player to get an unbroken row of five stones horizontally, vertically, or diagonally.
Computer search by L. Victor Allis has shown that on a 15×15 board, *black* wins with perfect play.
This applies regardless of whether overlines are considered as wins.
Renju eliminates the "Perfect Win" situation in Gomoku by adding special conditions for the first player (*Black*).
(c) Wikipedia
**Objective**
Consider you are a part of a Renju match, you are playing black, and there is just one turn left for you to win.
Take the current board position as an input, identify one of the winning moves (if there is one), and output it (see below for the data formats and restrictions).
Sample input board:
```
A B C D E F G H J K L M N O P . - vacant spot (intersection)
15 . . . . . . . . . . . . . . . 15 0 - white stone
14 . . . . . . . . . . . . . . . 14 * - black stone
13 . . . . . . . . . . . . . . . 13 X - the winning move
12 . . . . . . . . . . . . . . . 12
11 . . . . . . . . . . . . . . . 11
10 . . . . . . . 0 . . . . . . . 10
9 . . . . . . . * . . . . . . . 9
8 . . . . . . . * . . . . . . . 8
7 . . . 0 . . . * . . . . . . . 7
6 . . . 0 0 . . * . . . . . . . 6
5 . . . . . . . X . . . . . . . 5
4 . . . . . . . . . . . . . . . 4
3 . . . . . . . . . . . . . . . 3
2 . . . . . . . . . . . . . . . 2
1 . . . . . . . . . . . . . . . 1
A B C D E F G H J K L M N O P
```
(axis labels are for illustration purposes only and *are not* part of the input)
Sample output:
```
H5
```
**Rules**
For the purpose of this challenge, only the following subset of Renju rules apply:
* You can place your stone on any vacant intersection (spot);
* Player who achieved an unbroken row of five stones horizontally, vertically, or diagonally, wins;
* Black (you) may not make a move which will result (directly or indirectly) in creation of an "overline" i.e. six or more black stones in a row.
**Data Formats**
Input data is a 15x15 grid of characters (".","\*","0"]), ASCII-encoded, in any acceptable format, e.g. a two-dimensional character array or a newline separated set of strings e.t.c.
You *may not* however modify the input alphabet in any way.
Output data is a string, denoting the alpha-numeric board position, as illustrated by the sample board above.
Note that original horizontal axis numeration (A..P), does not include 'I', you *MAY* use 'A..O' instead, w/o penalty.
If there is no winning move available, output "T" instead.
**Scoring**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins !
**Some Tests Cases**
*Tie*
Input:
```
A B C D E F G H J K L M N O P
15 . . . . . . . . . . . . . . . 15
14 . . . . . . . . . . . . . . . 14
13 . . . . . . . . . . . . . . . 13
12 . . . . . . . . . . . . . . . 12
11 . . . . . . . . . . . . . . . 11
10 . . . . . . . 0 . . . . . . . 10
9 . . . . . . . * . . . . . . . 9
8 . . . . . . . * . . . . . . . 8
7 . . . 0 . . . * . . . . . . . 7
6 . . . 0 0 . . * . . . . . . . 6
5 . . . . . . . Z . . . . . . . 5
4 . . . . . . . * . . . . . . . 4
3 . . . . . . . . . . . . . . . 3
2 . . . . . . . . . . . . . . . 2
1 . . . . . . . . . . . . . . . 1
A B C D E F G H J K L M N O P
```
Output:
```
"T", the only "winning move" is H5 (denoted with "Z"), but that would create an overline H4-H9
```
*Overline*
Input:
```
A B C D E F G H J K L M N O P
15 . . . . . . . . . . . . . . . 15
14 . . . . . . . . . . . . . . . 14
13 . . . . . . . . . . . . . . . 13
12 . . . . . . . . . . . . . . . 12
11 . . . . . . . . . . . . . . . 11
10 . . . . . . . . . . . . . . . 10
9 . . . . . 0 . . . . 0 . . . . 9
8 . . 0 . . . . . . * 0 0 . . . 8
7 . . 0 . . . . . * . . 0 . . . 7
6 . . 0 * . 0 . * . . 0 0 . . . 6
5 . . 0 . * . * X * * * . . . . 5
4 . . . . . Z . . . . . . . . . 4
3 . . . . . . * . . . . . . . . 3
2 . . . . . . . * . . . . . . . 2
1 . . . . . . . . * . . . . . . 1
A B C D E F G H J K L M N O P
```
Output:
```
"H5", the other possible winning move is "F4", but that would result in J1-D6 diagonal overline.
```
*Multiple winning moves*
Input:
```
A B C D E F G H J K L M N O P
15 . * * * . . * * * . . . . . . 15
14 . * . . . . . * . . * . . . . 14
13 . * . . . . . . . . . . . * . 13
12 . . . . . 0 0 0 0 0 0 0 . * . 12
11 . . . . 0 . . X . . . 0 . * * 11
10 . . . . 0 X * * * * X 0 . . * 10
9 . . . . 0 . . * . . . 0 . * * 9
8 . . . . 0 0 . * . . 0 0 . * . 8
7 . . . . . 0 . * . . 0 . . * . 7
6 . . . . . 0 . X . . 0 . . . . 6
5 . . . . . 0 0 0 0 0 0 . . . * 5
4 . . . . . . . . . . . . . . . 4
3 . . . . . . . . . . . . . . . 3
2 . . . . . . . . . . . . . . . 2
1 . . . . . . . . . . . . . . . 1
A B C D E F G H J K L M N O P
```
Output:
```
"H6" or "H11" or "F10" or "L10" (one of)
```
**Test Data**
The test data in a bit more machine-friendly form (JSON) is available [HERE](http://pastebin.com/4rZKphB6)
Added BLANK,EDGE and TIE2 test cases: [UPDATED TEST SUITE](http://pastebin.com/XBd6gBxk)
You can use the following JS snippet to convert it to multiline strings, if necessary:
```
for(B in RENJU) { console.log(B+"\n"+RENJU[B].map(l=>l.join``).join`\n`); }
```
or just download them [here](http://pastebin.com/LRGV7651)
[Answer]
# PHP, ~~205~~ ~~203~~ ~~201~~ ~~246~~ ~~257~~ 238 bytes
requires PHP<7.1 (relies on empty negative string offsets)
third approach, finally really complete, and I think I have left nothing to golf.
```
for($p=240;(!$l|$o)&&$p--;)for($k=4,$l=$o=0;$k--;$l|=preg_match("#\*{5}#",$s),$o+=preg_match("#\*{6}#",$s))for($s="*",$i=0;"."==($g=$argv[1])[$p]&&$i++<5;)$s=$g[$p-$i*$d=!$k?:$k+14].$s.$g[$p+$d*$i];echo$p<0?T:chr(65+$p%16).(15-($p/16|0));
```
takes multiline string with Linux style linebreaks (1 character) from command line argument.
For 2 character linebreak: add one each to `14`, `15` and `16` and replace `240` with `255`.
Run with `-r`.
**breakdown**
```
for($p=240;(!$l|$o)&&$p--;) // loop through positions while (no line or has overlines)
for($k=4,$l=$o=0;$k--; // loop through four directions
$l|=preg_match("#\*{5}#",$s), // post condition: set flag for line
$o+=preg_match("#\*{6}#",$s) // and count overlines
)
for($s="*", // assume asterisk at current position
$i=0;
"."==($g=$argv[1])[$p] // if character is "."
&&$i++<5;) // look 5 fields in +/- direction:
$s=$g[$p-$i*
$d=!$k?:$k+14 // map [3,2,1,0] to offset [17,16,15,1]
].$s.$g[$p+$d*$i]; // add characters
// output
echo$p<0?T:chr(65+$p%16).(15-($p/16|0));
```
uses columns `A..O`. For `A..H`+`J..P`, append `+($p/8&1)` to the `chr` parameter.
[Answer]
# JavaScript (ES6), 161
Input as multiline string.
Note: could save 1 byte using `A..O` instead of `A..P`
```
s=>[...s].some((q,p)=>([1,15,16,17].map(d=>x=(q=((r=p=>s[p-d]=='*'?r(p-d):p)(a=p)-r(p,d=-d))/d)>x?q:x,x=q!='.'&&5),x==4))?'ABCDEFGHJKLMNOP'[a%16]+(15-(a>>4)):'T'
```
*Less golfed*
```
s=>
[...s].some(
(q, p) => // execute for each character q in position p, stop when true
(
[1, 15, 16, 17].map( // offset for 4 directions
d => // for each direction d
(
// recursive function to find adjacent '*' in direction -d
r = p => s[p-d] == '*' ? r(p-d) : p,
// I need 4 adjacent '*' in at least 1 direction
// but no more in any direction
a = p, // current position in a, could be the answer
q = r(p), // look back (reuse variable q)
d = -d, q -= r(p), // then look forward
q = q/d, // number of '*' in q
x = q > x ? q : x // keep the max in any direction
),
// init x to 0 if the current position is empty
// else init x to 5, so it will be not valid in any case (too big)
x = q !='.' && 5
),
// if 4 '*' found, exit the loop
x==4
)
) // return true if solution found (solution in a)
? 'ABCDEFGHJKLMNOP'[a % 16] + (15 - ( a >> 4))
: 'T'
```
**Test**
```
F=
s=>[...s].some((q,p)=>([1,15,16,17].map(d=>x=(q=((r=p=>s[p-d]=='*'?r(p-d):p)(a=p)-r(p,d=-d))/d)>x?q:x,x=q!='.'&&5),x==4))?'ABCDEFGHJKLMNOP'[a%16]+(15-(a>>4)):'T'
out=x=>O.textContent+=x+'\n\n'
;renju = {
"BLANK":"...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............\n...............",
"EDGE":"...........****\n.0.............\n.0.............\n.0.............\n.00000.........\n.....0.........\n.....0.........\n.....0.........\n.....0.........\n...............\n...............\n.....*........*\n....*.........*\n...*..........*\n..*...........*",
"TIE":"...............\n...............\n...............\n...............\n...............\n.......0.......\n.......*.......\n.......*.......\n...0...*.......\n...00..*.......\n...............\n.......*.......\n...............\n...............\n...............",
"TIE2":"...............\n.....0****000..\n...............\n.*0............\n..*.0..........\n..0*...0.......\n.......*.......\n.......*.......\n.......*.00....\n.......*.......\n.......0.......\n...............\n...............\n...............\n...............",
"OVERLINE":"...............\n...............\n...............\n...............\n...............\n...............\n.....0....0....\n..0......*00...\n..0.....*..0...\n..0*.0.*..00...\n..0.*.*.***....\n...............\n......*........\n.......*.......\n........*......",
"MULTIPLE":"...............\n...............\n...............\n.....0000000...\n....0......0...\n....0.****.0...\n....0..*...0...\n....00.*..00...\n.....0.*..0....\n.....0....0....\n.....000000....\n...............\n...............\n...............\n..............."
};
for(k in renju) {
var r=F(renju[k])
out(k+' '+r+'\n ABCDEFGHJKLMNOP\n'+renju[k].split`\n`.map((v,i)=>(115-i+' ').slice(1)+v).join`\n`)
}
```
```
<pre id=O></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes
```
ṭ³Ṛœẹ”*¤ŒṬµ;Z;ŒD;ŒdŒrẎḢƇṀf5
Ṛœẹ”.ÇƇḢṚịØA,ɗ/ȯ”T
```
[Try it online! (OVERLINE testcase)](https://tio.run/##y0rNyan8///hzrWHNj/cOevo5Ie7dj5qmKt1aMnRSQ93rjm01TrK@ugkFyBOOTqp6OGuvoc7Fh1rf7izIc2UC0m93uF2oOiORUChh7u7D89w1Dk5Xf/EeqBMyP///6OV9FCBkg6tRQzgBFjEACKrZWCAKqIFYUBEtIBskACSGi0Q1NIiYLsWpnu0MF0IFVKKBQA "Jelly – Try It Online")
[44 bytes](https://tio.run/##y0rNyan8///hzrWHNh@d/HDXzkcNc7UOLTk66eHONYe2WkdZH53kAsQpRycVPdzV93DHomPtD3c2pJlywRTrHW4HCu1Y9HDnrIe7uw/PcNQ5OV3/xHqgTMj///@jlfRQgZIOrUUM4ARYxAAiq2VggCqiBWFARLSAbJAAkhotENTSImC7FqZ7tDBdCBVSigUA "Jelly – Try It Online") if you allow indexing the rows from top to bottom or taking them in reverse order.
[TIE testcase](https://tio.run/##y0rNyan8///hzrWHNj/cOevo5Ie7dj5qmKt1aMnRSQ93rjm01TrK@ugkFyBOOTqp6OGuvoc7Fh1rf7izIc2UC0m93uF2oOiORUChh7u7D89w1Dk5Xf/EeqBMyP///6OV9FCBkg61RQwwRLQIiBhgihhg06VHhMkkuTkWAA "Jelly – Try It Online")
[MULTIPLE testcase](https://tio.run/##y0rNyan8///hzrWHNj/cOevo5Ie7dj5qmKt1aMnRSQ93rjm01TrK@ugkFyBOOTqp6OGuvoc7Fh1rf7izIc2UC0m93uF2oOiORUChh7u7D89w1Dk5Xf/EeqBMyP///6OV9FCBkg7xIgYQgBAxgMijiGgBAaqInhaaGgOQCLI5ehARFLvgBKrtpLoZr0gsAA "Jelly – Try It Online")
## Explanation
```
ṭ³Ṛœẹ”*¤ŒṬµ;Z;ŒD;ŒdŒrẎḢƇṀf5 Auxiliary monadic link, takes a pair of coordinates
ṭ Append the pair to
¤ (
³ The input
Ṛ Reverse
œẹ”* Find all coordinates of "*"
¤ )
ŒṬ Create a matrix with 1s at these coordinates and 0s everywhere else
µ With this matrix:
; Join with
Z the columns
; Join with
ŒD diagonals
; Join with
Œd antidiagonals
Œr Run-length encode each subarray into pairs of [item, length]
Ẏ Shallow flatten
Ƈ Find pairs where
Ḣ the first item is truthy (and remove the item)
Ṁ Maximum (by the length, since the item has been removed)
f5 Filter 5. This creates [5] (truthy) if the longest run has length exactly 5, and [] (falsy) otherwise.
Ṛœẹ”.ÇƇḢṚịØA,ɗ/ȯ”T Main monadic link, takes a list of strings
Ṛ Reverse
œẹ”. Find all coordinates of "."
Ƈ Find those for which
Ç the auxiliary link gives a truthy result
Ḣ First item, or 0 if the list is empty
Ṛ Reverse
/ Fold under the following operation
ɗ (
ị Index the first item into
ØA the uppercase alphabet
, Pair with the second item
ɗ )
ȯ Logical OR with
”T "T"
```
] |
[Question]
[
This challenge is based upon three sequences, below are their formulae:
* [Recamán's sequence:](https://oeis.org/A005132)
>
>
> >
> > a1 = 0; for n > 0, an = an-1 - n
> >
> >
> >
>
>
> if positive and not already in the sequence, otherwise
>
>
>
> >
> > an = an-1 + n
> >
> >
> >
>
>
>
* [Fibonacci sequence:](https://oeis.org/A000045)
>
>
> >
> > an = (Φn – (–Φ)–n) / √5
> >
> >
> >
>
>
> where Φ denotes the [golden ratio](https://en.wikipedia.org/wiki/Golden_ratio), and
>
>
>
> >
> > a1 = 0
> >
> >
> >
>
>
>
* [Triangular numbers sequence:](https://oeis.org/A000217)
>
> a1 = 0; an = n \* (n+1) / 2
>
>
>
Your task is to take specified nth terms of each sequence and perform certain basic mathematical operations on them, namely addition, subtraction, multiplication, division, and the support of parentheses, nothing more is required.
Input is always in infix notation, and output formats are unrestricted.
Your code must be able to handle all real numbers from -10,000,000 to +10,000,000
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, and built-in functions for these sequences are not allowed.
Examples:
(These examples use an example output format of ***1R*** = *1st term of R*, ***3430T*** = *3430th term of T, and so on, however you are free to use whichever output format you desire.*)
Examples:
* (1R + 1F) \* 3
= ( 0 + 0 ) \* 3
= 0
* (1R \* 1F) - 3
= ( 0 \* 0 ) - 3
= - 3
* (1R + 2R) + (57R - 35R) / (51R - 41R) ) + (31F + 32F) - (54T)
= { [ (0 + 1) + (30 - 113) ] / (33 - 38) } + (832040 + 1346269) - (1431)
= { [ (0 + 1) + (-83) ] / (-5) } + (2178309) - (1431)
= [ (1 - 83 ) / (-5) ] + (2178309) - (1431)
= (-82 / -5) + (2178309) - (1431)
= (16.4) + (2178309) - (1431)
= 2176894.4
[Answer]
## JavaScript (ES6), ~~164~~ ~~163~~ 148 bytes
Input format: `F(n), R(n), T(n)`
```
s=>eval(s.replace(/[FRT]/g,c=>`(F=n=>${c<'R'?'n>1?F(n-2)+F(n-1):n':c>'R'?'n*++n/2':'(N=>{for(l=[1];--n;)l[x=y+=++N>y|l[y-N]?N:-N]=1})(x=y=0)|x'})`))
```
### Example
This may take a few seconds to complete.
```
let f =
s=>eval(s.replace(/[FRT]/g,c=>`(F=n=>${c<'R'?'n>1?F(n-2)+F(n-1):n':c>'R'?'n*++n/2':'(N=>{for(l=[1];--n;)l[x=y+=++N>y|l[y-N]?N:-N]=1})(x=y=0)|x'})`))
console.log(f("((R(1) + R(2)) + (R(57) - R(35))) / (R(51) - R(41)) + (F(30) + F(31)) - (T(53))"));
```
[Answer]
# Perl, ~~201~~ ~~199~~ 169 + 1 = 170 bytes
Run with the `-n` flag.
Whitespace is provided for readability and is not part of the code.
```
sub R{
$_=pop;
%m=(@_=0,1);
$m{push@_,$m{$a=$_[-1]-@_}||$a<0?$a+2*@_:$a}=1 for 2..$_;
pop
}
sub F{
@_=(0,1,@_);
push@_,$_[-1]+$_[-2]for 3..pop;
pop
}
sub T{
($_=pop)*$_++/2
}
say eval
```
Pretty straightforward. `R` calculates the nth Recaman number, `F` calculates the nth Fibonacci number, and `T` calculates the nth Triangular number. The script accepts input of an expression with terms such as `R(##)`, `T(##)`, and `F(##)`, and evaluates it.
I'm sure I can reduce the byte-count for `R`, but I'll have to spend more time thinking about it.
[Answer]
## Ruby, ~~135 132~~ 129 bytes
```
->s{R,F,T=->x{*y=r=0;(x-1).times{|i|r<<y;y=r-[z=y+~i]!=r||z<0?y-~i:z};y},->x{a,b=1,0;(x-1).times{a=b+b=a};b},->x{x*~-x/2};eval s}
```
Input format: string using the sequence names and subscript.
Example:
```
( (1R + 2R) + (57R - 35R) / (51R - 41R) ) + (31F + 32F) - (54T)
```
becomes
```
"( (R[1] + R[2]) + (R[57] - R[35]) / (R[51] - R[41]) ) + (F[31] + F[32]) - (T[54])"
```
Sorry for adding the missing bracket to the example, it wouldn't work otherwise. :-)
### Explanation
The `eval`is using the definition of R, T, and F functions.
Fibonacci: my own entry in the Fibonacci contest: <https://codegolf.stackexchange.com/a/103329/18535> changed to start from 0 instead of 1.
Recamán: inspired by Martin Ender's answer: <https://codegolf.stackexchange.com/a/37640/18535> then golfed away a couple of bytes.
Triangular: starting from 0, instead of `n*(n+1)/2` I could use `n*(n-1)/2`
] |
[Question]
[
Given a string of text that contains lowercase letters, encode it as follows: (I will be using `abcdef`)
* First, encode the [alphabet cipher](https://codegolf.stackexchange.com/questions/97859/encode-the-alphabet-cipher), but this time, 0-indexed. `000102030405`
* Reverse it. `504030201000`
* Loop through the string.
+ If the next two digits together are 25 or smaller, encode those two numbers. `5` `04` `03` `02` `01` `00` `0`
+ Otherwise, encode one number. `f` `e` `d` `c` `b` `a` `a`
* Join. `fedcbaa`
## Test cases
```
abcdef fedcbaa
abcdefghijklmnopqrstuvwxyz fyxwvucjsrqponmlktihgfedcbaa
helloworld dbromylloha
ppcg gcfpb
codegolf fboqedema
programmingpuzzlesandcodegolf fboqedemddkiobpzuzqdscmkhqerpb
```
[Encoder (not golfed)](https://repl.it/EQXU/3)
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins.
[Answer]
# JavaScript, ~~126~~ 125 bytes
```
s=>[...s.replace(/./g,c=>(parseInt(c,36)+90+'').slice(1))].reverse().join``.replace(/2[0-5]|[01]?./g,c=>(+c+10).toString(36))
```
[Try it online!](https://tio.run/##fZE9T8MwEIb3/opusZXUTUEgEErZkJgZSwX@uDhOnNix89WI/14soCoD5ZZbnve5011JB@q5U7ZbNUbAMc@OPtvuCCGeOLCackBrspYJz7bIUufhuekQT65vcXyfxlGEidcqQBuM9yExQEAQJqVRzfv7WXG1S1c3@49dutk/nnQxjzcpJp156ZxqJApOfHxYOGh75QBFuQ92B1Q8KQ0oTaK@y@@iBL0lE86201mOXscYL@OvFtwBoAkLCDeNNxqINhLliOIsYziMoIwLyJcXKwfBGaWLb04Wqqx03RjbOt/1wzgd5h/uMI1Dz0vvWmuaWledKuQpXIDWZjROi7@HCOZMfQhMQRfWcrn8pyTPLVvw8B9p9MXFc2ZaEFAHnzPS0boOR7X9PGvwtBG/4idSiEoZZud@boXndVW04Cz7BA "JavaScript (Node.js) – Try It Online")
[Answer]
# Perl, 73 + 2 = 75 bytes
Run with the `-lp` flag
```
s/./sprintf"%02d",-97+ord$&/eg;$_=reverse;s/2[0-5]|[01]?[0-9]/chr$&+97/eg
```
[Answer]
# [Haskell](https://www.haskell.org/), 107 bytes
```
g.reverse.(>>=tail.show.(+3).fromEnum)
g(a:b:c)|r<-read[a,b],r<26=['a'..]!!r:g c
g(a:b)=[a..]!!49:g b
g e=e
```
[Try it online!](https://tio.run/##Jco9T8MwEADQPb/iGiE1EYmHgpCI6m5sbIwhw8U5OxH@0jkBKeK3Y6p2fXozpi@yNjtcPEiYQgEQt/Vj5XcPD6ChjBwMo3OLN3Hbd0sJ/aTCRCZYXRZafmYjmL6JE4nqcpErLlakOfyI6vGpFpqDe/ObqwtTYTd2qv7lc8uEU4/NODR8Pr3I/ohHIYbDgTsD6j5r2ePNnl@vOBYGSFLOf0pbNCm3KsZ/ "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~31~~ 26 bytes
-5 bytes after taking a look at [Lynn's Haskell answer](https://codegolf.stackexchange.com/a/231228/64121).
```
Ç3+€¦JR[Ð2£₂‹>DŠ£Aè?.$DõQ#
```
[Try it online!](https://tio.run/##AU8AsP9vc2FiaWX//8OHMyvigqzCpkpSW8OQMsKj4oKC4oC5PkTFoMKjQcOoPy4kRMO1USP//3Byb2dyYW1taW5ncHV6emxlc2FuZGNvZGVnb2xm "05AB1E – Try It Online")
```
Ç # codepoints of the input
3+ # add 3 to each (a->100, b->101, ...)
€¦ # remove the leading "1" from each number/string
J # join into a single string
R # and reverse the string
STACK
[ # infinite loop
Ð # push 2 copies of the current remaining string s s, s, s
2£ # take the first two chars of s s[:2], s, s
₂‹ # are they (as a number) less than 26 (0 or 1) s[:2]<26, s, s
>D # add 1 and duplicate the result (s[:2]<26)+1, (s[:2]<26)+1, s, s
Š # rotate the top three items on the stack (s[:2]<26)+1, s, (s[:2]<26)+1, s
£ # take the first or two first characters from s s[:(s[:2]<26)+1], (s[:2]<26)+1, s
Aè # index with those into the alphabet
? # and print the result without a trailing newline
.$ # remove the characters from s s[(s[:2]<26)+1:]
DõQ# # if s is now empty, exit the loop
```
] |
[Question]
[
Air balloons need a gas that is lighter than air. However, hydrogen is flammable, while helium is [not sustainable](https://en.wikipedia.org/wiki/Helium#Conservation_advocates), so we need a replacement! You must write code that determines whether any given gas is lighter than air.
---
Input: a [molecular chemical formula](https://en.wikipedia.org/wiki/Chemical_formula#Molecular_formula) of a gas (ASCII)
Output: `true` if the gas is lighter than air; `false` otherwise (see [here](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) for consensus on what can be used as `true` and `false`).
If the chemical formula doesn't represent a gas (at [standard conditions](https://en.wikipedia.org/wiki/Standard_conditions_for_temperature_and_pressure)), or if it's a nonsense, any behavior is acceptable.
That is to say, you can assume the following:
* The input is a valid chemical formula
* The input is a molecular chemical formula: all element symbols are mentioned only once, and there are no parentheses
* The chemical substance exists at normal conditions
* The chemical substance is a gas at normal conditions
As a special case, `H2O` (water vapor) is considered a gas, because you can mix a significant quantity of it with air at standard conditions.
---
Whether or not a gas is lighter than air can be determined by calculating its molar mass:
Extract the chemical element symbols from the formula. Their atomic masses are given by the following table:
* H - 1
* He - 4
* B - 11
* C - 12
* N - 14
* O - 16
* F - 19
* Ne - 20
* Others - greater values
Calculate the molar mass, which is the sum of all the atomic masses. If the molar mass is less than [29](https://en.wikipedia.org/wiki/Molar_mass#Average_molar_mass_of_mixtures), the gas is lighter than air.
---
Test cases:
```
H2 true
He true
B2H6 true
CH4 true
C2H2 true
C2H4 true
HCN true
N2 true
NH3 true
H2O true
CO true
HF true
Ne true
O2 false
C2H6 false
C4H10 false
H2S false
COH2 false
CO2 false
SiH4 false
NO false
BN behavior nor specified: not a gas
HBO2 behavior nor specified: not a gas
F2O behavior nor specified: incorrect formula
CH3 behavior nor specified: incorrect formula
HCOOH behavior nor specified: not a molecular formula
B(OH)3 behavior nor specified: not a molecular formula
XYZ behavior nor specified: nonsense
```
(Note: this is meant to be an enumeration of **all** possible inputs that generate `true`. If I forgot some, I'll add it. In any case, Wikipedia is the answer for questions like "Does substance X exist?", "Is it a gas?")
---
A related (but different) question: [calculate the molar mass](https://codegolf.stackexchange.com/q/35599/25315)
[Answer]
# Perl 5, 52 bytes
51 plus 1 for `-p`:
```
$_=/^(B2H6|C2H2|C2?H4|H(CN|F|2O?|e)|N2|NH3|Ne|CO)$/
```
or
```
$_=/^(B2H6|C2H2|C2?H4|H(CN|F|2O)|[HN][e2]|NH3|CO)$/
```
or any of a few similar scripts.
Based (obviously) on [MattPutnam's Clojure answer](/a/80735).
[Answer]
# Retina, ~~108~~ 104 bytes
```
[A-Z]
;$&
Ne
xF
F
xxxO
O
xxN
N
xxC
C
xB
B
11$*x
e
xxx
H
x
x(?=x*(\d+))
$1$*x
[A-Z]
30$*x
[^x]
M`x{29}
0
```
[Try it online!](http://retina.tryitonline.net/#code=W0EtWl0KOyQmCk5lCnhGCkYKeHh4TwpPCnh4TgpOCnh4QwpDCnhCCkIKMTEkKngKZQp4eHgKSAp4CngoPz14KihcZCspKQokMSQqeApbQS1aXQozMCQqeApbXnhdCgpNYHh7Mjl9CjA&input=QjJINg)
[Test suite.](http://retina.tryitonline.net/#code=JShgW0EtWl0KOyQmCk5lCnhGCkYKeHh4TwpPCnh4TgpOCnh4QwpDCnhCCkIKMTEkKngKZQp4eHgKSAp4CngoPz14KihcZCspKQokMSQqeApbQS1aXQozMCQqeApbXnhdCgpNYHh7Mjl9CjA&input=SDIKSGUKQjJINgpDSDQKQzJIMgpDMkg0CkhDTgpOMgpOSDMKSDJPCkNPCkhGCk5lCk8yCkMySDYKQzRIMTAKSDJTCkNPSDIKQ08yClNpSDQKTk8)
[Answer]
## JavaScript (ES6), 119 bytes
```
s=>s.replace(/([A-Z][a-z]?)(\d*)/g,(_,a,n)=>m+=[11,12,19,1,4,14,20,16]["B C F H HeN NeO".search(a)/2]*(n||1),m=0)&&m<29
```
Any unknown atom causes the result to compute to `NaN` which is not less than 29.
[Answer]
# Clojure, 69 bytes
```
#(#{"H2""He""B2H6""CH4""C2H2""C2H4""HCN""N2""NH3""H2O""CO""HF""Ne"}%)
```
If that's the full list of truthy answers...
[Answer]
# Python, 235 Bytes
```
import re
a={"H":1,"He":4,"B":11,"C":12,"N":14,"O":16,"F":19,"Ne":20}
try:print(str(29>sum([int(p[1])*a[p[0]] for p in [c if c[1]!="" else (c[0],"1") for c in re.findall(r'([A-Z][a-z]*)(\d*)',input())]])).lower())
except:print("false")
```
Explanation:
```
import re # For the Regex
a={...} # Defining masses
try... except: # Catches unexpected elements and return false
re.findall(r'([A-Z][a-z]*)(\d*)',input()) # Group capture of the elements (credit to Draxx)
c if c[1]!="" else (c[0],"1") for c in # Sometimes, they may not have numbers after them, thus, if else!
int(p[1])*a[p[0]] # Mass of each elements
str(29>sum(...)).lower() # Boolean whether the statement is true/false translated to lower case string
```
Or, taking the MattPutnam way of doing things...
# Python, 71 Bytes
```
lambda n:n in"H2 He B2H6 CH4 C2H2 C2H4 HCN N2 NH3 H2O CO HF Ne".split()
```
(Credit to @Lynn)
] |
[Question]
[
First challenge!
# What is an ambigram?
Ambigrams are word(s) that read the same word(s) or another word given a certain transformation and possibly stylistic alterations.
Example:
[](https://i.stack.imgur.com/0eHn9.png)
That's an example of a rotational ambigram; it reads the same word, even when flipped around.
# The Challenge
You are to create a function, program, etc. that can detect whether a given input (consisting of only a-zA-Z chars) is a natural symmetric ambigram (an ambigram that reads the same word without significant artistic alteration given a transformation). You can compete in one or more of the following categories:
## Rotational
Examples: `I`, `O`, `ae`, `AV`, `pod`
### Transformation table (both ways)
```
a e/D
b q
d p/P
h y
l l
m w
n u/U
o o/O/G/Q
s s/S
t t
x x/X
z z/Z
A v/V
B E
D G
H H
I I
M W
N N
```
Output truesy or falsy value.
## Reflectional (Vertical Line)
Examples: `wow`, `mom`, `HOH`
### Chars to match
```
b/d i j l m n o p/q s/z t u v w x y A B/E G/D H I M O Q S/Z T U V W X Y
```
Output truthy or falsy value.
## Reflectional (Horizontal Line)
Examples: `XOD`, `KEK`, `BED`
### Chars to match
```
a l o t x B C D E H I K O X
```
Output truthy or falsy value.
## Totem
Examples:
```
x n O
o u H
x M I
O
```
### Chars to match
```
A H I M O T U V W X Y i l m n o t u v w x y
```
Output truthy or falsy value.
## Any (bonus of -50%)
This code should either output the type(s) of ambigram(s) that the input could possibly be (if the input is an ambigram) or a falsy value (if the input is not an ambigram).
# Code rules
* Standard loopholes are disallowed.
* Input is case-sensitive. This means that AV would count, but aV would not count as a rotational ambigram.
* An input of zero length is considered to be a natural symmetric ambigram.
* Make sure to write your header as: `# Division, Language, Byte-Count`.
* This is code-golf! You know what that means.
[Answer]
# Python 2, 258 bytes (~~622~~ ~~567~~ ~~543~~ 516-50%)
Here's my attempt at an answer.
```
R=dict(zip(list('abdhlmnostxzABDHIMN'),'eD q pP y l w uU oOGQ sS t xX zZ vV E G H I W N'.split()))
V='ijlmnotuvwxyAHIMOQTUVWXY'
W=dict(b='d',p='q',s='z',B='E',G='D',S='Z')
H='lotxBCDEHIKOX'
T='AHIMOTUVWXYilmnotuvwxy'
s=raw_input()
r=v=h=t=1
for i,j in R.items():
for c in j:R[c]=R.get(c,'')+i
for i,j in W.items():
for c in j:W[c]=W.get(c,'')+i
for i in range(len(s)):
c,l=s[i],s[-i-1]
r&=(c in R and l in R[c])
v&=c in V or(c in W and l in W[c])
h&=(c in H)+(l in H)>1
t&=c in T
print 'R'*r+'V'*v+'H'*h+'T'*t
```
Prints the possible types of ambigrams, or `0` if no ambigrams are possible.
`RVHT` for rotational, vertical, horizontal and totem respectively.
[Answer]
# All, Ruby, 289 - 50% = 144.5 bytes
```
i=gets.chop;s=i.tr('ijlmnotuvwxyAHIMOQTUVWXY','').tr'bpsBGS','dqzEDZ';t=i.tr'eDqpPylwuUOGQStXZvVEGHIWN','aabddhlmnnooostxzAABDHIMN';o=(i.tr('alotxBCDEHIKOX','')=='' ? 'V':'')+(s==s.reverse ? 'H':'')+(i.tr('AHIMOUVWXYilmnotuvwxy','')=='' ? 'T':'')+(t==t.reverse ? 'R':'');puts o=='' ? 1<0:o
```
This seems too long...
] |
[Question]
[
Consider a function plot like this:
```
###########
#################
####################
#######################
###########################
#############################
################################
###################################
#####################################
########################################
--------------------------------------------------------------------------------
#####################################
###################################
#################################
#############################
###########################
#######################
#####################
#################
###########
```
This function plot has been created with the J code below, which is not a solution to this challenge.
```
([: |: ([: |."1 [: #&'#'"0 [: >. [: - (* 0&>)) ,. '-' ,. [: #&'#'"0 [: <. (* 0&<)) 10 * sin 12.7 %~ i. 80
```
Your task is to write a function or program that takes as input from an implementation defined source that is not the source code of your entry:
1. Two positive integers
* *w,* the width of the plot
* *h,* the height of the plot
2. Two real numbers
* *b,* the beginning of the region to plot
* *e,* the end of the region to plot
3. A function *f* mapping real numbers to real numbers. You may assume that this function does not crash, throw an exception, return a NaN or ±∞ for arguments in the range *b* to *e* inclusive. The way in which this function is described is implementation defined, but it should be possible to use any combination of the following:
* floating point constants except NaN and ±∞
* addition
* subtraction
* multiplication
* division
* the e*x* function
* natural logarithm
* sine and cosine
Your function or program shall return or print out an ASCII art plot with dimensions *w* × *h* that looks like plot above and plots *f* in the range *b* to *e* inclusive. The plot shall be scaled so that both the topmost and bottommost line contain a `#` sign or a `-`. Your output format may diverge from the output format shown above in a meaningful way if that doesn't simplify your solution. In particular, you may exchange `#` and `-` for other characters that give the impression of *black space* and *horizontal line.*
The score of your submission is the number of tokens your program source consists of. String literals count as the length of the string they describe but at least as one point, numeric literals count as ⌈log256(|*n*|)⌉ where *n* is the number described by the numeric literal.
An identifier which is either predefined by the language or a library your submission uses or whose name can be exchanged with any other unused name counts as one character. All other identifiers count as their length in characters.
If the programming language your submission is written does not have the concept of a token, it's score is the total number of characters that can't be removed from the source without changing the meaning of the program.
The scoring rules ensure that you can indent your code and use descriptive names for your variables, etc. and lowers the edge of domain-specific languages for golfing.
The winner is the submission with the least score.
[Answer]
# Ruby (>=2.1), ~28.19812
As @FUZxxl considered that *the scoring scheme is flawed anyway*, I shall make full use of it.
```
eval (123125010100101102032105110116040115116114044102109116061034037115034041010098101103105110010115116114061115116114046100117112010115116114046103115117098033040039094039044039042042039041010115116114046103115117098033040047040097099111115104124097115105110104124097116097110104124097116097110050124097116097110124097115105110124097099111115124099111115104124115105110104124116097110104124115105110124099111115124116097110124115113114116124108111103049048124108111103050124103097109109097124108111103124101120112124101114102099124101114102124104121112111116041047105041123034077097116104046035123036049046100111119110099097115101125034125010115116114046103115117098033040047040101040036124091094114120093041124112105041047105041123034077097116104058058035123036049046117112099097115101125034125010101118097108040102109116037115116114041010114101115099117101032069120099101112116105111110061062101010112117116115032034105110118097108105100032105110112117116034010101120105116032049010101110100010101110100010119061105110116040065082071086046115104105102116041046116111095105010104061105110116040065082071086046115104105102116041046116111095105010098061105110116040065082071086046115104105102116041046116111095102010101061105110116040065082071086046115104105102116041046116111095102010102061105110116040065082071086046106111105110040039032039041044034045062120123037115125034041010119105110061065114114097121046110101119040104041123065114114097121046110101119040119041123039032039125125010100120061040101045098041047119046116111095102010098101103105110010121061065114114097121046110101119040119041123124120124102091098043040120043048046053041042100120093125010114101115099117101032069120099101112116105111110010112117116115032034105110118097108105100032105110112117116034010101120105116032049010101110100010114044113061121046109105110109097120010114061048032105102032114062048010113061048032105102032113060048010114045061048046048048049032105102032114061061113010121046109097112033032100111032124122124032010112121061040040122045114041042104047040113045114041046116111095102045048046053041046114111117110100010112121061048032105102032112121032060032048010112121061104045049032105102032112121062061104010112121010101110100010121048061040045114042104047040113045114041046116111095102045048046053041046114111117110100010121048061048032105102032121048060048010121048061104045049032105102032121048062061104010100121061040113045114041047104046116111095102010119046116105109101115032100111032124120124010121049044121050061091121048044121091120093093046109105110109097120010040121049046046121050041046101097099104123124122124119105110091122093091120093061063035125010119105110091121048093091120093061063045010101110100010112117116115032119105110046114101118101114115101046109097112040038058106111105110041046106111105110040034010034041010/123125010100101102032105110116040115116114044102109116061034037115034041010098101103105110010115116114061115116114046100117112010115116114046103115117098033040039094039044039042042039041010115116114046103115117098033040047040097099111115104124097115105110104124097116097110104124097116097110050124097116097110124097115105110124097099111115124099111115104124115105110104124116097110104124115105110124099111115124116097110124115113114116124108111103049048124108111103050124103097109109097124108111103124101120112124101114102099124101114102124104121112111116041047105041123034077097116104046035123036049046100111119110099097115101125034125010115116114046103115117098033040047040101040036124091094114120093041124112105041047105041123034077097116104058058035123036049046117112099097115101125034125010101118097108040102109116037115116114041010114101115099117101032069120099101112116105111110061062101010112117116115032034105110118097108105100032105110112117116034010101120105116032049010101110100010101110100010119061105110116040065082071086046115104105102116041046116111095105010104061105110116040065082071086046115104105102116041046116111095105010098061105110116040065082071086046115104105102116041046116111095102010101061105110116040065082071086046115104105102116041046116111095102010102061105110116040065082071086046106111105110040039032039041044034045062120123037115125034041010119105110061065114114097121046110101119040104041123065114114097121046110101119040119041123039032039125125010100120061040101045098041047119046116111095102010098101103105110010121061065114114097121046110101119040119041123124120124102091098043040120043048046053041042100120093125010114101115099117101032069120099101112116105111110010112117116115032034105110118097108105100032105110112117116034010101120105116032049010101110100010114044113061121046109105110109097120010114061048032105102032114062048010113061048032105102032113060048010114045061048046048048049032105102032114061061113010121046109097112033032100111032124122124032010112121061040040122045114041042104047040113045114041046116111095102045048046053041046114111117110100010112121061048032105102032112121032060032048010112121061104045049032105102032112121062061104010112121010101110100010121048061040045114042104047040113045114041046116111095102045048046053041046114111117110100010121048061048032105102032121048060048010121048061104045049032105102032121048062061104010100121061040113045114041047104046116111095102010119046116105109101115032100111032124120124010121049044121050061091121048044121091120093093046109105110109097120010040121049046046121050041046101097099104123124122124119105110091122093091120093061063035125010119105110091121048093091120093061063045010101110100010112117116115032119105110046114101118101114115101046109097112040038058106111105110041046106111105110040034010034041011r).numerator.to_s.chars.each_slice(3).map{|x|x.join.to_i.chr}.join
```
Try it online [here at repl.it](https://repl.it/mu8). Click `run`, then enter a valid argument line, such as `35 15 0 2*pi sin x`.
Note that [ruby has](https://bugs.ruby-lang.org/issues/8430) got [numeric literals in rational notation](http://ruby.about.com/od/Whats-New-in-Ruby-210/fl/Whats-new-in-Ruby-210-Numerics.htm), ie. `4/5r` *is* the number `0.8`. For your convenience, that number is in decimal notation:
```
0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999187817325507631477699523385795515799913435957136728483704843160446828746942390560409186850860550459503103569586130927727288203772199112576191921844592640902889572035182931044557197282985366759740529782716849115850973388128888140605856016243400934225013988573856465542961369877921225012232953123348907301055390544351983324259941650975914266982601521665336561026433337692479737252981932280375408178656797642567580351663715370847184948090264644342895761006305302658546567374207081251715305393141559888678604977336029384249599993510989638718694557098772678079302066224417461706230825883262839423706745230612246592682896861249489867511258470413422890405366642937755571215609655828342795522353669812478241921849184839881173278930914688691396470788124987284884994811350626430408706034083184877791252901811307637379707951652160630308934802951331036015209780395306897171922455792008341833306929756217105134837856722072340152691999593553044410316914296444316575597487088525352291142399342475681074383014729577969560349972908717460451924770322618430398137345975228390098138869196651815744192409770636367186809979333259806799971376312736295078106749882462806603965702298252800964932469571749077234373118173757367981246728722700185281874663305484854815686267951948417500805081514299284030097759433335422488161129087633379029256009841419395473193916652580757339572787031196350523848595739059934610272262632032121135958705400942675585265747208134940670459504182950490822639691988552469570184285722029155876735451418448434291837262494438475865157329632147682775273525502912629309290525247994344119402352906746562912938813927144960422882419280530188325720273357853282893027151548648597228005528806765612233826918005205637908161744746471586122788946189949197068027339580298342252401459219142053457266988043819308357365906624005185998891437015020338032062403957367331681344553645293069200824975432746819295160780502306565769430776755994267478055740983942989630802287991539070194275453164595814059912284843601522641410777102500263105136878073562527389017443916782604694404080884774270752289843169670231007599978515021264254378508439750915875696503075901715672796427206476124499884915354847212732145752199507692504324028476581994433822922095411336560774187464600857696611043903444276823939715034512911523115906203964192584762514518937414389869657622224007910810557978457559493621672434510900434676685136972372427070800690493574076002506601857966532889163912919790105381442988912454576487941545180577660951785673131001806319591499835474292142459954689545865168183300727693709294406587624795251901082689944668219506486589909889789178251301044755043291325912683548593327027307428216501496164310642944204812200141529560315129763903199886131965593255497607579963064788560238693963956045769026069143853104216790763807120448790598924521987287764993238737
```
This is a complete program, use it like this from the command line:
```
~ $ ruby cplot.rb 35 15 0 2*pi 'sin x'
######
########
##########
############
##############
###############
#################
-----------------------------------
#################
###############
##############
############
##########
########
######
```
or
```
~ $ ruby cplot.rb 35 15 1/pi pi '1/x'
#
#
##
##
###
###
####
######
#######
#########
#############
##################
#############################
###################################
-----------------------------------
```
I count the code as follows:
```
eval
(
<numeric> [log_256(1)=0]
)
.
numerator
.
to_s
.
chars
.
each_slice
(
<numeric> [log_256(3)=0.19812]
)
.
map
{
|
x
|
.
join
.
to_i
.
chr
}
.
join
```
[Answer]
**c# - 70ish?**
```
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
static void Main()
{
Func<double,double> f = x => Math.Sin(x) -0.5;
string r = Draw(60, 20, -10, 10, f);
Console.Write(r);
Console.ReadLine();
}
static string Draw(int w, int h, int b, int e, Func<double, double> f)
{
IEnumerable<double> values = Enumerable.Range(0, w).Select(i => f(i * (double)(e - b) / w));
double scale = h / (values.Max() - values.Min());
return String.Join(Environment.NewLine,
Enumerable.Range(0, h)
.Select(y => ((h - y) / scale) - Math.Abs(values.Min()))
.Select(ypos => Math.Abs(ypos) < 1 / (scale * 2)
? new String('-', w)
: new String(values.Select(v => v > ypos ^ ypos < 0
? '#'
: ' ').ToArray())
)
);
}
}
```
] |
[Question]
[
**This question already has answers here**:
[Print this Multiplication Table](/questions/11305/print-this-multiplication-table)
(69 answers)
Closed 9 years ago.
This javascript code:
`for(x=1;x<6;x++)for(y=1;y<6;y++)console.log((y==1?'\n':'')+x+'*'+y+'='+x*y);`
prints the following:
```
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
```
2 questions:
* Is there a smaller (in bytes) way to do the same?
* What is the smallest code that can do the same without using 2 `for` statements?
[Answer]
## Single for loop, ~~80 75 72~~ 68 bytes
I will try to make the code smaller too, but as far as single for loop goes:
```
for(i=5;i<30;)console.log(k=i/5|0,"*",l=i%5+1,"=",k*l,++i%5?"":"\n")
```
Try it in your console! (Although IE gives the best results)
] |
[Question]
[
I want a program that outputs "hello world" on console on my x86\_64 based Linux computer. Yes, a complete program, not something silly that needs an interpreter or a compiler to work.
You may:
* use all glibc functionality
* submit a static executable
* submit a dynamic executable with dependencies if you outline them
* compile an ELF file
* dig into the ELF format and remove all unneeded stuff
* be creative and work around the ELF format
Describe here how you create and execute the program.
The shortest program wins.
[Answer]
## MS-DOS .COM - 21 bytes
From the comments:
>
> marinus may use any platform he likes to go below the 45 bytes from muppetlabs.com/~breadbox/software/tiny/teensy.html – Thorsten Staerk
>
>
>
So now I had to. (So don't accept this answer because it's cheating.)
He made a mistake, because that allows me to do:
```
BITS 16
org 0x100
mov ah,9
mov dx,hello
int 0x21
int 0x20
hello: db "hello world$"
```
Compile with:
```
nasm -f bin -o hello.com hello.asm
```
And then DOSBOX or something will run the resulting `.com`, which is **21** bytes in size.
No hacks are even needed because `.com` files have no structure.
[Answer]
This is what you had in mind? Or you want any more hacky?
`EDITED(2)`
## Assembler (NASM) { source: 155 bytes, compiled: 384 bytes }
### Source code: helloworld.nasm
```
global _start
_start:
write:
mov eax, 4
mov ebx, 1
mov ecx, h
mov edx, 12
int 0x80
exit:
mov eax, 1
mov ebx, 0
int 0x80
h: db 'hello world', 10, 0
```
### Compile
```
$ nasm helloworld.nasm -f elf64 -o helloworld.o
$ ld helloworld.o -s -o helloworld
```
### Execution
```
$ ./helloworld
hello world
```
### Size
```
$ ls -al helloworld.nasm helloworld
-rw-rw-r-- 1 user user 155 Jan 5 11:08 helloworld.nasm
-rwxrwxr-x 1 user user 384 Jan 5 11:09 helloworld
```
### Platform:
```
$ uname -io
x86_64 GNU/Linux
$ nasm -v
NASM version 2.09.10 compiled on Oct 17 2011
```
[Answer]
## Assembly - compiled: 76 bytes
This is a 32-bit executable, but taking advantage of backwards compatibility it will run on x86\_64 systems too. At least it did on mine. It's based on [breadbox's "tiny.asm"](http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html) and it's hackier still so I wouldn't be that surprised if some Linuxes didn't want to touch it.
I tried it on Debian 7 in a VM, and it worked.
```
BITS 32
org 0x00200000
db 0x7F, "ELF"
hello: db "hello world", 10
dw 2
dw 3
; nasm insisted on aligning them properly so let's do it this way
exit: dd 0x80cd4066 ; inc eax - int 0x80
dd start
dd phdr - $$
phdr: dd 1
dd 0
dd $$
dw 1
dw 0
dd filesize
dd filesize
start: mov ecx, hello ; B9 0400 0200 -> flag 1 set -> executable
mov edx, 12
inc eax
shl eax,2
int 0x80
xor eax, eax
jmp exit
filesize equ $ - $$
```
It actually works:
```
~$ nasm -f bin -o hello hello.asm;chmod +x hello
~$ ./hello
hello world
~$ wc -c hello
76 hello
~$
```
It even neatly outputs a newline as I had a byte to spare in the ELF header.
] |
[Question]
[
**This question already has answers here**:
Closed 11 years ago.
>
> **Possible Duplicate:**
>
> [Holiday Gift Exchange](https://codegolf.stackexchange.com/questions/838/holiday-gift-exchange)
>
>
>
**Background:**
Secret Santa is a Western Christmas tradition in which members of a group or community are randomly assigned a person to whom they anonymously give a gift.
<http://en.wikipedia.org/wiki/Secret_Santa>
>
>
>
Ok, me and my work colleges did this today during our lunch hour - we made a secret algorithm santa pick random gifters and receivers.
Think of this question as a Christmas Programming Challenge to see who can come up with some of the most elegant solutions for this problem.
**Input:**
The input should be an array ['Oliver', 'Paul', 'Rowan', 'Darren', 'Nick', 'Atif', 'Kevin']
**Output**
A representation of something similar to key value pairs for the gifter and receiver. e.g.
```
Oliver -> Darren,
Paul -> Nick,
Rowan -> Kevin
Kevin -> Atif,
Darren -> Paul,
Nick -> Oliver,
Atif -> Rowan
```
**Deadline:** 15th December (for those late christmas shoppers)
**Remember:** you cannot have a person choosing themselves and the program must not spiral off into an infinite loop when gifter == receiver when there is only one person left.
**Rules:**
1. Must not have duplicates
2. Must be random (we all have different views on what is random - but you get my gist)
3. No Language constraints
4. Have fun
Here is mine (not golfed) in ruby:
```
require 'pp'
def move(array, from, to)
array.insert(to, array.delete_at(from))
end
gifters = ['Oliver', 'Paul', 'Rowan', 'Darren', 'Nick', 'Atif', 'Kevin'].shuffle!
recievers = gifters.dup
move recievers, recievers.count - 1, 0
pp Hash[gifters.zip recievers]
```
which spits out:
```
{"Nick"=>"Darren",
"Paul"=>"Nick",
"Kevin"=>"Paul",
"Rowan"=>"Kevin",
"Atif"=>"Rowan",
"Oliver"=>"Atif",
"Darren"=>"Oliver"}
```
[Answer]
# k (~~29~~ 20 chars)
```
{i!(1_i),*i:(-#x)?x}
```
~~{i!@[i:(-:#x)?x;,/|2 0N#!#x]}~~
Example
```
k){i!(1_i),*i:(-#x)?x}`person1`person2`person3`person4`person5
person2| person1
person5| person3
person4| person2
person1| person5
person3| person4
```
Explanation - as above, shuffles list and maps to rotation of itself.
[Answer]
```
NSMutableArray *people =
[NSMutableArray arrayWithArray:@[@"Oliver", @"Paul", @"Rowan", @"Darren", @"Nick", @"Atif", @"Kevin"]];
[people sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return (arc4random_uniform(3)-1);
}];
for (int i = 0; i < [people count]; i++)
NSLog(@"%@ gifts %@", people[i], people[(i+1)%[people count]]);
```
[Answer]
## Ruby - 161 42 chars
```
#!/usr/bin/env ruby
require 'csv'
gifters = CSV.read(ARGV[0]).first
receivers = gifters.shuffle!.dup
puts Hash[gifters.zip(receivers << receivers.shift)]
```
Usage
```
./secret_santa path_to_some_csv
=> {"Edward"=>"Alan", "Alan"=>"Charlie", "Charlie"=>"Dave", "Dave"=>"Brett", "Brett"=>"Edward"}
```
## Update
```
r=ARGV.shuffle!.dup;p ARGV.zip(r<<r.shift)
```
] |
[Question]
[
Given a string, find the 10 least common alpha-numeric characters within that string.
Output should be formatted with numbers left-padded with spaces so they look like this:
```
e: 1
t: 16
c: 42
b: 400
z: 50000
a: 100000
```
Use this to test your program: [here](https://codegolf.stackexchange.com/questions/4771/text-compression-and-decompression-nevermore)
Output for test case:
```
j: 2
x: 3
q: 9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96
```
Shortest code wins. You can submit a program or a function.
[Answer]
## Mathematica, ~~102~~ 93:
v2:
```
Grid[SortBy[
Tally@StringCases[ToLowerCase@#,x_?LetterQ:>x<>":"],
Last@# &],
Alignment->Right]&@s
```
v1:
```
TableForm[
SortBy[Tally@StringCases[ToLowerCase@#, x_?LetterQ :> x <> ":"],
#[[2]] &],
TableAlignments -> Right] &
```
[Answer]
### Bash, 72
Assuming no single-letter-named files in the current directory; input from stdin:
```
grep -io [a-z]|sort -f|uniq -ci|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'
```
Works on Linux, but for some reason, my mac's grep seems to ignore the `-i` when used with `-o` (bug or undocumented gotcha?), but the following (78) works:
```
tr A-Z a-z|grep -o [a-z]|sort|uniq -c|sort|head|sed -E 's/(.*)([a-z])/\2:\1/'
```
If the output were allowed to be reversed, the sed part could be dropped to save 30 characters in each of the previous solutions.
[Answer]
## Java ~~452~~ ~~444~~ ~~433~~ 430
```
import java.util.*;
interface L{
static void main(String[]a){
Map<Character,Integer>m=new HashMap<>();
for(char c:a[0].toLowerCase().toCharArray())if(96<c&&c<123) m.merge(c,1,(j,i)->j+i);
int l=String.valueOf(m.values().stream().reduce(0,Integer::max)).length();
m.entrySet().stream().sorted((e,f)->e.getValue()-f.getValue())
.forEachOrdered(e->System.out.println(e.getKey()+"-"+String.format("%"+l+"s",e.getValue())));
}}
```
My first contribution. I know Java will never win this kind of challenges but until now it is at least the shortest java response :)
First argument is used as input. If it contains spaces, it has to be quoted(")
Explained:
```
// there is not a lot you get for free, so import you will
import java.util.*;
interface L{
static void main(String[]a) { // java main entry point
Map<Character,Integer> m=new HashMap<>(); // key=character, value=number of occurances in input text
for(char c: // for each character in
a[0] // take first argument from command line
.toLowerCase() // convert all characters to lowercase
.toCharArray()) // convert to array so we can loop over it
if(96<c&&c<123) // accept only a-z
m.merge(c, 1, (j,i)->j+i); // fill map, increase corresponding value
int l=String.valueOf( // l: to store length of counter
m.values().stream() // loop over counter values
.reduce(0,Integer::max)) // find max value
.length(); // count number of digits of max value
m.entrySet().stream() // loop over the counter map
.sorted((e,f)->e.getValue()-f.getValue()) // sort the map by value ascending
.forEachOrdered( // loop over the ordered result
e->System.out.println( // print for every entry
e.getKey() // - the key
+"-"
+String.format("%"+l+"s", // - format using l
e.getValue()))); // the value
}}
```
452 -> 444 : removed spaces
444 -> 433 : class-> interface, ~~public~~
433 -> 430: 96<c&c<123 (thanks @ceilingcat)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~45~~ 36 bytes
```
10↑⌷⍨∘⊂∘⍋∘⌽⍨{⍺':',≢⍵}⌸∊⎕(∊⊆⊣)⍥⎕C⎕D,⎕A
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9/eNqjtgnVGo96twKRwqPeXZpADEQIka2atVyPOtqcgeosDC0f9WwD8trT/hsaPGqb@Khn@6PeFY86ZjzqagKRvd0gsmcvULAaaIi6lbrOo85FQDNqH/XseNTR9ahvqgaI6mp71LVY8/A0BbDBfVNddICE43@gwf/TFLjUPVJzcvLVAQ "APL (Dyalog Unicode) – Try It Online")
A full program which accepts a string as input. tio link uses polyfills for `⍥` and `⎕C`.
Shortened and tested with help from Bubbler.
-12 bytes from Adám.
~~Doesn't work on tio due to some problem with `⎕C`.~~(Now works, thanks to Adám's help)
## Explanation
```
10↑⌷⍨∘⊂∘⍋∘⌽⍨{⍺':',≢⍵}⌸∊⎕(∊⊆⊣)⍥⎕C⎕D,⎕A
⍥⎕C lowercase the following:
⎕D,⎕A string of the alphabet and digits
⎕ and the input
(∊⊆⊣) filter out nonalphanumerics
∊ flatten the string
{⍺':',≢⍵}⌸ create a frequency table for each letter key
⌷⍨∘⊂∘⍋∘⌽⍨ sort the table based on the last row
10↑ take the first 10 elements
```
[Answer]
# K, 60
```
{(-:|/#:'f)$f:10#$(!x)[i]!r i:<r:. x:#:'=_x@&x in,/.Q`a`A`n}
```
[Answer]
### Python, ~~206~~ ~~199~~ 195 characters
```
import sys
t=sys.stdin.read().lower()
f={}
for c in t:
if c.isalnum():f[c]=f.get(c,0)+1
s=lambda x:x[1]
h=sorted(f.items(),key=s)[:10]
for n in h:print n[0]+': '+`n[1]`.rjust(len(`max(h,s)[1]`))
```
Undoubtedly there is a lot of room for improvement, but here's my first attempt. Produces identical output for the test case provided.
206 -> 199: Removed unnecessary newline and keyword argument
199 -> 195: ~~iter~~items()
[Answer]
## Javascript, 271 characters
I'm not sure whether this breaks the rules of not (it doesn't justify the numbers in the output, but here's my solution anyway:
```
c=[];t=128;while(t--)c[t]=[0,t];i=prompt().toLowerCase();for(n=0;n<i.length;x=i.charCodeAt(n++),c[x][0]+=x>96&&x<123);for(n=i=0,c=c.sort(function(a,b){return(a[0]-b[0])});n<10;i++)if(c[i][0]>0){console.log(String.fromCharCode(c[i][1])+": "+(" "+c[i][0]).slice(-2));n++}
```
I'm pretty sure it can be simplified (I won't win with this character count :P), but now I can't find anything.
Okay, so I completely forgot that the padding was actually a requirement :O
Corrected that and fixed a bug. (250 -> 271)
[Answer]
## Haskell (229)
```
import Char
import Data.List
z=filter
t=show
l=length
k x=[(l$z(==m)x,m)|m<-x]
s z=[b:':':take(1+(maximum$map(l.t.fst)z)-l(t a))(repeat ' ')++t a++"\n"|(a,b)<-z]
main=interact$concat.s.take 10.sort.nub.k.map toLower.z isAlphaNum
```
[Answer]
## Perl, 86 chars
given string is in `$_`
```
s/[a-z]/$h{lc($&)}++/eig;printf"$_:%9d$/",$h{$_}for(sort{$h{$a}<=>$h{$b}}keys%h)[0..9]
```
[Answer]
## Python, 144
```
import os
s=os.read(0,10000).lower()
n=s.count
a=sorted(filter(str.isalnum,set(s)),key=n)[:10]
for c in a:print c+': %%%ii'%len(`n(a[-1])`)%n(c)
```
[Answer]
# JavaScript 1.8 (ES6) 186
```
F=s=>(
s.toLowerCase(n={}).replace(/[a-z0-9]/g,c=>n[c]=-~n[c]),
s=Object.keys(n).sort((a,b)=>n[a]-n[b]),
s.slice(0,10).map(x=>x+': '+(' '+n[x]).slice(-(n[s[9]]+'').length))
.join('\n')
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
Øa;ØD
ŒlċⱮ¢¢żPƇ0ị$Þḣ⁵G
```
[Try it online!](https://tio.run/##vVk9jxzHEc3nV/QtDDCZJRz7AoPUieQBJO/EW4DhoWemZ6d1M9Oj/tj1ho4cKHOkyIGcG3BgwIAdiZb/h/RH6FdVPbt71B18ZxAWBGhuu7u6uj5evSp9bfp@9/Hjh@/06Yfvzoof/9j/69uf//qXH77/4fsf/3n57z/8@qd/fPurD3/66e9//vn3f3v58ePHi7E2Kk1uVFoNthntuouq8Ub7Xam2ne2NOldYbow3DX4x@kbpsaEP7CguNsarQY87HP8maTtGXq2Tty4FtXF9GoxyrWqdX7sYzah6501ZvM@iR9c0JHiEvH6nRj1NdlyXKiT8PuKX2OFmVWuI0Srm5eJZIKHBkfDRqLUZI/b6@XT@UDqqYafqTg8V9Gyc80@LxZOVskHObmyw0fhyAU2GBPX4kYt47/HlslAP/udC9LehZKOMDt@QOsAATxdF8awrVWNDtGNNyp8rbwbDN9motjooO9LrVdWT0c9MzYt4O2QZXXcqmEl7HY1qdiRXzm69S@RDG4Nady5E8S4Jans2wJd6bTxfuLWhMw2vQSnvtr9ZLjdwIi92uoGRWFZ0quL14oV3A9mkcu4GNky@NjoY8QVtWC7lv@RvltuTBq/NiDfDdi/yr17Dp2QTrxurETSDtnA3Ag7iaYMe16YPCAc4aX/64ZZ/i3O9CUFx8JAuBoHKhi/YfnRHsP0N7gx4Z0IW@IiXK59C7MmaeBIbeUp@QqQiomm9WHXe9j2MNkCjdv6EJWOnWrxEw5@1QiB556E/Xata00dVGahhTosrh8sRWKPblmRY7O978bPRMd8MC3dIiFjCDyE6B0OZSZbvil@F8Pf5NH1qSupfBi/uxpmeIuZxB08fZfwVIp5C@L64v/QmSL7iGkRYr9bebPFO7@B1f4qnQzlRCnYZIQBhREtlsbiylK0B4aLOkanw7Bvd6AGm9AkSdy55xhq7MSMFwLmyw9Sz5Z@nKGmga1KO4l@HA@KQqsHNUAJBAjp@Dzmy3hLIHW@YMUndjxolwga/wpe1Rsbwvcgdwj9yc0PCFsslB@u5chNUB8IiI1jfx3vgTPsbfj2D5x1eKIozYyYATMzR2MwnJmM8v4Ysvo8@AeEtlwFebaE2W@XMpSryT1Q0BrqBPwJ5DXdF3XPu0Q0ENU6W9@kwOwXJaMZsmjRW3iE1RXE2wazeWm8MSY68vk9lR5C1dX7WNEy0zsJoGXUsTITtvAdhI5Bysig4Vs8PG@RKPSpTd9A/efyLY5Wub0TSJ@cf7pM3EJ/LwV3@eE43ZH@YffDE5EcJTmDEnC2ENUAqhF6Vl5HYVMDXBGBzSB2KJUPFlrzcu9SQ1A4PFAegHF4lUuw4qULKquo4I43oKpG9tWMDhAeOAOrgwtcmkjLBINIoX4k36Cie0AcY4JcPuwDY2SnzO05KRDWfznAHpTIegozg1swm7jr5uIQQyGQHWvbvbfvDkcUFsk7lDGz7JNijQsesgJ7EDyOYz3Sn7a0X/bCdNxXn4xx/0UyTIScEABkZ8x0CdyRoZ6kZQxq9Yx6zY0@8dZIKKPeoma4yNjAeDxpA0JlTUplZ2pgiXeH4CiAg7tjhq5N0mrW0cl9PWYFNvW7A6BDkNZV8XTkk0i/JzWVez4ywSqRJqy4Rf8ilr@nP@44@3Bv5kgy5Ot4JUCtCfva8qRwMXlm8ozLrZLk8UzKgcKPk1jvJmzDwSlk8Z9KIokJYwVfAOaNqTO18GmYf1C6NoKNsYeJbzEoXq44YDzbgeShTEpGdw3EW1JEXKcpdYs5IKYOEodBlPAcy1Z73FC87eBE@Xns7ZFCpLUW0RMJWZyxVrc@c5y1xb5yg@0wJi64MZb2Z02nHvmSSjB9hmEzr@NyToC4Rhm4EnRIJj0KnrxKsz9LeyRMXb/eMCcnxJoEJgSJrvzFMedgxSBIhi63b9gTtlMREaWFbD1aIajn1vIMKIBuWWKkewxZh09sYQawGownDlsv8N6DHbNirFRcIooxbagBGCv/O9BOAzhsj7ICJFERt6M8uDQxsxJK@pJqzM0KkK@KCXFIjsWY@y/EksUxv@SSYn1vJmopzcc@gQ536KUpJOOTCp@fLRxj@PatE5mWvQtnblp/rY3YLiBHzIlRnQpWsFqxcW1GplNrHFVFYB/VHUraopWhZW64j3F4cbVBUaCHGpTjBgQxInJEtuG/HdYMhUuVGabkUQAIXuLWc4ZA2FCsC85n3EOPDs6T@HLVbF3y89UiPBpSd0hatynauURBzMR41Keq6M9fwJSQDKgmLDL@Nqgi40x0Sni4eRV9N7rsoBnKG3/LJVUTCUxbozF2oZDE9Ed6iqh3xdUplp/TEOT0JYVkwX6JwPC64nOAAITZJUEyfg5AawHx9k1GMIeoLzS0Zowb3AGnsUOhhWk04Jy1UGgdgrG3h5TNUEVpAIvUwiSHMDLluHf9CDiSTSniM68BxAYZBfVklbljNrUpj/dpw6aLtr2B1CSV0XUjdzkHxo5OPaZlb9YRtjeDam/zJp3mQScKhGsz0SFrW/pOCcIXGhucaRPSMYc@hoQuddUS0A7OUkUw6crUTaBjnHMcHU3AuSeUBDACFGwBMsOMN06xzKAS2fENUxfQtAWIva8ULBrREWnHFohIiSzO4E5yjstPQhK/PrABGf7/fQKWk3KNuifaeSww@dMpU6S4ZjyKp1IzDFrV3mtW7HfmZLqNmo11c6zWsh83rhHhmE1SJ8TjsQBcAukTWvKwVK2G2XCoQoygPrWU@tzPUK2yZzLI8GIknDIhuVLWaq8Bqps0MIKJBQ6jP1wrhYRLJSckzCW/qntdn9Mgeh8zsOVmWyGXipdEqcqCsewfaBgs@IVpHsScq54Mb6/rDeb79jvPcy0PAI@x/fUXQBpqBeGbLAdi6Uu1T4aTIQUiMnGczpYxLrJcmGikXiK6C57VpoNQmnADcJvyOxKl5vbjaEsEFTOEPPXVgKNklzsVli9tBlhGflCk52GNqySB5hLR4702sO@ZANXCbh2YgKC/RK8KaHYB5ZJsigCumY2E/04Ew3hLmLcU7EyYbsdXLh9BBA0LOESP8CABnYAIrsJMbsOKrpNu2VK6j6WPbSp7c2KPzZYY6AFZOo6OR1OfkSItL76bOxJMjYJf6SaOkje1PlstJtgh@lVSNq0w0mrwD6W64HK7MMBEok5lK2rHNCxELxEyjY05DFpS@RQtxRGsfHA95iP5QJKWxIYAgL7nMqRs4BKS1J9ug70ZBjlyvL/J6R5UFnntFFdfDYUk2xExJedpSHqYrOHqexw3L5bUN17kRqnQ/EES8RHuvm9/uBew/jmT8X53x330hfQSg4ZXhmsPfFVMUpn1A4pCjGwsU@aCpFWmlm1wuDZfLmW8J@xQKg24MIm1bzt28VFV0ckiKZzQLBVk4jxkKajRfEzWT1DfSwPEh09Iv8qH/Ydb69HN64nnmBkwxaTwX7Jo70wksSqpGtntLBPCE@6oOiX5DAZumEGUfnrR4aQQyZCCzH5fMKTGPi@7riIrXJs@Pqp4ETPx/J0AdtQyUpDekQYk1DDnsN0ErJnCzhGEnDNwy65vnVUjfb5KVWlLdapWJP5wUK30jYisa6DOugWsfDXtZ/3kTIGvIm9p2L@QzemYenuXFPKvupcMoM8ei4L3vl7mwTojR3H48aFhwyldza7@b6brOzBJVashpqpGIA9freRI1jxgPg79DyaVKq6iShTgPImOHVAvCaDtNM6vj/xEiWsxDtb03@K68fY6FQCdyQT@S8AhXXHEeV1DYtgykh5L@Hw "Jelly – Try It Online")
Doesn't output with a `:` on each row, but given that isn't explicitly specified in the spec (compared to the left padding), I assumed this was OK. [26 bytes](https://tio.run/##vVk9jxzHEc3nVzQXBpjMEo51gSHqRPIAknfiLcCQ6Jnp2WnezPSoP3a9me3EgTJFSuxATg0DDgwYsCPR8v8Q/wj9qqpnd4@6g@8MwoIAzW13V1fXx6tXpbem73cfPrz7Tp@8@@60@PHb/l/fvP/rX374/ofvf/znxb9//8uf/vHNL9798ae//@n9b//29v3v/vz@N3/47OmHDx/Ox9qoNLlRaTXYZrTrLqrGG@13pdp2tjfqTGG5Md40@MXoK6XHhj6wozjfGK8GPe5w/Ouk7Rh5tU7euhTUxvVpMMq1qnV@7WI0o@qdN2XxOoseXdOQ4BHy@p0a9TTZcV2qkPD7iF9ih5tVrSFGq5iXi88DCQ2OhI9Grc0YsdfPp/OH0lENO1V3eqigZ@Ocf1QsHq6UDXJ2Y4ONxpcLaDIkqMePXMRbjy@XhbrzP@eivw0lG2V0@IbUAQZ4tCiKz7tSNTZEO9ak/JnyZjB8k41qq4OyI71eVT0Z/dTUvIi3Q5bRdaeCmbTX0ahmR3Ll7Na7RD60Mah150IU75KgtmcDfKnXxvOFWxs60/AalPJu@9lyuYETebHTDYzEsqJTFa8XT7wbyCaVc1ewYfK10cGIL2jDcin/JX@z3J40eG5GvBm2e5J/9Ro@JZt43ViNoBm0hbsRcBBPG/S4Nn1AOMBJ@9N3t/xLnOtNCIqDh3QxCFQ2fMH2ozuC7a9wZ8A7E7LAR7xc@RRiT9bEk9jIU/ITIhURTevFqvO272G0ARq18ycsGTvV4iUa/qwVAsk7D/3pWtWaPqrKQA1zUlw6XI7AGt22JMNif9@Ln42O@WZYuENCxBJ@CNE5GMpMsnxT/CqEv8@n6VNTUv88eHE3zvQUMfc7eHIv468Q8RTCt8X9hTdB8hXXIMJ6tfZmi3d6B6/7EzwdyolSsMsIAQgjWiqLxaWlbA0IF3WGTIVnX@hGDzClT5C4c8kz1tiNGSkAzpQdpp4t/zhFSQNdk3IU/zocEIdUDW6GEggS0PF7yJH1lkDueMOMSep21CgRNvgVvqw1MobvRe4Q/pGbGxK2WC45WM@Um6A6EBYZwfre3wOn2l/x6xk8b/BCUZwaMwFgYo7GZj4xGeP5NWTxffQJCG@5DPBqC7XZKqcuVZF/oqIx0A38EchruCvqnnOPbiCocbK8T4fZKUhGM2bTpLHyDqkpirMJZvXWemNIcuT1fSo7gqyt87OmYaJ1FkbLqGNhImznPQgbgZQHi4Jj9eywQa7UozJ1B/2Tx784Vun6SiR9dP7uPnkB8bkc3OSPx3RD9ofZB09MfpTgBEbM2UJYA6RC6FV5GYlNBXxNADaH1KFYMlRsycu9Sw1J7fBAcQDK4WUixY6TKqSsqo4z0oiuEtlbOzZAeOAIoA4ufG4iKRMMIo3ylXiDjuIJfYABfvmwC4CdnTK/5qREVPPpDHdQKuMhyAhuzWzippP3SwiBTHagZf9etz8cWZwj61TOwLZPgj0qdMwK6En8MIL5THfa3nrRD9t5U3E2zvEXzTQZckIAkJExXyFwR4J2lpoxpNE75jE79sRLJ6mAco@a6SpjA@PxoAEEnTkhlZmljSnSFY6vAALijh2@OkmnWUsr9/WUFdjU6waMDkFeU8nXlUMi/ZzcXOT1zAirRJq06gLxh1x6S3/edvTu3siXZMjV8UaAWhHys@dN5WDwyuIdlVkny@WZkgGFGyW33knehIFXyuIxk0YUFcIKvgLOGVVjaufTMPugdmkEHWULE99iVrpYdcR4sAHPQ5mSiOwcjrOgjrxIUe4Sc0ZKGSQMhS7jOZCp9ryneNrBi/Dx2tshg0ptKaIlErY6Y6lqfeY8L4l74wTdZ0pYdGUo682cTjv2JZNk/AjDZFrH5x4GdYEwdCPolEi4Fzp9lWB9lvZKnrh4uWdMSI4XCUwIFFn7jWHKw45BkghZbN22J2inJCZKC9t6sEJUy6nnHVQA2bDESvUYtgib3sYIYjUYTRi2XOa/AT1mw16tuEAQZdxSAzBS@HemnwB03hhhB0ykIGpDf3ZpYGAjlvQl1ZydESJdERfkkhqJNfNZjieJZXrLR8H82ErWVJyLewYd6tRPUUrCIRc@Pl/ew/CvWSUyL3sVyl63/Fwfs1tAjJgXoToTqmS1YOXaikql1D6uiMI6qD@SskUtRcvach3h9uJog6JCCzEuxQkOZEDijGzBfTuuGwyRKjdKy6UAErjAteUMh7ShWBGYz7yHGB@eJfXnqN065@OtR3o0oOyUtmhVtnONgpjz8ahJUW868wa@hGRAJWGR4bdRFQF3ukHCo8W96KvJfRfFQM7waz65jEh4ygKduQuVLKYnwltUtSO@TqnslJ44pychLAvmSxSOxwWXExwgxCYJiulzEFIDmK@vMooxRH2huSVj1OAeII0dCj1MqwnnpIVK4wCMtS28fIoqQgtIpB4mMYSZIdet41/IgWRSCY9xHTguwDCoL6vEDau5VWmsXxsuXbT9GawuoYSuC6nbOSh@dPI@LXOrHrKtEVx7kz/8OA8ySThUg5keScvaf1QQLtHY8FyDiJ4x7Dk0dKGzjoh2YJYykklHrnYCDeOc4/hgCs4lqTyAAaBwA4AJdrximnUGhcCWr4iqmL4lQOxlrXjCgJZIK65YVEJkaQZ3gnNUdhqa8PWZFcDor/cbqJSUe9Qt0d5zicGHTpkq3STjXiSVmnHYovZOs3rXIz/TZdRstItrvYb1sHmdEM9sgioxHocd6AJAl8ial7ViJcyWSwViFOWhtczndoZ6hS2TWZYHI/GEAdGNqlZzFVjNtJkBRDRoCPX5WiE8TCI5KXkm4U3d8/qMHtnjkJk9J8sSuUy8NFpFDpR170DbYMGHROso9kTlfHBjXX84z7ffcJ57eQi4h/3fXBK0gWYgntlyALauVPtUeFDkICRGzrOZUsYl1ksTjZQLRFfB89o0UGoTTgBuE35H4tS8XlxuieACpvCHnjowlOwS5@Kyxe0gy4hPypQc7DG1ZJA8Qlq89ibWHXOgGrjNQzMQlKfoFWHNDsA8sk0RwBXTsbCf6UAYbwnzluKVCZON2OrlQ@igASHniBF@BIAzMIEV2MkNWPFV0m1bKtfR9LFtJU@u7NH5MkMdACun0dFI6lNypMWFd1Nn4oMjYJf6SaOkje0fLJeTbBH8KqkaV5loNHkH0t1wOVyZYSJQJjOVtGObFyIWiJlGx5yGLCh9ixbiiNY@OB7yEP2hSEpjQwBBXnKZUzdwCEhrT7ZB342CHLlen@f1jioLPPeMKq6Hw5JsiJmS8rSlPExXcPQsjxuWyzc2vMmNUKX7gSDiKdp73fxqL2D/cSTj/@qM/@4L6SMADc8M1xz@rpiiMO0DEocc3VigyAdNrUgr3eRyabhcznxL2KdQGHRjEGnbcu7mpaqik0NSfE6zUJCFs5ihoEbzNVEzSX0jDRzvMi39Ih/6H2atjz6lJx5nbsAUk8Zzwa65M53AoqRqZLu3RAAfcF/VIdGvKGDTFKLsw5MWT41Ahgxk9uOSOSXmcdFtHVHx3OT5UdWTgIn/7wSoo5aBkvSGNCixhiGH/SZoxQRuljDshIFbZn3zvArp@3WyUkuqa60y8YcHxUpfidiKBvqMa@DaR8Ne1n/eBMga8qa23Qv5hJ6Zh2d5Mc@qe@kwysyxKHhv@2UurBNiNLcfdxoWnPDV3NrvZrquM7NElRpymmok4sD1ep5EzSPGw@DvUHKp0iqqZCHOg8jYIdWCMNpO08zq@H@EiBbzUG3vDb4rb59jIdCJXNCPJNzDFZecxxUUti0D6aGk/wc) to require separating by `:`.
## How it works
```
Øa;ØD - Helper link. Yield a constant value "abc...xyz012...789"
Øa - Yield "abc...xyz"
ØD - Yield "0123456789"
; - Concatenate
ŒlċⱮ¢¢żPƇ0ị$Þḣ⁵G - Main link. Takes a string S on the left
Œl - Convert S to lowercase
¢ - Yield "abc...789"
Ɱ - For each character:
ċ - Count occurrences in S
¢ - Yield "abc...789"
ż - Zip with occurrences
Ƈ - Keep characters where:
P - There is at least 1 occurrence in S
$Þ - Sort by:
0ị - Number of occurrences
ḣ⁵ - Take the first 10
G - Convert into a grid format
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Yet another old challenge hindered by an unnecessarily cumbersome output format.
```
r\W v ü ñʮάpZÊïA yù ®q":
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&header=YE9uY2UgdXBvbiBhIG1pZG5pZ2h0IGRyZWFyeSwgd2hpbGUgSSBwb25kZXJlZCwgd2VhayBhbmQgd2VhcnksCk92ZXIgbWFueSBhIHF1YWludCBhbmQgY3VyaW91cyB2b2x1bWUgb2YgZm9yZ290dGVuIGxvcmUsCldoaWxlIEkgbm9kZGVkLCBuZWFybHkgbmFwcGluZywgc3VkZGVubHkgdGhlcmUgY2FtZSBhIHRhcHBpbmcsCkFzIG9mIHNvbWUgb25lIGdlbnRseSByYXBwaW5nLCByYXBwaW5nIGF0IG15IGNoYW1iZXIgZG9vci4KIidUIGlzIHNvbWUgdmlzaXRlciwiIEkgbXV0dGVyZWQsICJ0YXBwaW5nIGF0IG15IGNoYW1iZXIgZG9vci0tCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIE9ubHkgdGhpcywgYW5kIG5vdGhpbmcgbW9yZS4iCgpBaCwgZGlzdGluY3RseSBJIHJlbWVtYmVyIGl0IHdhcyBpbiB0aGUgYmxlYWsgRGVjZW1iZXIsCkFuZCBlYWNoIHNlcGFyYXRlIGR5aW5nIGVtYmVyIHdyb3VnaHQgaXRzIGdob3N0IHVwb24gdGhlIGZsb29yLgpFYWdlcmx5IEkgd2lzaGVkIHRoZSBtb3Jyb3c6LS12YWlubHkgSSBoYWQgc291Z2h0IHRvIGJvcnJvdwpGcm9tIG15IGJvb2tzIHN1cmNlYXNlIG9mIHNvcnJvdy0tc29ycm93IGZvciB0aGUgbG9zdCBMZW5vcmUtLQpGb3IgdGhlIHJhcmUgYW5kIHJhZGlhbnQgbWFpZGVuIHdob20gdGhlIGFuZ2VscyBuYW1lIExlbm9yZS0tCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIE5hbWVsZXNzIGhlcmUgZm9yIGV2ZXJtb3JlLgoKQW5kIHRoZSBzaWxrZW4gc2FkIHVuY2VydGFpbiBydXN0bGluZyBvZiBlYWNoIHB1cnBsZSBjdXJ0YWluClRocmlsbGVkIG1lLS1maWxsZWQgbWUgd2l0aCBmYW50YXN0aWMgdGVycm9ycyBuZXZlciBmZWx0IGJlZm9yZTsKU28gdGhhdCBub3csIHRvIHN0aWxsIHRoZSBiZWF0aW5nIG9mIG15IGhlYXJ0LCBJIHN0b29kIHJlcGVhdGluZwoiJ1QgaXMgc29tZSB2aXNpdGVyIGVudHJlYXRpbmcgZW50cmFuY2UgYXQgbXkgY2hhbWJlciBkb29yClNvbWUgbGF0ZSB2aXNpdGVyIGVudHJlYXRpbmcgZW50cmFuY2UgYXQgbXkgY2hhbWJlciBkb29yOy0tCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFRoaXMgaXQgaXMsIGFuZCBub3RoaW5nIG1vcmUuImA&code=clxXIHYg/CDxyq7OuHBabMOvQSB5%2bSBtcSI6IA) (Note: I'm passing the input in the header here so it can be enclosed in backticks, allowing for the inclusion of both single & double quotes. Doing so, however, makes no difference to the code or byte count.)
```
r\W v ü ñʮάpZÊïA yù ®q": :Implicit input of string
r :Remove
\W : /[^A-Z0-9]/gi
v :Lowercase
ü :Group & sort
ñ :Sort by
Ê : Length
® :Map each Z
Î : First character
¬ : Split
p : Push
ZÊ : Length of Z
à :End map
¯ :Slice to
A : 10th element
y :Transpose
ù :Left pad each sub array with spaces to the length of the longest and implicitly transpose back
® :Map
q": : Join with ": "
:Implicit output joined with newlines
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 1 year ago.
[Improve this question](/posts/7223/edit)
*This is a variant of [List prime-factorized natural numbers up to N in ascending order](https://codegolf.stackexchange.com/q/7221/5273), but the solutions can be very different.*
Write a program that outputs [prime factorizations](https://en.wikipedia.org/wiki/Prime_factorization) of all natural numbers in any order. For example, the output could look like:
```
1:
4: 2^2
8: 2^3
2: 2^1
3: 3^1
5: 5^1
6: 2^1 3^1
21: 3^1 7^1
9: 3^2
...
```
**Requirements:**
1. *You cannot just iterate over the numbers and factor each of them.* This is too inefficient.
2. The output should be as in the example above: On each line the number and the list of its prime factors.
3. There is no given order in which the number appear in the list. However:
4. Each number must appear *exactly once* in the list (explain that your code satisfies this condition).
**Edit - remark:** Of course the program never finishes. But since (4) requires each number to appear in the list, for any `n` there is time `t` such that the list produced by the program within time `t` contains the factorization of `n`. (We don't care if `t` is comparable to the age of our universe or anything else.)
**Note:** This is *not* code-golf, it's code-challenge. This puzzle is about clever ideas, not code size. So please don't give the shortest solutions, give commented solutions that are easy to read and where the idea is easily understandable.
[Answer]
# Haskell
```
import Data.List
merge :: [[a]] -> [[a]] -> [[a]]
merge [] ys = ys
merge (x:xs) ys = x : merge ys xs
atmostonefromeach :: [[a]]-> [[a]]
atmostonefromeach = foldr weave undefined
weave :: [a] -> [[a]] -> [[a]]
weave pwrs odds = merge (map (:[]) pwrs) $
foldr (\odd -> merge (odd: (map (:odd) (pwrs)))) undefined odds
primes = nubBy (\x y->gcd x y > 1) [2..]
shw factors = show (product (map (\(p,k)->p^k) factors)) ++ ":" ++ concatMap(\(p,k) -> ' ': show p ++ '^': show k) factors
powers p = map (\x->(p,x)) [1..]
main = mapM_ (putStrLn . shw) $ ([]:) $ atmostonefromeach $ map powers primes
```
output:
```
1:
2: 2^1
3: 3^1
4: 2^2
5: 5^1
8: 2^3
6: 2^1 3^1
...
```
The program constructs,
from the list Q=[q0,q1,..] of composite numbers with all prime factors > p,
the list of those with primes factors >= p, as
merge(P, merge((map(q0\*)P1), merge(map(q1\*)P1),...
where P=[p^1,p^2,...] and P1=[p^0,p^1,..].
The name odds in function weave describes the case p==2,
where Q is the set of all odd numbers > 1.
[Answer]
Generates the list by iterating over N. Each iteration generates all numbers which are the product of up-to-Nth powers of the first N primes. Starts with N=1 and keeps growing N. To avoid duplicates, each iteration makes sure not to generate anything generated in previous iterations. Those are exactly the numbers that don't include the Nth prime and which don't have at least one exponent equal to N.
```
import itertools
print '1 ='
n = 0
primes = []
while 1:
n += 1
# generate next prime
q = primes[-1] if primes else 1
while 1:
q += 1
if all(q % p != 0 for p in primes):
primes.append(q)
break
# generate all exponents of at most n of first n primes
for e in itertools.product(*(xrange(n+1) for i in xrange(n))):
if max(e) == n or e[-1] > 0: # we didn't do this in iteration n-1
print reduce(lambda x, y: x * y, (primes[i]**e[i] for i in xrange(n))), '=', ' '.join('%d^%d' % (primes[i], e[i]) for i in xrange(n))
```
] |
[Question]
[
**Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/5359/edit).
Closed 1 year ago.
[Improve this question](/posts/5359/edit)
Implement any model of computation as powerful as a Turing machine using any existing language's type system.
Your solution should handle the computation using the language's type system, not the language's regular Turing complete features, nor a macro system. It is however acceptable to use the language's regular features for IO, typical boilerplate, etc. so long as your program's Turing completeness hangs on the type system.
You are certainly welcome to use optional type system features that require compiler options to activate.
Please specify how to program and run your machine, ala "edit these numbers/constructs in the source, compile it and run it."
As an example, there is an [implementation of brainfuck](http://graphov.blogspot.co.uk/2010/03/template-brainfuck-compiler.html) in [C++ template meta-programming](http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s04.html). In fact, brainfuck is more complex than necessary because it offers user IO separate from its tape. A few simpler [models of computation](http://en.wikipedia.org/wiki/Turing_machine_equivalents) include Brainfuck's ancestor [P"](http://en.wikipedia.org/wiki/P%22), [λ-calculus](http://en.wikipedia.org/wiki/Lambda_calculus), the [(2,3) Turing Machine](http://en.wikipedia.org/wiki/Wolfram%27s_2-state_3-symbol_Turing_machine#Description), and [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
We'll declare the winner to be whoever minimizes : their code's length plus 10 times the number of commenters who assert they already knew the language had a turing complete type system.
[Answer]
My limited Haskell-fu has come up with this implementation of SK-calculus in Haskell's type system:
```
data S = S
data K = K
data A l r = A l r
class C i o | i -> o
instance C (A (A K a) b) a
instance C (A (A (A S a) b) c) (A (A a c) (A b c))
```
] |
[Question]
[
Given an expression of one-letter variables (`[a-z]`), operators (`*, +, &`) and parenthesis, expand it using the following axioms:
```
a * b != b * a
a * b * c = (a * b) * c = a * (b * c)
a + b = b + a
a + b + c = (a + b) + c = a + (b + c)
a * (b + c) = a * b + a * c
a & b = b & a
a & (b + c) = a & b + a & c
| Comm | Assoc | Dist
* | NO | YES |
+ | YES | YES | *
& | YES | YES | + *
```
The user will input an expression, the syntax of the input expression is called "input form". It has the following grammar:
```
inputform ::= expr
var ::= [a-z] // one lowercase alphabet
expr ::= add
| add & expr
add ::= mult
| mult + add
mult ::= prim
| prim * mult
| prim mult
prim ::= var
| ( expr )
```
Before
That means, the order of operations is \* + &, `a + b * c & d + e = (a + (b * c)) & (d + e)`
Furthermore, the operator `*` can be omitted:
a b (c + d) = ab(c + d) = a \* b \* (c + d)
Whitespace is stripped out before parsing.
Examples:
```
(a + b) * (c + d)
= (a + b)(c + d)
= (a + b)c + (a + b)d
= ac + bc + ad + bd
(a & b)(c & d)
= ac & ad & bc & bd
(a & b) + (c & d)
= a + c & a + d & b + c & b + d
((a & b) + c)(d + e)
= ((a & b) + c)d + ((a & b) + c)e (I'm choosing the reduction order that is shortest, but you don't need to)
= ((a & b)d + cd) + ((a & b)e + ce)
= ((ad & bd) + cd) + ((ae & be) + ce)
= (ad + cd & bd + cd) + (ae + ce & be + ce)
= ad + cd + ae + ce & ad + cd + be + ce & bd + cd + ae + ce & bd + cd + be + ce
```
Due to commutativity, order of some terms do not matter.
Your program will read an expression in input form, and expand the expression fully, and output the expanded expression in input form, with one space separating operators, and no spaces for multiplication. (`a + bc` instead of `a+b * c` or `a + b * c` or `a + b c`)
The fully expanded form can be written without any parens, for example, `a + b & a + c` is fully expanded, because it has no parens, and `a(b + c)` is not.
Here is an example interactive session (notice the whitespaces in input)
```
$ expand
> a(b + (c&d))
ab + ac & ab + ad
> x y * (wz)
xywz
> x-y+1
Syntax error
> c(a +b
Syntax error
```
[Answer]
## Ruby, 698 648
```
O=[A='&',B='+',C='*']
M='Syntax error'
def u(x)c=x.shift;(c.nil?)?S[0]=~/[a-z]/?(S.shift):S[0]=='('?(S.shift;o=u(O*1);S[0]==')'?(S.shift;o):abort(M)):abort(M):(o=[c];loop{o<<u(x*1);break if S[0]!=c;S.shift};o)end
def d(e,a,b)a!=e[0]?e:(i=e.index{|x|x[0]==b};(i.nil?)?e:y([b]+e[i][1..-1].map{|k|z=e*1;z[i]=k;z}))end
def y(e)e.map!{|x|(x.is_a?Array)?(y(x)):(x)};o=[e[0]];e[1..-1].map{|x|x[0]==o[0]?(o+=x[1..-1]):(o<<x)};d(d(d(o.size==2?o[1]:o,C,B),C,A),B,A)end
def j(e)(e.is_a?Array)?(e.map!{|x|j(x)};o=e.shift;e*(o=='*'?'':" #{o} ")):e;end
S=gets.gsub(/ /,'').gsub(/([a-z)])(?=[a-z(])/,'\1*\2').split(//)
k=u(O*1)
puts S!=["\n"]?(M):(j y k)
```
This solution consists of a basic recursive descent parser (method `u`) which builds an syntax tree which is then flattened (`y`) and transformed (`d`) according to the distribution axioms. The output (`j`) simply joins the operands again.
Unfortunately I broke the functionality when I later tried to reduce the code by restructuring. Nevertheless I think there is still some chance for golfing.
[Answer]
### Scala - 1049 characters
This is not fully golfed, but it gets increasingly incomprehensible as I continue, and since the examples do not all appear to be correct, I want to leave the code at least slightly sane so it can be modified.
To be run as a script file. Empty input ends the program.
```
type S=String
case class R(rs: List[R], s: S)
def n(s: S)=List(" + "," & ").indexOf(s)
def pr(r:R,v:Int=2):S = if (r.rs.isEmpty) r.s else {
val x = r.rs.map(pr(_,n(r.s))).mkString(r.s)
if (n(r.s)>v) "("+x+")" else x
}
object P extends scala.util.parsing.combinator.RegexParsers {
val v="[a-z]"r
def e:Parser[R]=repsep(a,"&") ^^ {R(_," & ")}
def a=repsep(m,"+") ^^ {R(_," + ")}
def m=repsep(p,"\\*?"r) ^^ {R(_,"")}
def p=v ^^ {R(Nil,_)} | "("~>e<~")" ^^ {r=>R(r::Nil,"")}
}
def up(r: R):R = r match {
case R(x::Nil,_) => up(x)
case _ => R(r.rs.map(up),r.s)
}
def asc(r: R) = R(r.rs.flatMap(i=>if (i.s==r.s) i.rs else List(i)),r.s)
def dis(r: R):R = {
val q = asc(r.rs.find(i=>n(i.s)>n(r.s)).map(i => {
val (a,b)=r.rs.span(_ ne i)
R(i.rs.map(j=>R(a ::: j :: b.tail,r.s)),i.s)
}).getOrElse(R(r.rs.map(dis),r.s)))
if (q==r) r else dis(q)
}
def parse(s: S) = P.parseAll(P.e,s).map(x=>pr(dis(up(x)))).getOrElse("Syntax error")
Iterator.continually{print("> ");readLine}.
takeWhile(_.length>0).foreach(s=>println(parse(s)))
```
[Answer]
# Haskell, ~~472~~ 437 characters
```
import Text.Parsec
data E=V Char|O Int E E
r o=fmap$foldr1(O o)
c=char
s=sepBy1
e=r 0$s(r 1$s (r 2$s(fmap V lower<|>between(c '(')(c ')')e)(optional$c '*'))(c '+'))(c '&')
g(O a x(O b y z))|b<a=g$O b(g$O a x y)(g$O a x z)
g(O a (O b x y)z)|b<a=g$O b(g$O a x z)(g$O a y z)
g e=e
d(V c)=[c]
d(O o x y)=d x++[" & "," + ",""]!!o++d y
x=either(const "Syntax error")d.fmap g.parse e"".filter(`notElem`" \t")
main=interact$unlines.map x.lines
```
] |
[Question]
[
**This question already has answers here**:
[Implement the Torian](/questions/231274/implement-the-torian)
(22 answers)
Closed 2 years ago.
## Introduction
Factorials are one of the most frequently used examples to show how a programming language works.
A factorial, denoted \$n!\$, is \$1⋅2⋅3⋅…⋅(n-2)⋅(n-1)⋅n\$.
There is also the superfactorial (there are other definitions of this, but I chose this one because it looks more like the factorial), denoted \$n$\$, which is equal to \$1!⋅2!⋅3!⋅…⋅(n-2)!⋅(n-1)!⋅n!\$.
From that you can create an infinity of (super)\*factorials (means *any number of times `super` followed by one `factorial`*) (supersuperfactorial, supersupersuperfactorial, etc...) which all can be represented as a function \$‼(x,y)\$, which has two parameters, \$x\$ the number to (super)\*factorialize, and y, the number of times plus one that you add the prefix *super* before *factorial* (So if \$y=1\$ it would be a factorial (\$x!=\space‼(x,1)\$), with \$y=2\$ a superfactorial, and with \$y=4\$ a supersupersuperfactorial).
\$!!\$ is defined as such:
\$‼(x,0)=x\$ (if \$y\$ is 0, return \$x\$)
\$‼(x,y)\space=\space‼(1,y-1)\space⋅\space‼(2,y-1)\space⋅\space‼(3,y-1)\space⋅…⋅\space‼(x-2,y-1)\space⋅\space‼(x-1,y-1)\$
The second definition would have looked cleaner with a pi product \$\prod\$, but it does not display properly. (image [here](https://i.stack.imgur.com/OVWXc.png))
In Python, \$!!\$ could be implemented this way:
```
from functools import reduce
def n_superfactorial(x, supers):
if x == 0:
return 1
elif supers == 0:
return x
return reduce(lambda x,y:x*y, [n_superfactorial(i, supers-1) for i in range(1, x+1)])
```
## Challenge
Create a function/program that calculates \$!!(x,y)\$.
Your code is *not* required to support floats or negative numbers.
\$x\$ will always be \$≥1\$ and \$y\$ will always be \$≥0\$.
It is not required to compute \$!!\$ via recursion.
Your program may exit with a recursion error given large numbers, but should at least *theoretically* be able to calculate in finite time any (super)\*factorial.
## Test cases
```
Format : [x, y] -> result
[1, 1] -> 1
[2, 2] -> 2
[3, 3] -> 24
[3, 7] -> 384
[4, 4] -> 331776
[5, 3] -> 238878720
[2232, 0] -> 2232
[3, 200] -> 4820814132776970826625886277023487807566608981348378505904128
```
Note: if your language does not support integer types that are that large, you are not required to support the last test case.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://github.com/abrudz/SBCS)
A naïve recursive implementation.
```
{×⍺:×/(⍺-1)∇¨⍳⍵⋄⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ee9u6wOT9fXANK6hpqPOtoPrXjUu/lR79ZH3S1AsvZ/2qO2CY96@x71TfX0f9TVfGi98aO2iUBecJAzkAzx8Az@b6iQpmDIZQQkjbiMgaQxlzmYNAGSJmARUy4DkKyRsREA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
When encountering a problem whose input is meant to be read sequentially, *but you may also want to push back onto the input like a stack*, which languages have the optimal boilerplates for doing so, and how?
For example, from [Create a Boolean Calculator](https://codegolf.stackexchange.com/questions/207084/create-a-boolean-calculator), we have a string like:
```
1AND0OR1XOR1
```
We want to "pop" 5 chars `1AND0`, compute it to be `0`, then "push" it back to form:
```
0OR1XOR1
```
Then, repeat until there's only 1 char left. In this case:
```
0
```
It's trivial to write `while` loops and such, but this seems common enough in codegolf problems that there must be canonical forms. I wasn't able to find a [tips](/questions/tagged/tips "show questions tagged 'tips'") question specifically about this setup though, and going through each [tips](/questions/tagged/tips "show questions tagged 'tips'") question by language was difficult.
[Answer]
The approach you're asking seems like reduce/left fold in general. Many languages have this, such as Python (`reduce(f,seq)` or `functools.reduce(f,seq)`), APL (`f⍨/⌽seq`), Jelly (`f/seq`), and Haskell (`foldl f start seq`).
As a Python example, let's assume we already have the input parsed as a list `seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]`. Then `reduce(f,seq)` is equivalent to
```
f(f(f(f(f(f(1, 'AND'), 0), 'OR'), 1), 'XOR'), 1)
```
The trouble here is that we need to take 3 arguments at a time. A way this could be done is by grouping most of the sequence into pairs `seq2=[1, ['AND',0], ['OR',1], ['XOR',1]]`, so `reduce(f,seq)` would be equivalent to
```
f(f(f(1, ['AND',0]), ['OR',1]), ['XOR',1])
```
This could work well in Jelly because it has a builtin `s` that could help [split into pairs](https://tio.run/##y0rNyan8///hzlnFRkDi6KSHO2f8//8/2lBHQd3Rz0VdR8EAyPIPAjJAQhEQViwA) (output looks funny strings are internally lists of chars).
However, a loop-based approach would work better in Python by assigning to a slice of an array:
```
seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]
while len(seq)>1:
seq[1:3] = [f(*seq[1:3])]
print(seq[0])
```
This would output `f(f(f(1, 'AND', 0), 'OR', 1), 'XOR', 1)`.
As @AdHocGarfHunter notes in the comments, recursion is a good idea too:
```
# (ungolfed)
def r(s):
if len(s)>1:
return r(f(*s[:3]) + s[3:])
else:
return s[0]
```
APL has little boilerplate for this: `{1=⍴⍵:⊃⍵⋄∇(3↓⍵),f3↑⍵}` (`∇` is the recursion). Jelly does too, with `1` byte recursion.
] |
[Question]
[
# Introduction
I crochet a lot, and lately I've started writing crochet patterns. However, while I work very well from notes such as *rnds 2-6 (round number = x, original number of stitches = y): \*dc x-2 stitches, 2 dc in next stitch\* around (xy stitches)*, most published patterns spell out each row in more detail. I don't like writing out each individual row/round myself though, so I want to have a program do it for me.
# Challenge
The challenge is to write a program or function that takes three mandatory inputs (r, s, and y) and returns a string of the pattern.
## Inputs
The inputs can go in any appropriate order or format, just please point that out so others can run your code.
R is an integer corresponding to the number of rounds/rows (use whichever designation you want) to generate. S is a string corresponding to the type of stitch. This can be guaranteed to be one of the following strings: "tc", "dc", "hdc", "sc", or "ch". Y is the number of stitches in row/round 1, and the number of increases in each following row (for instance, if y=6, row 1 has 6 stitches, row 2 has 12 stitches, row 3 has 18 stitches, etc). In the general case: row x has xy stitches.
## Outputs
The output is a list of strings with length r, in the following pattern.
`O N: \*s in next N-2 stitches, 2 s in next stitch\* y times (NY stitches).`
To clarify: it should return r strings, in order from least row/rnd number to greatest row/rnd number. The first row/rnd should be row 1, and the last row should be row r. In the template, replace s and y with the matching inputs, and N is the row number of the current row (N isn’t an input, just an integer that represents the current row). O is used to denote one of the following strings, your choice: “Row”, “Round”, or “Rnd”.
Each line of output should be separated by a newline. The period is necessary and should follow the parentheses.
## Edge Cases
You can assume s is one of the listed strings. R will always be a positive integer, as will y.
You don’t have to do anything fancy for row 1, it can be `Row 1: \*s in next -1 stitches, 2 s in next stitch\* y times (y stitches).` Row 2 can also be outputted in the default format, as `Row 2: \*s in next 0 stitches, 2 s in next stitch\* y times (2y stitches).` Thusly, it can be outputted with a for loop. But, if you output rows 1 and 2 as `Row 1: s in next y stitches (y stitches).\nRow 2: 2 s in next y stitches (2y stitches).`, you can have -10% or -10 bytes, whichever is smaller, removed from your score.
## Scoring
This is code golf, so fewest bytes wins. If you output rows 1 and 2 as shown in the Output section above, your score is lowered by -10% or -10 bytes, whichever is smaller.
# Example Input and Output
Input [the format doesn’t matter so much as the answer, so it could be any format the language supports]: (r,s,y)
>
> 1. (5, “dc”, 6)
> 2. (3, “sc”, 1)
> 3. (6, “hdc”, 100)
> 4. (0, “ch”, 1)
> 5. (5, “tc”, 0)
>
>
>
Output [this format must be fairly exact, hyphens are used to show negative numbers]:
>
> 1. `Row 1: \*dc in next -1 stitches, 2 dc in next stitch\* 6 times (6 stitches).\nRow 2: \*dc in next 0 stitches, 2 dc in next stitch\* 6 times (12 stitches).\nRow 3: \*dc in next 1 stitches, 2 dc in next stitch\* 6 times (18 stitches).\nRow 4: \*dc in next 2 stitches, 2 dc in next stitch\* 6 times (24 stitches).\nRow 5: \*dc in next 3 stitches, 2 dc in next stitch\* 6 times (30 stitches).`
> 2. `Rnd 1: \*sc in next -1 stitches, 2 sc in next stitch\* 1 times (1 stitches).\nRnd 2: \*sc in next 0 stitches, 2 sc in next stitch\* 1 times (2 stitches).\nRnd 3: \*sc in next 1 stitches, 2 sc in next stitch\* 1 times (3 stitches).\n`
> 3. `Rnd 1: \*hdc in next -1 stitches, 2 hdc in next stitch\* 100 times (100 stitches).\nRnd 2: \*hdc in next 0 stitches, 2 hdc in next stitch\* 100 times (200 stitches).\nRnd 3: \*hdc in next 1 stitches, 2 hdc in next stitch\* 100 times (300 stitches).\nRnd 4: \*hdc in next 2 stitches, 2 hdc in next stitch\* 100 times (400 stitches).\nRnd 5: \*hdc in next 3 stitches, 2 hdc in next stitch\* 100 times (500 stitches).\nRnd 6: \*hdc in next 4 stitches, 2 hdc in next stitch\* 100 times (600 stitches).\n`
> 4. This can error, or not produce any output, or anything. R will always be positive and nonzero.
> 5. This can either error OR produce `Rnd 1: \*tc in next -1 stitches, 2 tc in next stitch\* 0 times (0 stitches).\nRnd 2: \*tc in next 0 stitches, 2 tc in next stitch\* 0 times (0 stitches).\nRnd 3: \*tc in next 1 stitches, 2 tc in next stitch\* 0 times (0 stitches).\nRnd 4: \*tc in next 2 stitches, 2 tc in next stitch\* 0 times (0 stitches).\nRnd 5: \*tc in next 3 stitches, 2 tc in next stitch\* 0 times (0 stitches).`
>
>
>
Suggestions for more test cases welcomed! Please let me know how to improve it. If you have an input/output that produces a pattern you like, add it to your answer and maybe I’ll crochet it when I have time.
Ungolfed solution in Python 2: [Try it online](https://tio.run/##VY7BDoIwEETvfMVmTy1UIiRcTPgFDl7VA8EqTbA07Rrt19cWMNHb7MzbyRhP46zrEPpWafMkxktnJkUMBfLMRpNYf9pfeOZaRzbqKmq/@XXUt9lCB0qD7fVdMssPGUxKyxaP8wuwSF9dUfECD5DHs8AEa/mmb7hLIThSNIzSCajhH1uTfMN9gkk9pAO2Okt97n9LeHnWmIGxceeyJgRsxHUQDX4A)
[Answer]
# perl -M5.010 -a, 124 bytes
```
say"Row $_: \\*$F[1] in next ${\($_-2)} stitches, 2 $F[1] in next stitch\\* $F[2] times (${\($_*$F[2])} stitches)."for 1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIpKL9cQSXeSiEmRkvFLdowViEzTyEvtaJEQaU6RkMlXtdIs1ahuCSzJDkjtVhHwUgBVRFEBqgXJG4Uq1CSmZtarKAB0asFFkPSr6mnlJZfpGCop6cS//@/mUJGSrKCoYHBv/yCksz8vOL/ur6megaGBv91EwE "Perl 5 – Try It Online")
Pretty trivial. The bulk of the program consists of the line which needs to be printed, with some variable interpolation.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 132 bytes
```
^\d+
*
Lv^$`(_+) (.+) (.+)
Row $.1: \$\*$2 in next $1 stitches, 2 $2 in next stitch\$* $3 times ($.($3*$1) stitches).
__(_*)
$.1
_
-1
```
[Try it online!](https://tio.run/##TYy9CsIwFIX3@xRnuEKSakgs7eALuDg5l6aSBprBCiaobx8DirgcON/5uYcc14stG3GcyjjMDSk6PUaehGskhP4KnW9PsLYHDKx4j7hiDa8Mtkg5Zr@EtMUef8kH1za4RY7XkCBYC24VW/kbSU3OCack1XNytLOldJg9emqRPCz1WKq1xpCBXyrokD3MGw "Retina – Try It Online") Takes input in the order `r`, `s`, `y`. Explanation:
```
^\d+
*
```
Convert `r` to unary.
```
Lv^$`(_+) (.+) (.+)
```
Count down from `r` to `1`, then reverse the results, and substitute in the output pattern:
```
Row $.1: \$\*$2 in next $1 stitches, 2 $2 in next stitch\$* $3 times ($.($3*$1) stitches).
```
`$.1` is the row, `$*` is a literal `*`, `$2` is `s`, `$1` is the row in unary, `$3` is `y`, and `$.($3*$1)` is the product of the row with `y` (in decimal).
```
__(_*)
$.1
```
Subtract 2 from the row for the final substitution.
```
_
-1
```
Fix up the first row.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 62 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
EN³*³²NͲN“ ÿ: \*ÿ€†‚š ÿÀŠ, 2 ÿ€†‚šïŠ\* ÿ„Æ (ÿÀŠ).“'w't:'¢ã™ì,
```
Input in the same order as the challenge description, as three loose inputs \$r,s,y\$.
I've used `Row` for the optional first word, although `Round` and `Rnd` could both also be used for the same byte-count, by replacing `'¢ã™` with `'퉙` or `…Rnd` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f/f1e/QZq1Dmw9t8jvcCyQeNcxROLzfSiFG6/D@R01rHjUseNQw6@hCoNjhhqMLdBSMFFDED68/uiBGCyTWMO9wm4IGRJmmHtAY9XL1Eiv1Q4sOL37UsujwGp3//025UpK5TAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJYaH/Xf0itSIj/A73Rvg9apijcHi/lUKM1uH9j5rWPGpY8Khh1tGFQLHDDUcX6CgYKaCIH15/dEGMFkisYd7hNgUNiDJNPaAx6uXqJVbqhxYdXvyoZdHhNTr/aw9ts/8fHW2qo5SSrKRjGqujAGObgdjGOkrFQLYhiG2mo5QBkjA0MABxDXSUkjOgUkAtJUAZg9hYAA).
**Explanation:**
```
E # Loop `N` in the range [1, (implicit) first input `r`]:
N³* # Push `N` multiplied by the third input `y`
³ # Push the third input `y`
² # Push the second input `s`
NÍ # Push `N-2`
² # Push the second input `s` again
N # Push `N`
“ ÿ: \*ÿ€†‚š ÿÀŠ, 2 ÿ€†‚šïŠ\* ÿÀŠ (ÿ„Æ).“
# Push dictionary string " ÿ: \*ÿ in next ÿ switches, 2 ÿ in next switch\* ÿ times (ÿ switches).",
# where the `ÿ` are automatically replaced with the values on the stack
'w't: # Replace all "w" with "t" ("switch" to "stitch")
'¢ã '# Push dictionary string "row"
™ # Titlecase it to "Row"
ì # Prepend it in front of the string
, # And output it with trailing newline
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“ ÿ: \*ÿ€†‚š ÿÀŠ, 2 ÿ€†‚šïŠ\* ÿ„Æ (ÿÀŠ).“` is `" ÿ: \*ÿ in next ÿ switches, 2 ÿ in next switch\* ÿ times (ÿ switches)."` and `'¢ã` is `"row"`.
] |
[Question]
[
# Challenge
## Premise
I've got multiple pretty numbers all in a row. Each is a decimal digit.
0s are weakly attracted to 0s, 1s are attracted to 1s a little more strongly and so on until 9. I don't know *why* — it must be something I ate. As a result, a sort of two-way sideways sedimentation occurs until the higher values are closer to the middle and the lower values closer to the sides.
Specifically, this happens:
1) Find all instances of digits having the highest value. If there's an even number \$2p\$ of them, go to step 2a. If there's an odd number \$2q+1\$ of them, go to step 2b.
2a) Consider the \$p\$ instances on the left and the \$p\$ instances on the right. Continue to step 3.
2b) Consider the \$q\$ instances on the left of the middle instance, and the \$q\$ instances on its right. Continue to step 3.
3) Each member of the former subset will move right by swapping places with the digit directly on its right *as long as this other digit is smaller*, and members of the latter subset will move left in a similar fashion. All such swaps happen simultaneously. If exactly one lower-value digit is enclosed by two high-value digits (one on each side), always move this lower-value digit to the right instead.
4) Repeat step 3 until all digits of this value are directly side-by-side.
5) Repeat steps 1 to 4 for smaller and smaller values until the values are exhausted.
Here's a detailed example.
```
2101210121012 | begin
1201120211021 | four 2s; the two on the left move right, the two on the right move left
1021122011201 | conflict, resulting in change from 202 to 220 (see step 3); meanwhile,
the two other 2s move inwards
1012122012101 | no remarks
1011222021101 | no remarks
1011222201101 | 2s are done
0111222210110 | six 1s, but exactly one on the left of the chain of 2s moves right, and
exactly two on the right move left. observe 1s can never pass through 2s
because 2 is not smaller than 1 (see step 3)
0111222211010 | no remarks
0111222211100 | end; 1s and 0s are done at the same time
```
Let's find the end state with the power of automation!
## Task
Input: an integer sequence where each element is between 0 and 9 inclusive. The sequence is of length \$3\leq n\leq10000\$.
Output: in any format, the end state that would be reached by following the instructions in the section 'Premise'. Shortcut algorithms that give you the correct answer are allowed.
### Examples
```
Input -> output
0 -> 0
40304 -> 04430
3141592654 -> 1134596542
2101210121012 -> 0111222211100
23811463271786968331343738852531058695870911824015 -> 01111122233333333445556666777888888999887554211100
```
# Remarks
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/), [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* If possible, link an online demo of your code.
* Please explain your code.
[Answer]
# JavaScript (ES8), 186 bytes
A direct transformation of the input.
```
s=>(g=s=>s.join``)([...b=g((a=s.split(n=Math.max(...s)))[S='slice'](0,(k=a[L='length'])/2))+(m=a[k>>1])[S](0,k&1&&m[L]/2)].sort())+''.padEnd(k-1,n)+g([...g(a)[S](b[L])].sort((a,b)=>b-a))
```
[Try it online!](https://tio.run/##bY49b4MwEED3/owMcKeA68MYnMFs3dKpI0KK@QghgIliVPXfUzdSO1QZfMN776y7mk/jmvtwW2O7tN121pvTBfTaT8euy2BPJ4SSMVbrHsBox9xtGlaw@t2sFzabL/DSIWL5oUM3DU0XVsAjGLUpjzqcOtuvl7DC1wRxD7OnY1FQ5fOfbAwoCObyWHldMbfcV/BZGLKbad9sC2NMkcV9/zihB/NYq33/W4OJatRFHRvErVmsW6aOTUsPZ9jxHeLLP5ZywdMnXFBK8pBk8plMiNPfe@aFIkozkeSUq@yQKSFIpCIXSslECuLSU6lyfiBSScpJ@k@2bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
MÆṁ$ĊœṖ⁸Ṣ€U2¦;/
```
A monadic link accepting a list (of any orderable items) which yields a list.
**[Try it online!](https://tio.run/##y0rNyan8/9/3cNvDnY0qR7qOTn64c9qjxh0Pdy561LQm1OjQMmv9////KxkZWxgampgZG5kbmluYWZpZGBsbGpsYmxtbWJgamRobGpgCRU0tzA0sDQ0tjEwMDE2VAA "Jelly – Try It Online")**
[Answer]
# [J](http://jsoftware.com/), 44 42 bytes
```
(/:~@{.,\:~@}.)~[:(#{2#]<.@-:@+|.)@I.>./=]
```
[Try it online!](https://tio.run/##ZVDLbsIwELznK1ZwgKjE@JkYi6BISEhInLi2nCoQ6qUfwOPXw3jtiBY0cvYxk1mvf/qRmJyoDTShGUkKOJWg9X636afzcO8uYvaFcBPl/TNMxxc9PixFV4Xu4yrKbitWYt4e@rI4fp9/ydMC8NRQFeiUy4Z8kWhJLbpyKCxg4ryotUgMNxOtAIPKwaHG15JOQgPC4kRCJ2owVAydkSo5DNBcqPf4/@@ng3mB5dtE1BkNw//BIj9AfAKXb/12DwNa8RY1cg2pYpuaV/U8LC1v0Dds56Bz3JeISet4jEQW3TwUltdwVPQP "J – Try It Online")
The meat of the problem is finding the right point to split the input.
After that, you just sort the left side up and the right side down, and cat them together (`/:~@{.,\:~@}.`).
We'd like to avoid treating "odd number of max elements" and "even number of max elements" as two special cases.
To do this, notice that given the indices of the max elements (`I.>./=]`), you can add that list elementwise with its reverse and average each element (`]<.@-:@+|.`).
Next, duplicate each element of *that* list in place (`2#`), and pull from the result the element at index "length of original list" (`#{`).
All together, this gives us the "midpoint" of the original list, where "midpoint" is defined as "the actual midpoint" in the odd case, and "the average of the two middle-ish" elements in the even case.
This is exactly where the algorithm tells us to split the input.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 135 bytes
```
$
¶¶$`¶
O`\G.
+`((.)¶.*)¶(.*?\2)(.*)(\2.*)¶
$1$3¶$4¶$5
((.)¶.*)¶(.*)\2(.*)¶
$1$3¶$2¶$4
1A`
+`¶(.)(.*)(.)¶
$1¶$2¶$3
2=`¶
%O^`.
O`\G.
¶
```
[Try it online!](https://tio.run/##VY49DsIwDIV3nyOVkiJFsZ2/DggxdewFIhQGBhYGxNlygFwspLRC6vBs2f787Pfj83zd2yDn3ATUUovItcCS06zhlKXUqhY99iD1eEmkelIy0a8FAgX3Ddvl4MiqRPIA0QoCXnO3XYnNSW/EPmeg83oehuWW9f5Fr1szYA0bC4wW3UTeWSA0@BcQR0TrmQKG6CcfmZEtB47RkWM0rnddDGZCjGQNui8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶¶$`¶
```
Make a working area with a copy of the input surrounded by blank lines.
```
O`\G.
```
Sort the digits of the original input.
```
+`((.)¶.*)¶(.*?\2)(.*)(\2.*)¶
$1$3¶$4¶$5
```
Move minimal suffixes and prefixes of the copy of the input to the blank lines. Each moved minimal suffix must end with the largest digit and each moved minimal prefix must start with the largest digit.
```
((.)¶.*)¶(.*)\2(.*)¶
$1$3¶$2¶$4
```
If there is an odd number of the largest digit, move its exclusive prefix and suffix too.
```
1A`
```
Delete the sorted copy of the digits.
```
+`¶(.)(.*)(.)¶
$1¶$2¶$3
```
If there was an even number of the largest digit, move individual digits from the remainder of the copy of the input to the prefix and suffix areas.
```
2=`¶
```
Move the last digit (if any) or the odd largest digit to the suffix.
```
%O^`.
```
Sort both the prefix and the suffix descending.
```
O`\G.
```
Reverse the prefix.
```
¶
```
Join the prefix and suffix together.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
≔⌕Aθ⌈θη≔…θ÷ΣE²§η÷⁻Lη鲦²η⭆χ×Iι№ηIι⮌⭆χ×Iι⁻№θIι№ηIι
```
[Try it online!](https://tio.run/##fY7RaoQwEEXf@xU@TsAFkxjN0iexFBYqLLv9gaDBBGJcTZTt16cRd2kfSgeGgTv3nplWibkdhQmhck73Ft617SpjYEqTRtz1sAwwIZQmCr2@PCz1V2tkrcbbZjpZ/6ZX3Um4RmsjbkDSpPIn28k7qN/7RtvFwYe0vVegIlLHJgihfewnzrO2Hq4@jn6D4SxNPvUgHdTCedgi9bhES0Q/lK2ewYtc5ezk/4D9kR0z/WD@Jkd2CIRyjPOCkhKXvDgWnFJMc1pSzhlhFGcsqoyX2RFjTvIMs3BYzTc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌕Aθ⌈θη
```
Find all the positions of the maximum digit.
```
≔…θ÷ΣE²§η÷⁻Lη鲦²η
```
Take the average of the middle two (or the middle position duplicated if there are an odd number of positions) and chop the input to this length.
```
⭆χ×Iι№ηIι
```
Sort the chopped input. (Because we know the range of characters, we just repeat each character by the number of times it appears in the desired string.)
```
⮌⭆χ×Iι⁻№θIι№ηIι
```
Calculate the number of each digit remaining to give the sorted remainder, and then print that reversed so that the sort is descending.
] |
[Question]
[
[Pure data](https://puredata.info/) is a graphical programming language designed for audio processing. This makes it unsuitable for most general programming but especially unsuitable for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
It would then be nice to have a [tips](/questions/tagged/tips "show questions tagged 'tips'") question so that people can get a first foot up in this language.
What tips are there for golfing in Pure Data? Answers should apply specifically to Pure Data.
[Answer]
## Use a text editor
The editor that comes with Pure Data is really useful for making programs that work or helping you to understand existing programs. However if you want to golf, the files it creates are full of extra stuff that can be removed with an text editor (e.g. vim).
This post will serve as a list of a bunch of small byte saving tricks accessible only through or more easily though a traditional editor.
* **Use defaults on `canvas`:** Your file needs a canvas line. `#N canvas;` is enough to get things to run without error. The missing arguments default to zero.
* **Newlines are optional:** The graphical editor puts newlines between statements. Presumably to make these files somewhat readable. However these are not strictly required and can be removed with an editor.
* **Rearrange your objects for better object indices:** Since connections identify objects by their order in the source, placing objects with a lot of connections earlier in the file can shorten your source. Make sure that you update all the references once you reorder.
* **Put everything in the top left:** Since object location is purely a graphical aid, you can place them wherever. Single digit locations are the shortest so changing the location to `0 0` or something similar will save you. This turns your code into an unreadable blob so it is probably best to do this once everything already works.
[Answer]
# Avoid using `trigger`s to sequence messages
One of the common uses of `trigger` objects is to make the order of execution clear when a single object is sending messages to multiple places. In those cases, since code readability is not a concern for us, you can depend on Pure Data's default behavior which is to send the messages across connections in the order that the connections were created (or if you are [using a text editor](https://codegolf.stackexchange.com/a/201343), the connection that appears first in the file).
] |
[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/197117/edit).
Closed 4 years ago.
[Improve this question](/posts/197117/edit)
This is kept fairly original:
Write a program that creates a standard blackjack game:
* input "h" means hit or draw another card
* input "s" means stand, or take what you have already
Rules:
* cards values are as follows:
* 2-9 = face value of card
* 10, J, Q, K = 10
* aces = 11 unless player busts, then it's only a 1
* if 2 or more aces are drawn the first is 11, and each one after is a 1
* the bank needs 18-21, and has to draw another card until they are in this range
* this game runs forever
Procedure:
+ The player gets 2 cards at the beginning, shown by "Player:" in the console
(Example: Player gets 2 and 5 at the beginning. Console output: "Player: 2, 5").
+ The cards can be shown in the console by their values
(For example: 2, 10, 1 | No need for: 2, K, A), but you can also use
the card-names instead. Your choice
+ The input by the player is "h" for "hit" and "s" for "stand". Also allowed is 1 and 0
+ The bank gets one card at the beginning, shown by "Bank:"
+ At the end you get the output "Win", "Lose", "Draw",
or "Blackjack", depending on the game
This game is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~574~~ \$\cdots\$ ~~338~~ 337 bytes
```
from random import*
e,L,B,P=exit,"Lose","Bank:","Player:"
d=[*range(2,12)]*4+[10]*12
c=d.pop
def h(l,m):
l+=[c()]
if sum(l)>21and 11in l:l[l.index(11)]=1
print(m,*l);return sum(l)
shuffle(d)
b=[]
t=h(b,B)
p=[c()]
u=h(p,P)
u>20<e("Blackjack")
while'h'==input():u=h(p,P)
u>21<e(L)
while t<18:t=h(b,B)
22>t>u<e(L)
u==t<e("Draw")
e("Win")
```
[Try it online!](https://tio.run/##TU49b4MwFNz9K17pEJtYUUw7VDRmQB0zZOuAGAiY4sTYlj@U5NdTV0VVh9Od3ru79@wjTEa/LHK2xgXwD48Sdj4Mwjm@ShMDPMMl@mQwIAMoY64etOwFSA1BmqdldGYG1@kh0W9ZjgQ90pqeuLjLQLOj8SKjWd3pa5n4pLqHcGWGBt7kKfglcEFZQdr8dduwfZuzAvV82Flj0SBGmLCiMykRqC1vekxaBHIEH2esSFWwdBkYS9@oUjVqJ/Ug7pgx0nKGwDqpA55prsi7EyE6vQaRn@I4KoEHgs68aVHgEz7TmiC7HolpYOmJoFgV@4PAWa26/npJyAi6TVKJzbThXGobAyblfztL9uNqgnBgb@Vfe1FUoYq/@8h5@Cn@cN0tdSb1KXVGlmVCHn0D "Python 3 – Try It Online")
Saved 34 bytes thanks to @ReinstateMonica!!!
] |
[Question]
[
You are given two arbitrary integer lists, e.g. `[-10, 99, -6, 43]`, `[100, 32, 44]`. You are to pick one integer from each list and sum them up, then sort the best pairs ordered by the absolute distance to 100 in ascending order. Paired up integers from each list shall not be repeated in the output.
For instance, we have
| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 100) | 100 - (-10 + 100) | = 10 |
| (-10, 32) | 100 - (-10 + 32 ) | = 78 |
| (-10, 44) | 100 - (-10 + 44 ) | = 66 |
| (99, 100) | 100 - (99 + 100 ) | = 99 |
| (99, 32 ) | 100 - (99 + 32 ) | = 31 |
| (99, 44 ) | 100 - (99 + 44 ) | = 43 |
| (-6, 100) | 100 - (-6 + 100 ) | = 6 |
| (-6, 32 ) | 100 - (-6 + 32 ) | = 74 |
| (-6, 44 ) | 100 - (-6 + 44 ) | = 62 |
| (43, 100) | 100 - (43 + 100 ) | = 43 |
| (43, 32 ) | 100 - (43 + 32 ) | = 25 |
| (43, 44 ) | 100 - (43 + 44 ) | = 13 |
After pairing with the first item `-10`, it is tempted to pick the pair `(-10, 100)` as the best pair as it has the least distance to 100. But further checking down the list, `(-6, 100)` in fact has a lesser distance to 100, hence it should be the best pair picked. After picking the pair, they are removed from their lists, leaving us
| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 32) | 100 - (-10 + 32) | = 78 |
| (-10, 44) | 100 - (-10 + 44) | = 66 |
| (99, 32 ) | 100 - (99 + 32 ) | = 31 |
| (99, 44 ) | 100 - (99 + 44 ) | = 43 |
| (43, 32 ) | 100 - (43 + 32 ) | = 25 |
| (43, 44 ) | 100 - (43 + 44 ) | = 13 |
Then next pair to pick will be `(43, 44)`. Notice that the distance to 100 is 13 for this pair, which is higher than the pair `(-10, 100)`, but only because `100` has been paired with `-6` and hence the pair `(-10, 100)` is gone. Moving on, we have these remaining
| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 32) : | 100 - (-10 + 32) | = 78 |
| (99, 32 ) : | 100 - (99 + 32 ) | = 31 |
And finally `(99, 32)` is picked. Hence the output `(-6, 100), (43, 44), (99, 32)`. Ignore the rest that have nothing to pair up.
*Note: when there is a tie, just pick any pair, without worrying the consequence to the remaining candidates.*
The challenge here is to complete the task with the least number of comparisons operating on the inputs. i.e. if all comparison result has to come from a function `comp(a, b)`, then the least number of call to this function wins. Looping control etc. are not included. Three way comparison is essentially 2 operations. General purpose code only and no special purpose optimisation is required. Favour code that can verify the number of comparison calls, however, when using build in functions, please explain their complexity for us to examine.
[Answer]
## Python O(mn log mn)
The best pairs can be found computing the distances of all the possible pairs, and iteratively choosing the best pair among those remaining after filtering out the already chosen items.
A simple implementation is shown in the following code:
```
def find_nearest_pairs_to_100(l, m):
pair_list = sorted([((i, j), abs(100 - i - j)) for i in l for j in m], key=lambda x: x[1])
chosen_pairs = []
while pair_list:
best_pair = pair_list[0][0]
chosen_pairs.append(best_pair)
pair_list = [(p, s) for (p, s) in pair_list if p[0] != best_pair[0] and p[1] != best_pair[1]]
return chosen_pairs
```
The `find_nearest_pairs_to_100` function takes the two lists in input and returns an ordered list with the chosen pairs.
The `sorted` function in Python is based on [Timsort](https://en.wikipedia.org/wiki/Timsort) algorithm, that requires O(n log n) comparisons in the worst case (where n is the length of the list).
In this case the length of the list is the cardinality of the Cartesian product of the two input lists, i.e. mn (with n > m). Therefore, the total cost of this implementation is of O(mn log mn) comparisons, excluding the other comparison operations needed for filtering.
Including comparisons for filtering, at each iteration, in the worst case, all the items of the list are checked against the elements of the chosen pair; the length the `pair_list` is mn at the first iteration, (n-1)(m-1) at the second, (n-2)(m-2) at the third, and n-m+1 at the last step. So the total number of comparisons for filtering is O(n^3).
If you like golfing, it is a golfed version (163 bytes) of the previous one (a little bit different):
```
f=lambda l,m:l and m and[[k]+f(l.remove(k[0])or l,m.remove(k[1])or m)for k in sorted([[[[i,j]],abs(100-i-j)]for i in l for j in m],key=lambda x:x[1])[0][0]][0]or[]
```
] |
[Question]
[
(Note: I'm not in the army so feel free to correct me if my formation is wrong, but I will not be changing the question. I will change any terminology mistakes though, because I'm trying to avoid air-cadet-specific wording choices)
(Note: this follows the standards for Canadian Air Cadets, not any actual army thing)
# Challenge
Given some configurations for a squadron, output what it should look like.
You will use 1 non-whitespace character to represent people.
### Configuration
The configuration will consist of a mandatory non-empty list, a mandatory positive integer, and an optional positive integer. The list represents the number of people per "squad", the mandatory integer represents the maximum number of rows, and the optional integer represents the number of "squads" in the squadron; in other words, the length of the list.
Each squad looks like this (without the commanders):
```
X X X X X
X X X X
X X X X
```
This would be a squad with 13 people in 3 rows.
A squad must be strictly wider than it is tall, unless it's a single person, in which case it's 1 × 1. It must also be as tall as possible (within the restriction for the number of rows); that is, once it is one larger than a perfect square, it should form another row. An exception is that when there are 5 people, it should still be a single row.\*\* The gap is always placed in the second column from the left, starting from the second row and moving downwards. For example, with 28 people and 5 rows maximum:
```
X X X X X X
X X X X X
X X X X X
X X X X X X
X X X X X X
```
Then, after the squad is formed, a commander is to be placed 2 rows above and below the squad, in the exact centre. For odd width squads:
```
X
X X X X X
X X X X X
X X X X X
X
```
And for even width squads:
```
X
X X X X
X X X X
X X X X
X
```
Hopefully you now understand how an individual squad is formed. Then, to form a squadron, each squad has 7 blank columns between it. For example, with a maximum row count of 3 and three squads of size 15, 16, and 17:
```
X
X X X
X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
X X X
```
Then, in the final step, a commander is placed two rows above the row of front commanders, directly in the centre of the squadron, to the left if it has even width. In the example above, that would be the `X` at the very top.
The final output may contain trailing whitespace on each line and an optional trailing newline.
Here's a reference implementation: [Try It Online!](https://tio.run/##jVNNj9owEL37V0y1hyQsEALaboXKoULqqYdeKlVKc/ASk7hK7OA4BX49nbGThdBt1RzAno/33ny4OdtSq9Xl8vAu7loTv0gVC/ULGm9nDzCbzEConc6lKtbQ2f0HMjEWBAH7pgpd7UUOX104YJRgW92cjSxKC58qceIqFwa@SK4h3EWwXCTPbLtdoGUnVCvW8NkIAV3LCwF6D7aULTRGF4bXoA1wdSaztC2C141WQuHxKJGus8CtNfKlsxK5jTh00ojcCWMSY42FmtuSsfbQ8byFDUhlQ6mazoZRxGp@Mvp4b93pjhg2kN6aYY9aJJZywl8wXBUiTKbQAz9CEmUMwarWUmYtVejRp5CA3EMjdFMJ2GzgCUTVCkdJ2ubtwdiwd88QJqKiE8/XmyX1lURl7ChzWzpxLnknZBV6X@rEZRCDl9Hf3xTuVaNibgw/O7g0TVzkTZTnGnAy5z5f3WOa7J88r53GA5bdhJVQU/Ds2HJGue5Gud68ZoDfsZTYAIwOnTWCj@CxvJs@55jzphEqD9NFBpNrPF4H@LeleRjyk77bySY41FGJiDvqCE5r1PnoTtJgTxElS5MMq18w3K66di/CdT0ICNZr8TLd@S8yr7mpsxNk8D3ALVBWmPC16sFN1SP80u0Vo/W8IfVt9KSj2r2jp6QcVwBR9dUF858a9zsNhhNqoB3f6crvNjpcS8kwzNOB@GW8G3SG0lxj79eDuHF6jaG3EhLoBPxSQhzDEl/KI5U/RAz/dzKvTYv@iPyh@qAR1X8AXS4rtmLJE0ves@T5Nw) (Python 3)
# Input
Input will be given in any flexible format with the 3 components listed above: `list, int[, int]`.
# Rules
* Standard loopholes apply
* Output must be in this exact format (of course, you may choose the character to use)
* Newline may be CR, LF, or CRLF
* Trailing whitespace is allowed
* Trailing newline is allowed
\*\*Except our squadron's Flag Party formed a 3x2 pseudorectangle :P
[Answer]
# [Python 3](https://docs.python.org/3/), 308 314 309 305 269 bytes
Input is the number rows in a squad and a list with a single integer for each squad, indicating the number of persons in the squad.
Could probably be golfed quite a bit.
**Edit:** +6 bytes, fixed a bug for squads with the same number of persons as rows
**Edit:** -6 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
**Edit:** -36 bytes by combining everything to one function
```
def z(r,l,v=" ",z="X "):q=[z,v]+[(v*6).join(([z.center((w//r+(w%r>0))*2),v]+[r*[z],[z+[z,v*2][I*w%r and r>=w%r+I]+z*(w//r+(w%r>0)-2)for I in range(r)]][w>r]+[v,z.center((w//r+(w%r>0))*2)])[i]for w in l)for i in range(r+4)];return"\n".join(p.center(len(q[2]))for p in q)
```
[Try it online!](https://tio.run/##dY/BSsNAEIZfZVkQZnanrSS1ByW55w2EcQ/FbjUSJsmQJrgvH5OIoAdvc/i@72e6z@G9lXyeL/FqEig1NBbWWEqFfTYWH/uCE43BM4zuhPuPthYATvvXKENUgOlwUA/TnZb3iC7DjVXHKRAnv7ouC1y5hTBnuRgti@X0VfDJ/ZF3GV5bNZWpxehZ3iIohsBTqUtwpP8XA3IdVnVa1War1L8q/ojhSeNwU7EvYr9f6H5yTRToOQu4ed3q9Th3WssACXLinI70QKcFmL8A)
[Answer]
## Batch, 628 bytes
```
@echo off
call:s 1 %1 %4
call:s 2 %2 %4
call:s 3 %3 %4
set s=%s1%X%s1% %s2%X%s2% %s3%X
echo %s1% %s2% %s3%X
echo(
echo %s%
echo(
for /l %%i in (1,1,%4)do call:r %%i
echo(
echo %s%
exit/b
:q
set/ah=h%1,f=f%1
call set x=%%x%1%%
if %2 gtr %f% set x=X %x:~3%
if %2 gtr %h% set x=%x:X= %
set r=%r%%x%
exit/b
:r
set r=
for %%j in (1 2 3)do call:q %%j %1
if not "%r: =%"=="" echo %r%
exit/b
:s
set h=%3
if %2==5 set h=1
:t
set/aw=~-%2/h+1
if %w% leq %h% set/ah-=1&goto t
set x=X
for /l %%i in (2,1,%w%)do call set x=%%x%% X
set/ah%1=h,f%1=%2-h*~-w
set x%1=%x%
set s%1=%x:X=%
```
Takes the three squad sizes and the height as parameters. Explanation:
```
call:s 1 %1 %4
call:s 2 %2 %4
call:s 3 %3 %4
```
Calculate the dimensions of each squad.
```
set s=%s1%X%s1% %s2%X%s2% %s3%X
```
Calculate the squad commanders. The `sN` variables hold a number of spaces equal to half the width in characters of the squads rounded down, so adding this on both sides centres each commander.
```
echo %s1% %s2% %s3%X
echo(
```
Calculate and output the position of the front commander. This is similar to the case of the individual commanders except for the additional spacing between the squads, which has to be rounded up to allow for the `sN` being rounded down.
```
echo %s%
echo(
```
Output the first row of individual commanders.
```
for /l %%i in (1,1,%4)do call:r %%i
```
Output the squads.
```
echo(
echo %s%
exit/b
```
Finish by outputting the second row of per-squad commanders.
```
:q
set/ah=h%1,f=f%1
call set x=%%x%1%%
```
Get the height, full width rows and full width cadet string for the squad.
```
if %2 gtr %f% set x=X %x:~3%
```
If this is not a full width row, remove the second cadet.
```
if %2 gtr %h% set x=%x:X= %
```
If all the rows have already been output, remove all the cadets.
```
set r=%r%%x%
exit/b
```
Add any remaining cadets to the overall row.
```
:r
set r=
for %%j in (1 2 3)do call:q %%j %1
if not "%r: =%"=="" echo %t%
exit/b
```
Given a row in `%1`, add each squad's cadets for that row and output the result.
```
:s
set h=%3
if %2==5 set h=1
:t
set/aw=~-%2/h+1
if %w% leq %h% set/ah-=1&goto t
```
Calculate the number of rows and columns for this squad.
```
set x=X
for /l %%i in (2,1,%w%)do call set x=%%x%% X
```
Calculate the full width cadet string for this squad.
```
set/ah%1=h,f%1=%2-h*~-w
set x%1=%x%
```
Calculate the number of full width rows and save all the results in per-squad variables.
```
set s%1=%x:X=%
```
Also calculate the half-width string for centring purposes.
] |
[Question]
[
## Introduction
*Don't worry - no knowledge in mathematics is needed. It is possible to just skip the motivation part, but I think it is nice if a puzzle has a background story. Since the title contains the number* I *there will be more puzzles of this kind, if you like them. Feedback is highly appreciated. I hope you have fun with this puzzle! :)*
[Sandbox-Answer](https://codegolf.meta.stackexchange.com/a/13232/70741)
---
## Motivation
Many processes in the real life can be modelled with differential equations.
A differential equation is an equation contain some differential expression, e.g.
```
x'(t) = λx(t)
```
This is a ordinary (= 1D) differential equation (ODE). And the solution to this is simply `x(t) = x₀e^{λt}` for any `x₀∈ℝ`. This ODE can be used as model for population growth (rabbits multiplying exponentially) or radiation decay. In both cases `x̧₀` is the initial population / initial amount of material.
Now not everything in the world of physics can be modelled with ODEs. Since we live in a multidimensional world there should be differential equations with more than just one component, right?
These equations are named partial differential equations (PDE).
For example flow fields can (in some cases) be modelled using the Stokes Equation:
```
-Δv + ∇p = f in Ω
∇∘v = 0 in Ω
```
where `v` is the velocity and `p` is the pressure of the flow. And `Ω⊂ℝ²` is just the geometry on which the equation is solved - e.g. a tube.
Now if you want to solve these equations there is a method called Finite Element Method. And this method requires a grid of your geometry. In most cases these grids contain [quadrilaterals](https://www.dealii.org/images/steps/developer/step-1.grid-2r2.png) or [triangles](https://fenicsproject.org/pub/images/800px-Fenics-plasticity-beam.png).
For this `code-golf` we will use a very simple grid:
```
(0,1) (1,1)
x-----x-----x-----x-----x
| | | | |
| 1 | 2 | 3 | 4 |
| | | | |
x-----x-----x-----x-----x
| | | | |
| 5 | 6 | 7 | 8 |
| | | | |
x-----x-----x-----x-----x
| | | | |
| 9 | 10 | 11 | 12 |
| | | | |
x-----x-----x-----x-----x
| | | | |
| 13 | 14 | 15 | 16 |
| | | | |
x-----x-----x-----x-----x
(0,0) (1,0)
```
This 2D-grid consists of 5x5 points in (2D) unit cube [0,1]×[0,1]⊂ℝ². Therefore we have 16 cells. The four Cartesian coordinates and the numbers in the cells are **not** part of the grid. They are just to explain the Input/Output.
There is a connection between the grid-size and the accuracy of the solution - the finer the grid the higher the accuracy. (Actually that is not always true.)
But a finer grid also has a draw-back: The finer the grid the higher the computation cost (RAM and CPU). So you only want to refine your grid at some locations. This idea is called `adaptive refinement` and is usually based on the behaviour of the solution - e.g. thinking about the flow problem above: refine that part of the grid, where the solution is turbulent, don't refine if the solution is boring.
## Task
The task is to implement this `adaptive refinement` in a general way.
Since we don't solve any PDE in this `code-golf` the criteria to refine grid cells is based on a circle disk. This circle disk is simply defined by the midpoint `p=[p0,p1]∈[0,1]²` and the radius `r ∈ [0,1]`.
Every cell intersecting with that disk (including boundaries - see Example 1) will be refined.
The output is the 5x5 grid above with the refined cells.
## Asked Questions
*What is the purpose of 'x'?*
'x' represents nodes/vertices, '-' and '|' edges.
Refinement of a cell means, that you split one cell into 4:
```
x-----x x--x--x
| | | | |
| | > x--x--x
| | | | |
x-----x x--x--x
```
## Examples
```
Input: p=[0,0] r=0.5
Output:
x-----x-----x-----x-----x
| | | | |
| | | | |
| | | | |
x--x--x-----x-----x-----x
| | | | | |
x--x--x | | |
| | | | | |
x--x--x--x--x-----x-----x
| | | | | | |
x--x--x--x--x | |
| | | | | | |
x--x--x--x--x--x--x-----x
| | | | | | | |
x--x--x--x--x--x--x |
| | | | | | | |
x--x--x--x--x--x--x-----x
The midpoint is located in (0,0) with radius 0.5.
Cell 13: Completely inside the cell.
Cell 9 : Intersects, since lower left corner has coords (0,0.25).
Cell 14: Intersects, since lower left corner has coords (0.25,0).
Cell 5 : Intersects, since lower left corner has the coordinates (0, 0.5).
Cell 15: Intersects, since lower left corner has the coordinates (0.5, 0).
Cell 10: Intersects, since lower left corner has the coordinates (0.25, 0.25).
The distance from (0,0) to that corner is √(0.25²+0.25²) < 0.36 < 0.5.
Cell 11: Does not intersect, since the closest point is the lower left
corner with coordinate (0.5,0.25), so the distance is
√(0.5² + 0.25²) > √(0.5²) = 0.5
Input: p=[0.5,0.5] r=0.1
Output:
x-----x-----x-----x-----x
| | | | |
| | | | |
| | | | |
x-----x--x--x--x--x-----x
| | | | | | |
| x--x--|--x--x |
| | | | | | |
x-----x--x--x--x--x-----x
| | | | | | |
| x--x--x--x--x |
| | | | | | |
x-----x--x--x--x--x-----x
| | | | |
| | | | |
| | | | |
x-----x-----x-----x-----x
The midpoint is located in (0.5,0.5) with radius 0.1.
Therefore the circle is completely inside the union of cells 6,7,10 and 11.
It does not touch any 'outer' boundaries of these four cells.
So the only refined cells are these four.
Input: p=[0.35,0.9] r=0.05
Output:
x-----x--x--x-----x-----x
| | | | | |
| x--x--x | |
| | | | | |
x-----x--x--x-----x-----x
| | | | |
| | | | |
| | | | |
x-----x-----x-----x-----x
| | | | |
| | | | |
| | | | |
x-----x-----x-----x-----x
| | | | |
| | | | |
| | | | |
x-----x-----x-----x-----x
Cell 2: Intersecting with the circle.
Cell 1: Not refined, since the right edge has x-coordinate 0.25 < 0.35-0.05 = 0.3.
Cell 3: Not refined, since the left edge has x-coordinate 0.5 > 0.35+0.05 = 0.4.
Cell 6: Not refined, since the top edge has y-coordinate 0.75 < 0.9 - 0.05 = 0.85.
```
## Rules
**Since this is my first puzzle / golf help is appreciated.**
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): Smallest byte size wins.
* Trailing / Leading whitespaces are allowed.
* The Cartesian coordinates are not part of the grid, and should not be seen in the output.
* Only allowed chars are '-', '|', 'x' and ' '
* Input: All three numbers will be floats. It does not matter if your input is a tuple `(p0,p1)` and a number `r`, or three numbers, or one array - just be reasonable.
[Answer]
# Charcoal, ~~107~~ ~~105~~ 106 bytes
```
F²«x⁵↷²x³↷»F³«C⁰±⁴C⁶¦⁰»F⁴«A⁻×⁴IθιεF⁴«A⁻×⁴Iηκ먪›⁺X⎇›ε¹⁻ε¹∧‹ε⁰ε²X⎇›δ¹⁻δ¹∧‹δ⁰δ²X×⁴I沫J⁺³×⁶ι⁻²×⁴κP|x|xP-x--x
```
[Try it online!](https://tio.run/##fZFdb4MgFIav9VcQrzDBxvnRZOtV04sty9qYxezeKFUyKw6wa7v52xmC/UyzhEPOged9OUBeZSynWS3lmjIAAxf82FbCSCOgs3Pc2bGIdUq2VLyTshIKnN3lwhtOlb2trUNtvaDtHvoIrHCZCQwjd@D14hQB/0xHmp5zTsoGLknTcZiSDeYwQmCRcQG/XBcBogIPDhea/0TVIPpUUQwii6wBXFEBnxlWzTCY1EqR0G@Vppg1GduftjACD0pnTMdi3hTwDXNd@7oTNQUq7lsUlxbFjUVhLApjcfa4av8w7rrmotZrt2lTatoOETDwdHiW0znBcTkaLq5f27KWXS1Iq//r6QMzQfKsRsDZ/ZqfvAZeKCMH2giDeN7I9LYavZT@JIxtf/Kowo@lt5Uer/8A "Charcoal – Try It Online") Link is to verbose version of code, not that it helps. Edit: Saved 2 bytes by handling the reversed sense of the Y-axis in a different way, but added a byte to handle a clarification in the question. Explanation:
```
F²«x⁵↷²x³↷»
```
Prints a cell. It does this by printing an `x`, then printing `5` (which expands to `-----` because the default cursor direction is right), then it rotates downwards, prints another `x`, prints `3` (which now expands to three `|`s downwards), then rotates left. Doing all that twice completes the cell.
```
F³«C⁰±⁴C⁶¦⁰»
```
There are four cells horizontally and vertically, so the cell needs to be copied horizontally and vertically three times. The vertical copy is done upwards to simplify the calculation below.
```
F⁴«A⁻×⁴IθιεF⁴«A⁻×⁴Iηκδ
```
The 16 cells are now looped over using a four by four nested loop. The coordinates of the midpoint are multiplied by 4, scaling them from 0 to 4, which corresponds to our loop indices which are subtracted, so the resulting variables are now relative to the cell's bottom left corner.
```
¿¬›⁺X⎇›ε¹⁻ε¹∧‹ε⁰ε²X⎇›δ¹⁻δ¹∧‹δ⁰δ²X×⁴I沫
```
The variables are now compared to the range 0 to 1 that represents the relative quadrupled cell coordinates. If they lie outside this range it means that the midpoint lies outside the cell, so the distance to the range is squared and the sum of the squares compared to the square of the quadrupled radius. If it is not greater, then the cell needs to be refined.
```
J⁺³×⁶ι⁻²×⁴κP|x|xP-x--x
```
The cursor is moved to the centre of the cell to be refined. The string `x|x` is printed vertically (both up and down), while the string `x--x` is printed horizontally (both left and right). (The middle `x`s overlap.)
] |
[Question]
[
**This question already has answers here**:
[Reversible hex dump utility (aka `xxd`)](/questions/11985/reversible-hex-dump-utility-aka-xxd)
(4 answers)
Closed 7 years ago.
Given an `xxd` hexdump such as this one:
```
00000000: 1f8b 0808 4920 2258 0003 7069 6c6c 6f77 ....I "X..pillow
00000010: 2e74 7874 00d3 d707 8218 10d0 2799 c545 .txt........'..E
00000020: ba96 41a1 994c 7d60 d650 d53c 44a3 8a22 ..A..L}`.P.<D.."
00000030: cd43 34aa 28d2 3c44 a38a 22cd 4334 aa28 .C4.(.<D..".C4.(
00000040: d20c 00fd 512d 46b8 0500 00 ....Q-F....
```
Reverse it to produce the original input:
```
I "Xpillow.txt����'��E��A��L}`�P�<D��"�C4�(�<D��"�C4�(�
�Q-F�
```
(This is only an approximation of the original input)
You do not need to expand to shellcodes.
### Dupe alert
This is not a duplicate of the other `xxd` hexdump challenge because this one does not to be expanded to shellcodes.
## Rules
* You may not use external programs that parse hexdumps (such as `xxd`).
* Standard loopholes apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), smallest code wins.
[Answer]
# [V](http://github.com/DJMcMayhem/V), 27 bytes
```
ÎdW40|D
Í üî
Ó../<C-v><C-v>x&
éiD@"
```
[Try it online!](http://v.tryitonline.net/#code=w45kVzQwfEQKw40gw7zDrgrDky4uLxYWeCYKw6lpREAi&input=MDAwMDAwMDA6IDFmOGIgMDgwOCA0OTIwIDIyNTggMDAwMyA3MDY5IDZjNmMgNmY3NyAgLi4uLkkgIlguLnBpbGxvdwowMDAwMDAxMDogMmU3NCA3ODc0IDAwZDMgZDcwNyA4MjE4IDEwZDAgMjc5OSBjNTQ1ICAudHh0Li4uLi4uLi4nLi5FCjAwMDAwMDIwOiBiYTk2IDQxYTEgOTk0YyA3ZDYwIGQ2NTAgZDUzYyA0NGEzIDhhMjIgIC4uQS4uTH1gLlAuPEQuLiIKMDAwMDAwMzA6IGNkNDMgMzRhYSAyOGQyIDNjNDQgYTM4YSAyMmNkIDQzMzQgYWEyOCAgLkM0LiguPEQuLiIuQzQuKAowMDAwMDA0MDogZDIwYyAwMGZkIDUxMmQgNDZiOCAwNTAwIDAwICAgICAgICAgICAgICAuLi4uUS1GLi4uLg)
Note that `<C-v>` represents the unprintable character `0x16`.
# Explanation
This answer is pretty fun because it's about modifying the input into V code and then executing that code. I'll explain each command one at a time
```
Î " On every line:
dW " Delete a word
40| " Move to the 40th column
D " Delete everything after this
Í " Remove all occurrences of
" A space
üî " or a newline
```
Now the buffer looks like this:
```
1f8b080849202258000370696c6c6f772e74787400d3d707821810d02799c545ba9641a1994c7d60d650d53c44a38a22cd4334aa28d23c44a38a22cd4334aa28d20c00fd512d46b8050000
```
The command to insert a character by its hex value is
```
<C-v>x<hex-value>
```
Here is where we start transforming it into actual V code.
```
Ó " Replace
.. " Two characters
/ " with
<C-v><C-v>x " the text "<C-v>x"
& " And the two characters we just matched
<C-v>x1fi<C-v>x8bi<C-v>x08i<C-v>x08i<C-v>x49...
```
But the command has to be in insert mode. So we insert an 'i' at the beginning.
```
éi " Insert an 'i'
D " Delete this line
@" " And evaluate it as V code
```
] |
[Question]
[
Given two words and a list as input, your program must (in as few characters as possible, of course) find the shortest way to "chain" the first word to the last using the ones in the list. Two words are "chained" if their first and last letters are the same, e.g. "Food" and "Door".
Your program will take input as a string with words separated by spaces, and output a list (in whatever format is most convenient: string, array/list type, etc) of the completed chain.
Examples:
`Input: joke corn tan disc need eat`
`Output: joke eat tan need disc corn`
The first two words in the input list are the first and last words in the chain, and the rest are the constituent words.
`Input: best fry easy elf mean tame yam nice`
`Output: best tame elf fry`
NOT: `best tame easy yam mean nice elf fry`
`Input: rug gunned orange purple gains pore soup emo ending`
`Output: rug gunned`
`Input: %3gioxl? 6699-4 !f!!&+ ?4; ;78! +6`
`Output: %3gioxl? ?4; ;78! !f!!&+ +6 6699-4`
The "words" don't have to be real words; for the purpose of the challenge, any ASCII character except the space will count as part of a word.
`Input: mouth rich frame inspire item sold`
Output when the first and last word are impossible to chain is undefined, so handle it however's shortest.
[Answer]
# Pyth, ~~51~~ 48 bytes
FGITW.
```
=cQdMqeGhHL++hQb@Q1holN{+Fmf.AgVTtTyM+]Y._d.p>Q2
```
[Test suite.](http://pyth.herokuapp.com/?code=%3DcQdMqeGhHL%2B%2BhQb%40Q1holN%7B%2BFmf.AgVTtTyM%2B%5DY._d.p%3EQ2&test_suite=1&test_suite_input=%22joke+corn+tan+disc+need+eat%22%0A%22best+fry+easy+elf+mean+tame+yam+nice%22%0A%22rug+gunned+orange+purple+gains+pore+soup+emo+ending%22%0A%22%253gioxl%3F+6699-4+!f!!%26%2B+%3F4%3B+%3B78!+%2B6%22%0A%22mouth+rich+frame+inspire+item+sold%22&debug=0)
[Answer]
# Pyth - 42 bytes
Complete brute force. Surprisingly fast, finishes all possible the test cases in seconds. Will run forever with impossible inputs.
```
Acczd]2.VZIJf.Amqhedehd,VTtTm++hGdeG^HbhJB
```
[Test Suite](http://pyth.herokuapp.com/?code=Acczd%5D2.VZIJf.Amqhedehd%2CVTtTm%2B%2BhGdeG%5EHbhJB&test_suite=1&test_suite_input=joke+corn+tan+disc+need+eat%0Abest+fry+easy+elf+mean+tame+yam+nice%0Arug+gunned+orange+purple+gains+pore+soup+emo+ending%0A%253gioxl%3F+6699-4+%21f%21%21%26%2B+%3F4%3B+%3B78%21+%2B6&debug=1).
] |
[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/80218/edit).
Closed 7 years ago.
[Improve this question](/posts/80218/edit)
Let's play code golf... by playing golf.
## Input
Your input will be a string consisting of `#`'s, an `o`, an `@`, and `.`'s. For example:
```
......@..
.....##..
.........
......o..
```
`.` - playable golf course (all shots must end on one of these)
`#` - a barrier (shots cannot go through this)
`o` - the starting position of your golf ball
`@` - the hole
## How to Play ASCII Golf
You start at the `o`. Here is a valid shot from point `A` to point `B`:
1) This shot is straight line that can be drawn between `A` and `B` (no curved shots).
```
A....
....B
```
2) The line `AB` may not intersect with a `#` (barrier), e.g.:
```
A.#.B
```
It **may**, however, be tangent to a barrier:
```
A#
.B
```
3) *(For clarity)* You may **not** bounce shots off barriers or the edge of the golf course.
## Output
Print to `stdout` (or an acceptable equivalent) the minimum number of shots to get the ball into the hole `@`. If it is not possible, print `-1`.
## Examples
```
o....@
```
`=> 1`
```
o.#.@
```
`=> -1`
```
o..#
..#@
```
`=> 2` (you can pass through the vertices of a `#`, but not the edges)
```
o#...#
.#.#.#
...#.@
```
`=> 4`
[Answer]
# Python 2, 469
Pretty long, but it's a start:
```
R=range
def l(c,x,y,z,t):
f=abs(z-x);g=1-2*(z<x);p=abs(t-y);q=1-2*(t<y);v=r=0
for i in R(f):
w=f+(2*i+1)*p
for j in R(v,(w-1)/2/f+1):r|='.'>c[x+g*i][y+q*j]
v=w/2/f
for j in R(v,p+1):r|='.'>c[z][y+q*j]
return r
def f(c):
a="".join(c);n=len(c[0]);b=len(a);d=[[9**9*l(c,i/n,i%n,j/n,j%n)+1for i in R(b)]for j in R(b)]
for k in R(b):
for i in R(b):
for j in R(b):
t=d[i][j]=min(d[i][j],d[i][k]+d[k][j])
if"o@"==a[i]+a[j]:r=t
return-1if r>9**9else r
```
Function f takes a list of strings and returns the number of shots.
Test suite:
```
def test(s,r):
print"ok"if f(s.split())==r else"fail"
test("o # @", -1)
test("......@.. .....##.. ......... ......o..", 2)
test("o....@", 1)
test("o.#.@", -1)
test("o..# ..#@", 2)
test("o#...# .#.#.# ...#.@", 4)
test("o### #..# ###@", 3)
test("o.## ##.@", 1)
test("...o .@#.", 2)
```
] |
[Question]
[
You live in a rectangular neighborhood which is completely partitioned into N rectangular plots, i.e. there are no gaps or overlaps. Plots do not necessarily have the same width/height as other plots. All widths/heights are positive integers. Your goal is to output all shared edges between plots.
# Inputs
The input may come from any source desired (stdio, file, function parameters, etc.). The input is a list-like sequence of rectangles. Inputs for rectangles may be any form desired, for example `(min_x, max_x, min_y, max_y)`, `(min_x, min_y, width, height)`, `(min_x, min_y, max_x, max_y)`, etc.
The neighborhood is bounded by `min_x = 0` and `min_y = 0`. You may assume `max_x` and `max_y` of the neighborhood both fit in your language's native integer type.
You may flatten the input data into a 1D sequence if desired.
The id of a plot is a sequentially incremented integer based on the order of input, where the first plot may have any id desired.
# Outputs
The output may be to any desired target (stdio, file, return value, output parameter, etc.).
The output is a list of lists of neighbors for each plot. A neighbor is defined as the id of the neighboring plot and the min/max bounds of the shared corner/edge. Shared corners/edges with the corner/edge of the neighborhood are not considered a neighbor relation and should not be outputted.
When printing out make some distinction between each list, for example using a newline to separate the neighbors of plot `i` from the neighbors of plot `i+1`.
The order of the neighbors of plot `i` is not important.
# Example Test Cases
All listed test case inputs are of the format `min_x, max_x, min_y, max_y` and plot IDs start with 0. Outputs are formatted as `(id, min_x, max_x, min_y, max_y)`.
**Input:**
```
0, 1, 0, 1
```
**Output:**
```
no output, empty list, list containing a single empty list, or anything similar such as null
```
**Input:**
```
0, 1, 0, 1
0, 1, 1, 2
```
**Output:**
```
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1)
```
**Input:**
```
0, 2, 1, 2
0, 2, 0, 1
```
**Output:**
```
(1, 0, 2, 1, 1)
(0, 0, 2, 1, 1)
```
**Input:**
```
0, 1, 0, 1
0, 1, 1, 2
0, 1, 2, 3
```
**Output:**
Regions with no neighbor relationships may be omitted.
```
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2)
```
It is also ok to output the id of the other region with some indication of "no shared boundary".
```
(1, 0, 1, 1, 1), (2)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2), (0, falsy)
```
**Input:**
```
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 2
```
**Output:**
```
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)
```
One possible alternative output (switched order of neighbors for plot 0):
```
(2, 1, 1, 0, 1), (1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)
```
**Input:**
You may have corner neighbors.
```
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 1
1, 2, 1, 2
```
**Output:**
```
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1), (3, 1, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 1), (3, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 1), (3, 1, 2, 1, 1)
(0, 1, 1, 1, 1), (1, 1, 1, 1, 2), (2, 1, 2, 1, 1)
```
# Scoring
This is code golf; shortest code wins.
**edit clarification that corner neighbors should be outputted as well. Also clarified that if two regions don't share any corners/edges the relation may be completely omitted, or a relation with a falsy edge bounds may be outputted. Both have test cases added.**
[Answer]
# Mathematica, 179 171 bytes
```
If[Depth@#2>2,Flatten/@(Thread@{##}/.Line->List)]&~MapThread~{Range@Length@#~Subsets~{2}-1,RegionIntersection/@Subsets[Line@{{##3},{#,#4},{#,#2},{#3,#2},{##3}}&@@@#,{2}]}&
```
---
**Test cases**
Inputs and outputs are list of elements in form `{x1, y1, x2, y2}`.
```
%[{{0, 0, 1, 1}, {0, 1, 1, 2}, {1, 0, 2, 2}}]
(*
{{{0, 0, 1, 1, 1}, {1, 0, 1, 1, 1}},
{{0, 1, 0, 1, 1}, {2, 1, 0, 1, 1}},
{{1, 1, 1, 1, 2}, {2, 1, 1, 1, 2}}}
*)
```
[Answer]
# Mathematica ~~123~~ 134 bytes
```
g@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.{{a_,{i_Integer}},
{b_,{j_}}}:>{{i-1,r=RegionIntersection[a,b][[1]]},{j-1,r}}
```
---
I prefer this version, at 123 bytes, which returns graphics objects instead of mere coordinates. It also avoids redundancy, using by MartinBüttner's suggestion, by listing two rectangle numbers followed by a `Line[{{x1,y1},{x2,y2}}]` in the case of a shared edge, and `Point[{x,y}]` in the case of a shared corner.
```
f@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.
{{a_,{i_Integer}},{b_,{j_}}}:>{{i,j}-1,r=RegionIntersection[a,b]}
```
---
[Answer]
# Python, 189 characters
```
for p in i:
for q in i:
for t in 0,2:
v,a,b=p[3-t],min(p[1+t],q[1+t]),max(p[t],q[t])
w,z=[v,v],[b,a]
if v==q[2-t]and a>b:
for d in p,q:
print[i.index(d)]+(w+z,z+w)[t/2]
```
The input is given as a list like
```
i = [[0, 1, 0, 1], [0, 1, 1, 2], [1, 2, 0, 2]]
```
[Answer]
# JavaScript (ES6), 228
Input / output as an array of arrays.
Format as in OP testcases:
* inputs min\_x, max\_x, min\_y, max\_y.
* outputs id (0 based), min\_x, max\_x, min\_y, max\_y.
```
l=>l.map(([x,r,y,s],i)=>l.map(([t,v,u,w],j)=>i-j&&(n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]),n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z])),o.push(q=[])),o=[])&&o
```
This can probably be shortened merging the horizontal and vertical check
**TEST**
```
f=l=>
l.map(([x,r,y,s],i)=>
l.map(([t,v,u,w],j)=>
i-j&&(
n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]), // vertical
n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z]) // horizontal
)
,o.push(q=[]))
,o=[])&&o
ArToStr=(a,s)=>a.map?(s?'[':'[\n ')+a.map(x=>ArToStr(x,1)).join(s?',':',\n ')+(s?']':'\n]\n'):a
console.log=x=>O.textContent+=x+'\n';
console.log(ArToStr(f([[0,1,0,1]])))
console.log(ArToStr(f([[0,1,0,1],[0,1,1,2]])))
console.log(ArToStr(f([[0, 2, 1, 2],[0, 2, 0, 1]])))
console.log(ArToStr(f([[0, 1, 0, 1],[0, 1, 1, 2],[1, 2, 0, 2]])))
```
```
<pre id=O></pre>
```
] |
[Question]
[
**This question already has answers here**:
[Golf Me An OOP!](/questions/61097/golf-me-an-oop)
(4 answers)
Closed 8 years ago.
I've been around for a while, watching you golf and I really enjoy it.
I came up with a challenge for you all so let's begin!
# Challenge
*I assume that everyone knows what Finite State Machine (FSM) is, I will edit the the description if needed.*
* Your program will take only one input consisting in a string that represents a FSM.
* The first character of the input is the FSM's initial state and the last character is the FSM's final state.
* Transitions are represented as two consecutive characters (`AB` will be the transition from state A to state B. `ABCD` will be the two transitions `A to B` and `C to D`)
* In this challenge, the FSM is considered valid when you have at least one path from the initial state to the final state.
# Goal
Output a truthy value, telling the world if the input is a valid FSM (any equivalent for `True` of `False` is fine)
### Bonus
* **-20%** if you add all the sequences of valid paths to the output
# Examples
`AB` should output (with bonus) `true AB`
`ABC` should output `false` (No transition to state C)
`ABCEBD` should output (with bonus) `true ABD` (The presence of unreachable states C and E doesn't make it false)
`ISSTSFTF` should output (with bonus) `true ISF ISTF`
`ABACBCCD` should output (with bonus) `true ACD ABCD`
`ABACBCD` should output `false`
`ABACADCDBCDEBE` should output (with bonus) `true ABE ADE ACDE ABCDE`
# Final word
If you think this challenge lacks something, please tell me, I'd really like to see the answers you can come up with
[Answer]
# JavaScript (ES6), 81 bytes
```
s=>(a=[...s]).map(_=>a.map((m,i)=>p=i%2&r[s[i-1]]?r[m]=1:r[m]),r={},r[s[0]]=1)&&p
```
## Explanation
Takes the states as a string and returns a `1` for true or `undefined` for false. This method was the shortest I could find, but it means that it's impossible to include the bonus because it just determines reachability, not the paths.
```
s=>
(a=[...s]) // a = states as an array
.map(_=> // loop a number of times to ensure all states have been reached
a.map((m,i)=> // for each state m at index i
p= // p = the reachability of the final state
i%2 // if this is the last state of a pair
&r[s[i-1]]? // and the first state is reachable
r[m]=1 // set the last state and p to reachable
:r[m] // else set p to the reachability of the state
),
r={}, // map of truthy values for reachable states
r[s[0]]=1 // set the initial state to reachable
)
&&p // return the final result
```
## Test
```
var solution = s=>(a=[...s]).map(_=>a.map((m,i)=>p=i%2&r[s[i-1]]?r[m]=1:r[m]),r={},r[s[0]]=1)&&p
```
```
<input type="text" id="input" value="ABACADCDBCDEBE" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/65264/edit).
Closed 8 years ago.
[Improve this question](/posts/65264/edit)
Implement a [FUSE filesystem](https://en.wikipedia.org/wiki/Filesystem_in_Userspace) in minimum bytes.
Your program must do three things:
* Mounting the virtual filesystem to a directory
* Handling requests to enumerate files in that directory (showing one file)
* Handling requests to read the file in that directory
Rules:
* `ls` (a system program, you don't need to implement it) must show `hello.txt` file (other unrelated files can also be visible, as well as errors may be printed). `hello.txt` must be exact, `68 65 6c 6c 6f 2e 74 78 74` in hex).
* `cat` (a system program) pointed to the file should output `Hello, world.` (punctuation, case and end of lines may differ. A bunch of zero bytes can also slip unnoticed). It can also be `cat m/hello.txt; echo` if there is no trailing newline.
* It must be actual FUSE filesystem, not just a regular file created by your program. For example, freezing your program should freeze the `hello.txt` file (`cat` and `ls` would hang). Creating a socket instead of mounting FUSE filesystem isn't an allowed workaround. Your mounted filesystem should be visible in `/proc/mounts` (or platform analogue).
* For 200 bytes penalty, you may depend on libfuse or use it's header files (or depend on the appropriate FUSE binding in some other language)
* Detaching is optional
* You program may be platform-specific. Somebody else on that platform should check and write a comment that it works (or not)
* Your program can't be a kernel module (`fuse.ko` is the involved kernel module on Linux and is considered a part of environtment, not your program)
* Your program can access `/dev/fuse` (or platform analogue) directly. It may require root access (or changing permissions) for it if needed. It can also rely on `fusermount` for the mounting step (like the example below). Whether using `fusermount` for mounting carry penalty or not I have not decided yet (because of I don't know implementation details enough): if the rest feels like talking to kernel directly then it should not be a problem.
* Additional compilation and invocation parameters are added to the score. A directory to be mounted may be specified as a free (non-penalty) parameter or may be just hardcoded (like `m`)
Example (directly based on official [hello.c](https://fossies.org/dox/fuse-2.9.4/hello_8c_source.html)):
```
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
static const char *hello_str = "Hello, world\n";
static const char *hello_path = "/hello.txt";
static int hello_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
}
return res;
}
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
filler(buf, hello_path + 1, NULL, 0);
return 0;
}
static int hello_open(const char *path, struct fuse_file_info *fi)
{
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return size;
}
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
int main(int argc, char *argv[])
{
return fuse_main(argc, argv, &hello_oper, NULL);
}
```
```
$ gcc -D_FILE_OFFSET_BITS=64 golffs.c -lfuse -o golffs
$ ./golffs m # uses fusermount under the hood
$ ls m
hello.txt
$ cat m/hello.txt
Hello, world
$ fusermount -u m
```
Score of the example: 1974 + 29 (compilation parameters) + 0 (invocation parameters) + 200 (penalty) = 2203
[Answer]
## Perl, 1348 998 846 748 714 683 642 575 520 + strlen("perl -mFuse") + 200 penalty for Fuse.pm = 731 bytes
Was interesting diversion from usual golf challenges. Started life as a version of <https://metacpan.org/source/DPATES/Fuse-0.16/examples/example.pl> before getting stripped down.
```
%k=('hello.txt'=>{});sub f{$_=shift;s,^/,,;return$_}Fuse::main(mountpoint=>$ARGV[0],getattr=>sub{$c=f(shift);$c=~s,^/,,;$c=~s/^$/\./;return(exists($k{$c})?0:-2,0,$c eq'.'?16877:33261,1,0,0,0,12,0,0,0,1024,0)},getdir=>sub{return(keys%k),0},open=>sub{return(0,[rand()])},statfs=>sub{return0},read=>sub{$c=f(shift);($x,$z,$h)=@_;return-2 unless exists($k{$c});if(!exists($k{$c})){$u=fuse_get_context();return sprintf("pid=0x%08x uid=0x%08x gid=0x%08x\n",@$u{'pid','uid','gid'})}return$z==12?0:substr("Hello, world",$z,$x)})
```
Long lines, but if presented via `fold`, appears as below:
```
# fold foo.pl
%k=('hello.txt'=>{});sub f{$_=shift;s,^/,,;return$_}Fuse::main(mountpoint=>$ARGV
[0],getattr=>sub{$c=f(shift);$c=~s,^/,,;$c=~s/^$/\./;return(exists($k{$c})?0:-2,
0,$c eq'.'?16877:33261,1,0,0,0,12,0,0,0,1024,0)},getdir=>sub{return(keys%k),0},o
pen=>sub{return(0,[rand()])},statfs=>sub{return0},read=>sub{$c=f(shift);($x,$z,$
h)=@_;return-2 unless exists($k{$c});if(!exists($k{$c})){$u=fuse_get_context();r
eturn sprintf("pid=0x%08x uid=0x%08x gid=0x%08x\n",@$u{'pid','uid','gid'})}retur
n$z==12?0:substr("Hello, world",$z,$x)})
#
```
Example use:
```
# perl -mFuse foo.pl m &
[1] 6410
# ls -ld m
drwxr-xr-x 1 root root 0 Jan 1 1970 m
# cd m
# ls -l
total 0
-rwxr-xr-x 1 root root 12 Jan 1 1970 hello.txt
# cat hello.txt
Hello, world#
```
] |
[Question]
[
Blade is a PHP templating engine. For this challenge, you only need to implement a modified version one feature -- text replacement.
## Challenge Description
Given an input file and a map of keys to their replacements, write an interpreter that reads through the file to find double open braces (`{{`) followed by a key, followed by double closing braces (`}}`). Whitespace inside the braces should be ignored, unless it is inside of the key.
## Requirements
If a key is not found in the map, your program should exit without outputting anything
Keys must be nestable. See the examples for a valid nesting example.
Keys may contain any character, but cannot start or end with a space. Whitespace should be trimmed from the start and end of the key.
## Example input/output
Input blade file:
```
Hello, {{user_{{username }}}}! It is { NICE } to meet you!
My name is {{ my n@m3}}!
```
Input map:
```
{
'user_Joe': 'Joseph, user #1234',
'username': 'Joe',
'my n@m3': 'Henry'
}
```
Expected output:
```
Hello, Joseph, user#1234! It is { NICE } to meet you!
My name is Henry!
```
## Marking:
Feel free to hard code input/output and exclude it from your byte count. However, if you implement the following features, take the corresponding value away from your byte count.
Read filename of blade template from stdin or arguments: 15 bytes
Read variable mapping as JSON from stdin or arguments: 20 bytes
Read variable mapping in any other format from stdin or arguments: 12 bytes
## Bonus
Allow calculations (`+`, `-`, `*`, `/`, `%`, etc) in your blade script. Example input file:
```
{{a + b}}
```
Input map:
```
{ 'a': 1, 'b': 4 }
```
Expected output:
```
5
```
[Answer]
## Perl: 105 - 15 - 20 = 70
```
perl -MJSON -pE'sub f{$_[0]=~s#{{\s*((.*?(?R)?.*?)+)\s*}}#$h->{f($1)}#reg};BEGIN{$h=from_json shift};$_=f$_' 'JSON' <input
```
Usage: the JSON is given as a command line argument. The template source is passed in STDIN. Example:
```
$ perl ... '{"user_Joe":"Joseph, user #1234","username":"Joe","my n@m3":"Henry"}'
>Hello, {{user_{{username }}}}! It is { NICE } to meet you!
>My name is {{ my n@m3}}!
```
(where lines beginning with `>` are pasted/typed/piped in)
Restrictions:
* can't do arithmetic.
* keys cannot span multiple lines.
* requires the `JSON` Perl module to be installed (non-standard).
* requires a new-ish perl (tested on Perl5 v20, but should work on at least v16 or v14).
I am not sure about the scoring rules, so I excluded `perl·`, the quotes for the code, and included an extra space and two quotes needed to pass the JSON on the command line.
Explanation:
Perl regexes can be recursive, but substitutions can't. To overcome this, we first define a regex that matches keys that might contain keys again: `{{\s* ((.*? (?R)? .*?)+) \s*}}`. Here, `(?R)` recurses into the whole pattern. The key does not have to contain a template tag, so the recursion is optional. In that case, the pattern is a non-greedy “match anything”: `.*?.*?`. This will terminate given a double closing braces. Usually braces are metacharacters in regexes, e.g. `a{10,20}` (match 10 to 20 "a"s). Fortunately, the regex compiler recognizes that these braces are not used as quantifiers.
Once we have matched the (possibly recursive) tag contents, we pass it to the function `f` which again applies the substitution to this content. The result is then used as a key in a hash reference `$h`, which replaces the tag contents. This is done non-destructively `/r` and globally `/g`.
The `$h` hash reference is defined in the `BEGIN` phase to the json-decoded value of the first command line argument. Since the `sub f` definition and the BEGIN block are done before the main execution, the actual script is `perl -pE'$_=f$_'`, which applies our substitution function `f` to each line.
Voilà, a template engine is born :)
] |
[Question]
[

This challenge is inspired by [dmenu](http://tools.suckless.org/dmenu/), the program I use to launch other programs on my Linux box. To start, for example, GIMP, I simply hit the keyboard shortcut I have assigned to dmenu, type "gimp" and hit enter. However, I don't have to type the whole name. On my machine, if I type "gim", that's enough. Here's how dmenu decides which program to launch when you hit enter1:
1. Find all program names that contain the input as a substring.
2. Sort this list alphabetically.
3. Take the items in the list that *begin* with the input, and (preserving their order) put them at the beginning.
4. Launch the first2 program in the list.
While this is usually quite convenient, it is sometimes annoying. For example, on my computer I have `chromedriver` and `chromium`. I never want to launch `chromedriver`, but it's earlier alphabetically than `chromium` is. If I start typing at the beginning of the word, like I naturally want to do, I have to type six characters to specify that I mean the latter.
However, we don't need to start typing at the beginning of the word! `chromium` is, alphabetically, the first program name containing the substring `iu`. I have no programs that start with `iu`. Therefore, I only need to type those two characters to unambiguously specify which program I want.
For this challenge, your program or function will receive at least two lines of input. No line will contain any whitespace characters (other than the newline, obviously) and the first line is guaranteed to be repeated somewhere in the remaining input. Your program or function will output (stdout, `return`, etc.) the shortest string that, using dmenu's rules, would find that first line in all the rest. If there are two or more that are tied for shortest, you may output whichever you like.
# Examples
```
In:
bbbb
aaaa
bbbb
cccc
Out:
b
In:
bc
bc
aaaa
bbc
Out:
bc
```
---
1: I don't actually know this to be the case, but in my experience it seems to work this way.
2: When actually using dmenu, you can hit left and right to choose different items in the list, but that's irrelevant for this challenge.
[Answer]
# Pyth, ~~22~~ 21 bytes
```
hfqzho>xNT0Sf}TY.z.:z
```
isaacg and me got the same 21 solution more or less at the same time. So he deleted his solution.
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=hfqzho%3ExNT0Sf%7DTY.z.%3Az&input=bc%0Abc%0Aaaaa%0Abbc&debug=0)
### Explanation
```
implicit: z = first input line
.z = all other input lines
f .:z filter all substrings T of z, which satisfy:
f .z filter .z for lines Y, which satisfy:
}TY T in Y
S sort these lines alphabetically
o order these lines N by:
>xNT0 (index of T in N) > 0
(sorting in Pyth is stable, so this brings the lines,
which start with T, to the beginning
without messing up the alphabetically order)
qzh z == first element of ...
h print first elment
```
] |
[Question]
[
## Iterated Function Systems
An [Iterated Function System](http://en.wikipedia.org/wiki/Iterated_function_system) (IFS) is a method of constructing self-similar fractals. Each fractal is defined recursively as the union of several copies of itself, with each copy obtained by applying a transformation function to the whole. The functions are usually [affine transformations](http://en.wikipedia.org/wiki/Affine_transformation) of the form x↦Mx+b: i.e. a linear transformation such as a rotation, scaling or reflection, followed by a translation. Given a set of transformations, the fractal can then be obtained iteratively as follows: begin with a point (for example the origin) and repeatedly apply a randomly-selected transformation from the set. The sequence of points generated, which converges to the fixed point of the IFS, is then plotted.
The most famous example of an IFS is the [Barnsley Fern](http://en.wikipedia.org/wiki/Barnsley_fern). This is produced from four affine transformations, shown in the diagram below (taken from Wikipedia).

The affine transformations used in this questions involve only uniform scaling, rotation by a multiple of 90°, and translation. They can be implemented as follows, where n is the scale factor, θ is the rotation angle in radians and b is the translation in 'plot units' (e.g. pixels):

## Seven-segment displays
A [seven-segment display](http://en.wikipedia.org/wiki/Seven-segment_display) (SSD) is a cheap and simple electronic display device often used in clocks, meters and calculators to display decimal numerals. Though it wasn't designed to display letters, it is sometimes used to do so. The resulting alphabet is often ambiguous and sometimes unintuitive, but is sufficient for certain status messages (e.g. "nO dISC" or "gOOdbYE"). Below is one way to represent the 26 letters and 10 numerals on a seven-segment display.

## Task
The aim of this challenge is to produce word fractals using IFSs and the SSD alphabet above.
* The input is a string of multiple alphanumeric characters. The string may contain both upper and lower case letters, though the SSD alphabet is case insensitive. The program need not support punctuation or whitespace characters.
* The output should be an IFS plot representing the string as rendered in the SSD alphabet above. Each lit segment in each character should correspond to an additional affine transformation mapping the bounding box of the rendered word to that of the segment. Horizontal segments should remain facing upwards, while vertical segments should face 'outwards' (i.e. left-side up on the left, right-side up on the right). The precise alignment/overlap of segments is left up to the solver, as long as the output is legible. For an example output showing one possible alignment, see below.
* There should be a constant non-empty gap between the letters, to make the output legible.
* The plot should contain enough points to be legible.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. The output should be drawn either to screen or to a file in any standard graphic format. **As part of the answer you should include a screenshot of your output for the word "COdEgOLF".** Standard code golf restrictions apply.
## Example

## Scoring
Shortest code (in bytes) wins. Standard rules apply.
## Miscellania
For a good mathematical introduction to IFSs (including fractal compression) see these [PDF lecture notes](https://www.cg.tuwien.ac.at/courses/Fraktale/PDF/fractals3.pdf).
For a similar challenge concerning self-similar text see [Words within words within words within words . . .](https://codegolf.stackexchange.com/q/44913/34694).
[Answer]
# Python (518)
```
from pylab import*
D=dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',[map(int,bin(7145037215283832782017591362181079009730769141301710950254702714880607436795)[2+n*7:9+n*7])for n in range(36)]))
def T(A,C):y,x=A.shape;M=zeros((2*x-1,x+y));p=A[::-1].T;q=A.T[::-1];M[:y,:x]=C[0]*A;M[:x,:y]=C[1]*p;M[:x,-2*y:-y]=C[2]*q;M[x-1:x-1+y,:x]=C[3]*A;M[x-1:,:y]=C[4]*p;M[x-1:,-2*y:-y]=C[5]*q;M[2*x-1-y:2*x-1,:x]=C[6]*A;return M
def R(S,N):
V=ones((1,3))
for i in range(N):V=concatenate([T(V,D[C])for C in S],1)
ion();imshow(V)
```
Call as `R('CODEGOLF', 3)`
first i make a dictionary that maps letters to their 7-bit SSD-representaion, where each bit stands for one bar, the `.`-corners are simply overwritten by the most recent bar
```
.000.
1 2
1 2
1 2
.333.
4 5
4 5
4 5
.666.
```
The function `T(BaseArray, BooleanArray)` makes a big empty array for one letter and puts rotated copies of BaseArray along the bars as indicated by BooleanArray. Finally `R(String, N_levels)` connects all the letters form the input and uses the result as BaseArray for the next iteration.
While technically correct, the result is quite ugly because of interpolation and the default colourmap

**Unglofed**
```
from pylab import*
D=dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
[map(int,bin(7145037215283832782017591362181079009730769141301710950254702714880607436795)[2+n*7:9+n*7])for n in range(36)]))
def T(A,C):
y,x = A.shape
M = zeros((2*x-1,x+y))
if C[0]: M[:y, :x] = A
if C[1]: M[:x, :y] = A[::-1].T
if C[2]: M[:x, -2*y:-y] = A.T[::-1]
if C[3]: M[x-y+y/2:x+y/2,:x] = A # middle bar shifted upwards by half thickness
if C[4]: M[x-1:, :y] = A[::-1].T
if C[5]: M[x-1:, -2*y:-y] = A.T[::-1]
if C[6]: M[2*x-1-y:2*x-1,:x] = A
return M
def R(S,N):
V = ones((1,3))
for i in range(N):
V = concatenate([T(V, D[C]) for C in S], 1)
imsave('%s_%s.png'%(S,N), V ,cmap='gray')
```
The initial seed `V` kinda controls the font on the deepest level. `[1 1 1]` make the smallest possible 3x5 letters

With `V = ones((1,11))` you get long and thin letters

And with
```
V=array([[0,1,1,1,1,1,1,1,1,0],
[1,0,0,0,0,0,0,0,0,1],
[0,1,1,1,1,1,1,1,1,0]])
```
you can make hollow letters

] |
[Question]
[
Recently, when doing some code-golf challenge, I came up with with two solutions, in 69 and 105 bytes. [It's a remarkable coincidence](http://en.wikipedia.org/wiki/69_%28number%29), because:
* 69 (decimal) = 105 (octal)
* 69 (hexadecimal) = 105 (decimal)
What other numbers have this property (using different bases)? You should help me answer this question!
Write a program or a subroutine that receives as input 3 numbers (base1, base2, base3, in ascending order), and prints two sequences of digits `d1 d2 d3 ...` and `D1 D2 D3 ...` that reproduce this numerical coincidence for the specified bases.
To make sure the various fine points are covered:
* Evaluate one sequence as a number in base `base1`, and the other sequence in base `base2` -- you must get the same number
* Evaluate one sequence as a number in base `base2`, and the other sequence in base `base3` -- you must get the same number
* Both sequences must have finite length, which is greater than 1
* Separate the sequences of digits with whitespace or in any other unambiguous way
* Output to `stdout` or other similar output device
* All digits must be between 0 and `base-1`; leading zeros are not allowed
* If a digit is greater than 9, use `a` or `A` for 10, `b` for 11, ..., `z` for 35
* You may assume that all bases are different, come in ascending order and are in the range 2...36; are represented in the most natural way for your language
* If there is no answer, your code must signal it in some way (e.g. outputting nothing)
* If there is an answer whose larger number is less than 1679616 (364), your code must find it; otherwise, it may output as if no solution exists
* Code-golf: shortest code wins!
Example input:
```
8, 10, 16
```
Example output:
```
69 105
```
or
```
104 68
```
Or any other solution.
I'll be happy if you provide theoretical insights into this problem (How to determine whether a solution exists? Is there an infinite number of solutions?).
[Answer]
## Python 2, 158 bytes
Came a bit too easily, so I might be missing something obvious!
```
s=lambda n,b:(n/b and s(n/b,b)or'')+chr(48+n%b+39*(n%b>9))
def f(a,b,c):
for n in range(b,36**4):
x=s(n,a);y=s(n,b)
if int(x,b)==int(y,c):print x,y;break
```
The base conversion function is lovingly stolen from @ugoren's solution to [Print integers in any base up to 36](https://codegolf.stackexchange.com/questions/8606/print-integers-in-any-base-up-to-36). The code simply tries all possible values for the smaller number and the rest is fully determined. We start counting from *base2* to ensure both sequences are at least length 2.
```
>>> f(8, 10, 16)
100 64
>>> f(8, 10, 17)
>>> f(16, 20, 24)
20 1c
```
] |
[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/35705/edit).
Closed 9 years ago.
[Improve this question](/posts/35705/edit)
The aim is to parse a sentence and `compress/encrypt` it according to the rules below and then `decrypt` it using the `key`:
1. Remove all letters in a word before the first vowel is encountered. Example: `pigeon` becomes `igeon`.
2. All characters except alphabets should be kept in the sentence including numerals, punctuations, etc. Example: `200-storey building` becomes `200-orey uilding`.
3. Generate the shortest key array `char[] = {a,b,x,<your data>}` and write code to generate the original sentence using this key.
You need to write two functions: `encrypt()` and `decrypt()` which works for every sentence minimising the key-size.
Example 1:
>
> **Input:** The most technologically efficient machine man has ever
> invented is the book. -Northrop Frye-
>
>
> **Output:** e ost echnologically efficient achine an as ever invented is e
> ook. -orthrop e-
>
>
> **Example key:** {T,m,t,m,h,b,N,F,14,2,5}
>
>
>
Example 2:
>
> **Input:** "I need your clothes, your boots and your motorcycle. " - The
> T-800 in Terminator 2: Judgment Day
>
>
> **Output:** "I eed our othes, our oots and our otorcycle. " - e -800 in
> erminator 2: udgment ay
>
>
> **Example key:** {n,y,c,2,b,2,m,T,J,D,15}
>
>
>
**Winning Criteria:**
1. Write function `encrypt()` with input from `stdin` or `file` which generates `output` sentence and a `key` on `stdout` or `file` or `memory`.
2. Write function `decrypt()` with inputs the generated sentence and `key` from `encrypt()` and produces the original sentence.
3. This is `code-golf` so cumulative size of the two functions should be minimum. In case of tie-breaker, the generated key-size should be minimum.
[Answer]
# Perl5 61 + 30 = 91 ~~122~~ ~~211~~
This is based on the same idea as [Comperendinous' Haskell answer](https://codegolf.stackexchange.com/a/35764/11290) where the key is indeed the whole cleartext and I cannot see anywhere in the rules that prevent this so kudos to Comperendinous :)
```
sub encrypt{$k=$_=<>;s/(.*?)\b[^\W\daeiou]+/$1/gi;print$_.$k}
sub decrypt{$i=<>;$_=<>;print}
```
**Perl5 - 91 + 31 = 122**
Here the key is slightly larger, but it actually prrduces the cleartext from the chipertext with the key so I find this more kosher.
```
sub encrypt{$_=<>;$k="s/(.{$+[1]})/\$1$+/;$k"while s/(.*)\b([^\d\Waeiou]+)/$1/i;print$_.$k}
sub decrypt{$_=<>;eval<>;print}
```
Ungolfed (though I've changed it to take parameters instead of two lines of text):
```
sub encrypt {
my ($str) = @_;
my $key = '';
while( $str =~ s/(.*)\b([^\d\Waeiou]+)/$1/i ){
$key = "\$str=~s/(.{$+[1]})/\$1$2/;$key";
}
($str, $key);
}
sub decrypt {
my ($str, $key) = @_;
eval $key;
$str;
}
```
**Perl5 - 114 + 75 + 22 (shared) = 211**
```
sub encrypt{$_=<>;@k=m/\b$x/ig;push@_,$+[1] while s/(.*?)\b$x/$1/i;print$_.join'',(@_,@k)[map{$_,$_+@k}0..$#k],$/}
sub decrypt{$i=<>;$_=<>;%k=m/(\d+)$x/g;print map{$k{$%++}|(),$_}split//,$i}
$x='([^\d\W\daeiou]+)'
```
With both functions chipertext is always output/input first, then the key.
Examples:
```
Input:
The most technologically efficient machine man has ever invented is the book. -Northrop Frye-
Output:
e ost echnologically efficient achine an as ever invented is e ook. -orthrop e-
0Th2m6t31m38m41h61th63b69N77Fry
Input:
"I need your clothes, your boots and your motorcycle. " - The T-800 in Terminator 2: Judgment Day
Output:
"I eed our othes, our oots and our otorcycle. " - e -800 in erminator 2: udgment ay
3n7y11cl18y22b31y35m50Th52T60T73J81D
```
Ungolfed code:
```
# credit: http://stackoverflow.com/a/71895/1565698
sub zip {
my $pivot = @_ / 2;
return @_[ map { $_, $_ + $pivot } 0 .. $pivot-1 ];
}
my $consonants = '([^\d\W\daeiou]+)';
sub encrypt {
my $str = <>;
my @matches = $str =~ m/\b$consonants/ig;
my @indexes = ();
while( $str =~ s/(.*?)\b$consonants/$1/i ) {
push @indexes, $+[1]; # @+ has the match positions starting at 1
}
my $key = join('', zip(@indexes, @matches));
print "$str$key\n";
}
sub decrypt {
my $str =<>;
my $key =<>;
my %map = ( $key =~ m/(\d+)$consonants/g );
my $index = 0;
my @result = map{ $map{$index++} || (), $_ } split //, $str;
print join '', @result;
}
```
[Answer]
# Perl (126+67=193 characters)
Key contains each character removed along with its offset.
Encrypt reads one line from STDIN
Decrypt reads two: first the ciphered string then the key
```
sub encrypt{$_=<>;s(.)(++$j,$q|=$&=~/[aeiou]/i,$q^=$&eq$",!$q&$&=~/[a-z]/i&&(push@d,($&,$j-1))||print$&)ge;print$/.join',',@d}
sub decrypt{$q=<>,$_=<>;s/(.),(\d+)/substr($q,$2,0)=$1/gie;print$q}
```
Examples:
```
(encrypting)
The most technologically efficient machine man has ever invented is the book. -Northrop Frye-
> e ost echnologically efficient achine an as ever invented is e ook. -orthrop e-
> T,0,h,1,m,4,t,9,m,35,m,43,h,47,t,68,h,69,b,72,N,79,F,88,r,89,y,90
"I need your clothes, your boots and your motorcycle. " - The T-800 in Terminator 2: Judgment Day
> "I eed our othes, our oots and our otorcycle. " - e -800 in erminator 2: Judgment ay
> n,3,y,8,c,13,l,14,y,22,b,27,y,37,m,42,T,58,h,59,T,62,T,71,D,94
(decrypting)
e ost echnologically efficient achine an as ever invented is e ook. -orthrop e-
T,0,h,1,m,4,t,9,m,35,m,43,h,47,t,68,h,69,b,72,N,79,F,88,r,89,y,90
> The most technologically efficient machine man has ever invented is the book. -Northrop Frye-
"I eed our othes, our oots and our otorcycle. " - e -800 in erminator 2: Judgment ay
n,3,y,8,c,13,l,14,y,22,b,27,y,37,m,42,T,58,h,59,T,62,T,71,D,94
> "I need your clothes, your boots and your motorcycle. " - The T-800 in Terminator 2: Judgment Day
```
Ungolfed with comments
```
sub encrypt{
# get input
$_=<>;
# for each character
s(.)(
# increment j
++$j,
# set q to 1 if vowel
$q |= $&=~/[aeiou]/i,
# set q to 0 if space
$q ^= $& eq $",
# if q==0 and is a letter (consonant, because q=1 if vowel)
!$q & $&=~/[a-z]/i &&
# push both the letter and the offset to @d
(push @d,($&,$j-1))
# otherwise print
|| print$&
)ge;
# print a newline, then @d
print$/.join',',@d
}
sub decrypt{
# read a line to $q, and another to $_
$q=<>,$_=<>;
# for each [character],[number] in key
s/(.),(\d+)/
# add character back into string
substr($q,$2,0)=$1
/gie;
# print deciphered string
print$q
}
```
[Answer]
## Haskell: 119 = 111 + 8
Since there's no restriction on the key, I'm going agile and not getting any more complex until someone has a shorter answer:
```
e t=(unwords.map((\(a,b)->filter(not.(`elem`['a'..'z']++['A'..'Z']))a++b).break(`elem`"aeiouAEIOU")).words$t,t)
d(c,k)=k
```
I can make this at least 6 characters shorter if I import isAlpha from Data.Char. It's part of the standard distribution, so is it allowed?
] |
[Question]
[
The popular `.bz2` compression format is used to store all sorts of things. One of the more interesting features is that it consists of several independently decompressible blocks, allowing recovery of partial segments if the file is damaged. The `bzip2recover` program, included with `bzip2`, allows recovery of blocks from a `bzip2` archive. In this challenge, you will implement a simple clone of `bzip2recover`.
The basic idea is to scan a bitstream for a particular magic number, and output blocks delimited by this magic number to separate files. Read on for gory details.
---
Technically, bzip2 files are a *bitstream*, with every group of 8 bits being stuffed into a byte. The first bit is placed in the most significant bit of a byte, with the eighth bit going in the least significant bit of a byte. Files begin with the header "BZh", and a digit "N" from 1 to 9 indicating the compression level (9 is the most common). Then the bitstream begins.
The bitstream is split up into blocks. Each block encodes N\*100KB of uncompressed text (e.g. 900KB of text for compression level 9).
Blocks can begin basically anywhere in the bitstream, and do not necessarily begin on 8-bit boundaries. Blocks begin with a magic number, which is set to the 48-bit sequence 0x314159265359 (in ASCII, "1AY&SY"). For example, the sequence of bytes "73 14 15 92 65 35 90" contains the magic number, offset by 4 bits within the byte.
Your goal will be to take a bzip2 file on stdin, and output each detected BZip2 block to a separate decompressible file. Specifically, your program does the following:
* Read and skip the bzip2 header ("BZh" + N)
* Scan the bitstream for the magic sequence
* Copy the bitstream between two consecutive magic sequences to a new file, with a new BZip2 header and block header. Note that this may require realigning the bitstream to start at a byte boundary, and padding the last byte.
You don't have to care about parsing the blocks, and you can assume that a magic sequence always starts a block (i.e. that it isn't in the middle of a block).
How you name the output files is up to you. The only requirement is that they be clearly sequential somehow (so, e.g. "a b c ... z aa ab" or "1 2 3 4 5 .. 9 10 11 12" are both acceptable).
---
For a test case, you may use [this file](http://ipsc.ksp.sk/2014/real/problems/d2.in) from the IPSC 2014 problem-solving contest. The file is a bzip2 file with four blocks. The file as a whole actually decompresses to another bzip2 file with 162 complete blocks. Therefore, you may use these block counts to validate that your solution is getting all of the blocks. (Note that the file actually decompresses even further into more bzip2 files, but you probably don't want to decompress it all the way).
---
This is code golf, with a twist: your score is the number of bytes in the bz2-compressed version of your source code. (I'm aware this may make submissions *larger*, but these are the rules!). Since bzip2 compressors may differ in performance, provide a base64-encoded version of the compressed file to prove it's size. (You may therefore be able to obtain a better score by optimizing your program for bzip2, though I don't necessarily expect anyone to do this). Standard loopholes apply.
[Answer]
# Python 3 -- 375(534 chars)
It can process the example file `d2.in` in about 10 seconds, using Pypy3. With CPython 3, it will cost 60 seconds.
It's interesting and weird that some old golf tricks would make the score worse! For example, replacing `<space>+<space>` by `+` would increase the score from 375 to 384; replacing all `range` by `R` will also increase the score to 384.
## Golfed
```
import sys
from collections import deque
def T(B):
for i in range(0,len(B),8):
x=0
for j in range(min(8,len(B)-i)): x |= B[i + j] << (7-j)
yield x
V=sys.argv
C=F=0
B=bytearray()
I=open(V[1],'rb')
H=I.read(4)
P=deque([(x>>(7-j)) & 1 for x in b'1AY&SY' for j in range(8)])
Q=deque([0]*48)
for x in I.read():
for j in range(8):
b=(x>>(7-j)) & 1
B.append(b)
Q.popleft()
Q.append(b)
if Q!=P: continue
C+=1
M,B=B[:-48],B[-48:]
if F:F.write(bytes(T(M)))
F=open(V[2] + str(C),'wb')
F.write(H)
F.write(bytes(T(B)))
```
## Base64
```
QlpoOTFBWSZTWSoMWQ0AAMLfgAAQYf901zlibSo/t//kMAFaCIaCQANTTTKMnlGg8oeRpPaoNDDAAAAAaAAAAABKaSGmmpplD0jQaAABo00ZNqLfKsdHBd3QgkQ2wY3RfYpMMjPpsyit5Ee6+k6E6ObzlFT2vmgbSKPkni7ZgDkcwTRiLFBmNCuEX/HtOC8KJ+Rg51SkMCiAGXZpXbvaK+DzMLvaEhAM8reCB8HFAsNYfRghS9+i5/IpLrDzGZVhsbVOpQzHIIVZ7zCCgDkcElOMvTuvfw2bruKz2WQuvEg99gDa8T3Kw2GdyMNjEVFVVQj4sU1MaOTUcwQROwt86LfUZAOJE6HqnB60CFO38NJmpifx+trcQ8x5alqRiEGoKC2wJpPkCXpT7fbtFDbLCLQaplK23qMTC5gqGwCghjN3zEtwyKhCz3kixqBr7gya6yPG03rMOGY9hlmV3tS0W/SdC2taUpCoNSEaEnUXckU4UJAqDFkN
```
] |
[Question]
[
## Introduction
The Fibonacci Linear Feedback Shift Register (LFSR) is a digital circuit which generates a stream of random-looking bits. It consists of several 1-bit flip-flops in a row, with certain positions designated as 'tapped'. In each iteration, the values in the tapped positions are XORed together (i.e., summed modulo 2) and the result is held in reserve. Then the bits are shifted to the right. The rightmost bit falls off the register and becomes the output, while the reserve bit is input on the left.
## Maximal LFSR
The output stream of a LFSR is periodic; it repeats after some number of iterations. A maximal LFSR has a period of 2^n - 1, where n is its number of bits. This only occurs if the tapped positions are correctly chosen; otherwise the period will be less. If the LFSR is maximal, it will cycle through all possible internal states (except all zeroes) exactly once before repeating.
For more information about maximal Fibonacci LFSRs (primitive polynomials), see this article: <https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Fibonacci_LFSRs>
## Task
You must write a function that takes as its arguments a list representing the initial internal state of an n-bit LFSR (a list of length n made of 0 and at least one 1), and a list of tapped positions. The tapped positions are input as a list with either of these general formats (brackets, commas, and spaces are shown for convenience and are entirely optional):
Format A: [0, 0, 1, 1]
Format B: [3, 4]
Both formats declare that the 3rd and 4th positions are tapped.
The function must produce exactly one complete cycle of output of the LFSR (either as function output, or printed to the screen), as well as a Boolean evaluation of whether or not the LFSR period is maximal.
If you prefer, you may use two functions to produce the LFSR output and maximality evaluation.
## Scoring
Per usual code golf rules, your score is the number of characters in your code. Make sure your code evaluates these examples correctly:
### Example 1
State: [1, 0, 1, 0]
Taps: [3,4]
Output: [0,1,0,1,1,1,1,0,0,0,1,0,0,1,1] and True (since the period is 2^n - 1 = 15)
### Example 2
State: [1, 0, 1, 0, 1]
Taps: [3, 5]
Output: [1,0,1,0,1,0,0,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,1,0,0,0,1,1,0,1,1] and True (since the period is 2^n - 1 = 31)
### Example 3
State: [1, 0, 1, 0, 1]
Taps: [4, 5]
Output: [1,0,1,0,1,1,1,1,1,0,0,0,0,1,0,0,0,1,1,0,0] and False (since the output has period 21, which is not equal to 2^n - 1)
[Answer]
### GolfScript, 38 characters
```
:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=
```
You may declare it as a named function if you enclose the code in `{<code>}:F`. It takes the top two arguments from the stack and pushes the results back to the stack, e.g. (test it [online](http://golfscript.apphb.com/?c=MTcsezgtYWJzIiAiKjkseykrfS85PC4tMSUxPit9JW4q&run=true)):
```
[1 0 1 0 1] [3 5]
:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=
# => yields [1 0 1 0 1 0 0 0 0 1 0 0 1 0 1 1 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1] 1
```
*Annotated code:*
```
:f; # save tap positions (1 indexed) to variable f
:i # and the initial state to variable i
[{ # the [{...}do;] loop generates an array using the loop
# top of stack is the current state
0 # push zero (accumulator)
{ # {...}f/ loops over all tap positions
( # make the current position zero-indexed
2$= # take the corresponding bit from the current state (2$)
^ # xor with the accumulator
}f/ # end of loop
\+ # prepend the new bit to the current state
)\ # and shift out the last bit (output)
.i= # compare the current state to input
! # if not equal then loop
}do;] # end of loop - discard the state
.,) # length of the output + 1
2i,? # 2^length of initial state
= # are those two numbers equal?
```
[Answer]
## Perl - 78 bytes
```
sub f{($_,$t)=@_;s//($_&$t)%9&1/e,@o=(@o,chop)until$o{$_}++;@o,$/,@o+1>>y///c}
```
Input is expected as two binary strings, one representing the current state, and the other the taps. For example, the input `('10101', '00011')` corresponds to an initial state with the 1st, 3rd, and 5th bits set (one indexed), with taps on the 4th and 5th bit.
For the truth condition, a `0` or `1` is returned, separated by a newline.
**Note**: The bit counting logic above, `($_&$t)%9&1`, will fail if the total number of bits is more than *16*, and/or the number of taps is greater than *8*. This can be replaced by `($_&$t)=~y|0||c&1` at the cost of *6* bytes.
**Test Case 1**
Input:
```
print f('1010', '0011');
```
Output:
```
010111100010011
1
```
**Test Case 2**
Input:
```
print f('10101', '00101');
```
Output:
```
1010100001001011001111100011011
1
```
**Test Case 3**
Input:
```
print f('10101', '00011');
```
Output:
```
101011111000010001100
0
```
[Answer]
# Javascript (E6) 144 ~~157 169~~
**Edit** Output as string instead of array
```
F=(s,t)=>(P=>{b=s.length,i=s=P(s,2),t=P(t,2);for(o='';!o||i-s;){for(p=q=s&t;q>>=1;p^=q);o+=s&1,s=s>>1|(p&1)<<b-1}})(parseInt)||[!!o[(1<<b)-2],o]
```
**Ungolfed**
```
F=(s,t)=>
( P => { // Inner block, spare a final 'return'
b = s.length,
i = s = P(s,2), t=P(t,2);
for (o='';!o||i-s;) {
for (p=q=s&t;q>>=1;p^=q);
o += s & 1,
s = s >> 1 | (p&1) << b-1
}
} ) (parseInt)
|| [!!o[(1<<b)-2], o]
```
**Usage**
State and Tapped position input as strings of bits (format A)
Return an array with true/false and a string of output bits
**Test**
Javascript console in firefox,
`F('1010', '0011')` `[true, "010111100010011"]`
`F('10101', '00101')` `[true, "1010100001001011001111100011011"]`
`F('10101', '00011')` `[false, "101011111000010001100"]`
[Answer]
# [Go](https://go.dev), 208 bytes
```
import."slices"
func f(S,T[]int)(o[]int,m bool){s:=S
for len(o)<1||!Equal(s,S){l,L:=S[T[0]],len(S)-1
for _,i:=range T[1:]{l^=S[i]}
o,S=append(o,S[L]),append([]int{l},S[:L]...)}
O:=len(o)+1
return o,O&(O-1)<1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVPNjtMwEJa41U8xG6mVLabZmOWAAuHGrahI6S0EZLLOKiJ_JM6qKM2T7KVC4hkQb8EVngY7iXfpLkjEsmcyGX_fN2Pn5stVdfxei-SjuJJQiKwkWVFXjXKdtFDO106l62c_f9hYm2eJbB2SdmUCKQ1xF8VZqRitRosFfKiqnPWtH4QkrRrIZUkr9oIfDmevPnUipy2GrM9xoxOiXeTFMZqUkK35mP8eMz9oRKnF7CLux33-Tidm8UAqDANR17K8pNqNNjHD-XWk7vNBR_1N7LouG8jWDybqx5w0UnVNCRVuV3S75lrNMNX169G3sRBTNmXQEyVb1YIfQBTvetJPwBzBQzDrgFPkCV5Y10OOZk7DGwefVz4gqKaTAz6E0usdGjy1PkcL6N0D824J-AM6bun-g-3ir2yniN49bF14KvLWQA-EvGn03rykTqAfaJVoFBjXYfMJKtPB6QynhvZkIRKlTx8ha1-LvfmeUuXqvUrqHrlK1C0ji_PzLIX5nihX7muZKHmJMG1mcDjo3ELss0LkcBbMYBp9MWpKqUOX17C8ZhC81AZhqYBOlun5tnQM2QmrBZ-VmfAd7y0Zwr9FrVZ_iApmUWMxg-7WabNAX1ewzTK9VJ9rfdF1E5suUb1VNuqyTDCe1XOwFOYHm-_v8TjZ3w)
] |
[Question]
[
This is a micro-optimization challenge. The task is to sample from the maximally skewed stable distribution F(x;1,-1,Pi/2,0). See Table 1 of <http://arxiv.org/pdf/0908.3961v2.pdf> . It is easiest to describe how to do this using the following C code which uses the Mersenne Twister RNG C code from [here](http://www.cs.hmc.edu/~geoff/mtwist.html#downloading) .
```
#include <stdio.h>
#include <stdlib.h>
#include "mtwist.h"
#include <math.h>
int main(void) {
int i;
volatile double x;
mt_seed();
double u1;
double u2;
double w1;
double w2;
for(i = 0; i < 100000000; ++i) {
u1 = mt_drand();
u2 = mt_drand();
w1 = M_PI*(u1-1/2.0);
w2 = -log(u2);
x = tan(w1)*(M_PI_2-w1)+log(w2*cos(w1)/(M_PI_2-w1));
}
return EXIT_SUCCESS;
}
```
I compile with
```
gcc -Wall -O3 random.c mtwist-1.5/mtwist.c -o random -lm
```
The running time is 20 seconds taking `5,000,000` iterations per second.
There are two obvious ways of making this fast. The first is to choose a very fast uniform random number generator. If you choose to use anything but the Mersenne twister then you must run it through the Diehard tests and check the P-values provided. Use the code here <http://www.stat.fsu.edu/pub/diehard/> to do this. Your uniform random number generator must pass at least 15 of these tests.
The second way is to find fast micro-optimizations for the transcendental functions, perhaps using some CPU specific features. For example in my case these [features](http://www.cpu-world.com/CPUs/Bulldozer/AMD-FX-Series%20FX-8350.html) of the AMD FX-8350 CPU.
**Rules** The code must maintain at least 32 bits of accuracy throughout. The code should be compilable on ubuntu using easy to install free software only. Please provide full compile and run instructions. You should also provide a diehard log for any non Mersenne twister RNGs as was done for [Build a random number generator that passes the Diehard tests](https://codegolf.stackexchange.com/questions/10553/build-a-random-number-generator-that-passes-the-diehard-tests) . Note the very simple RNG that passes 15 tests in that link.
**Scores** You can report your score as the time taken by the code above divided by the time taken by your code on your own machine. For running your code you can use any compiler and compilation options you like. To test the code above you should use gcc 4.8 or later with -O3. If any submission take less than one second I will increase N by factors of 10 until the fastest submission takes longer than 1 second.
**Test machine** My test machine was a standard 8GB RAM ubuntu install on an AMD FX-8350 Processor. Your machine can be anything that supports gcc 4.8 or later.
The [Intel optimization manual](http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf) says
>
> If there is no critical need to evaluate the transcendental functions
> using the extended precision of 80 bits, applications should consider
> an alternate, software-based approach, such as a look-up-table-based
> algorithm using interpolation techniques. It is possible to improve
> transcendental performance with these techniques by choosing the
> desired numeric precision and the size of the look-up table, and by
> taking advantage of the parallelism of the SSE and the SSE2
> instructions.
>
>
>
According to this very helpful [table](http://www.agner.org/optimize/instruction_tables.pdf),`fcos` has latency 154 and `fptan` has latency `166-231` on my AMD FX 8350.
[Answer]
# GMPY2
Abuse of GMP. @OP the slowest part of the code is printing the numbers, if leaving them in memory is fine the code would be much much faster.
```
import math
import random
import gmpy2
from gmpy2 import mpz, mpfr
gmpy2.get_context().precision = 11 # 32 bits of accuracy
N = 100000000
random_state = gmpy2.random_state()
pi = math.pi
half_pi = pi / 2
size = 0
for i in range(N):
u1 = gmpy2.mpfr_random(random_state)
u2 = gmpy2.mpfr_random(random_state)
w1 = gmpy2.mul(pi, gmpy2.sub(u1,1/2))
w2 = -gmpy2.log(u2)
a = gmpy2.mul(gmpy2.tan(w1), gmpy2.sub(half_pi, w1))
b = gmpy2.div(gmpy2.log(gmpy2.mul(w2, gmpy2.cos(w1))), gmpy2.sub(half_pi, w1))
x = gmpy2.add(a, b)
```
[Answer]
# Numpy (score = 1.8)
In response to my previous code not being fast enough (I admit it was very slow), I used numpy which is extremely fast at working with large arrays of numbers and uses low level number libraries (BLAS). This is almost a direct translation of your code, but already is noticeably faster and has the bonus of being very readable.
```
import math
from numpy import *
pi = math.pi
half_pi = pi / 2
for i in range(10000):
u1 = random.rand(10000)
u2 = random.rand(10000)
w1 = pi * (u1 - 1/2)
w2 = -log(u2)
a = half_pi - w1
x = tan(w1)*a + log(w2*cos(w1)/a)
print("done")
```
I am running on i7 4770 with 8 gb RAM. Your code (including -O3 in GCC): 21.8 sec, my code: 11.8 sec.
[Answer]
# Nimrod (Score = 1.71, 4.8 vs. 8.2 seconds)
Observe that x->[[cos x, -sin x], [sin x, cos x]] is a group isomorphism between [0, 2\*pi) (with respect to addition modulo 2\*pi) and the rotation matrices (as a subgroup of SL(2, R)).
Because `w1` is effectively of the form `pi*k/2^32`, where `k` is a signed 32-bit integer, we can split k in two 16-bit words, `h` and `l` and always represent `w1` as the sum of `pi*h/2^16+pi*l/2^32` and tabulate rotation matrices for both addends in `2*sizeof(double)*2^16` bytes each. We can then derive `sin(w1)` and `cos(w1)` from the product of the two rotation matrices per the isomorphism above (and `tan(w1)` as `sin(w1)/cos(w1)`).
The code below is in Nimrod, but should be directly portable to C, with the necessary renaming to integer and float types (`float64` in Nimrod corresponds to `double` in C, and `int` corresponds to `intptr_t`, i.e. 64-bit on most modern architectures) and essentially no change in runtime. It currently does not print anything, but uses a volatile variable as described in my earlier comment to avoid the code being optimized away.
Further speedups may come from looking at how to make the computation of the natural logarithm cheaper (and, of course, replace the Mersenne Twister with a different RNG, but that's not very interesting).
Compile with `nimrod cc -d:release random.nim`.
Compile with `-d:validate` instead to check floating point errors with respect to the normal sin/cos calculations.
Update: Added an option to use an Xorshift RNG, enabled by compiling with `-d:xorshift`. This reduces runtime by approximately a quarter. Also fixed RNG generation to avoid `u1 == 0` or `u2 == 0`.
```
import math, mersenne, unsigned
# It is sufficient to represent the rotation matrix
# [ [ cos x, -sin x], [sin x, cos x] ]]
# by just the values in the left column/bottom row.
type RotMat = tuple[sine, cosine: float64]
var tab1, tab2: array[65536, RotMat]
for i in 0..65535:
tab1[i] = (sin(pi*float64(i-32768)/float64(65536)),
cos(pi*float64(i-32768)/float64(65536)))
tab2[i] = (sin(pi*float64(i)/float64(65536*65536)),
cos(pi*float64(i)/float64(65536*65536)))
proc `*`(x, y: RotMat): RotMat {.inline.} =
result.cosine = x.cosine*y.cosine-x.sine*y.sine
result.sine = x.cosine*y.sine+x.sine*y.cosine
proc sincos(x: int): RotMat =
let r1 = tab1[(x shr 16) and 65535]
let r2 = tab2[x and 65535]
return r1*r2
when defined(xorshift):
type RNGState = object
x, y, z, w: uint32
proc getNum(s: var RNGState): int =
let t = s.x xor (s.x shl 11)
s.x = s.y; s.y = s.z; s.z = s.w
s.w = s.w xor (s.w shr 19) xor t xor (t shr 8)
result = int(s.w)
var rng = RNGState(x: 1)
else:
var rng = newMersenneTwister(1)
const maxRand = 1 shl 32
for i in 1..100_000_000:
var t1, t2: int
while true:
t1 = rng.getNum; if t1 != 0: break
let u1 = t1/maxRand
while true:
t2 = rng.getNum; if t2 != 0: break
let u2 = t2/maxRand
let w1 = pi*(u1-1/2)
let w2 = -ln(u2)
when defined(original):
let (sw1, cw1) = (sin(w1), cos(w1))
else:
let (sw1, cw1) = sincos(t1)
var x {.volatile.} = sw1/cw1*(pi/2-w1)+ln(w2*cw1/(pi/2-w1))
when defined(validate):
var x2 = sin(w1)/cos(w1)*(pi/2-w1)+ln(w2*cos(w1)/(pi/2-w1))
echo sw1-sin(w1)
echo cw1-cos(w1)
echo x-x2
```
] |
[Question]
[
Code-golfing is incredibly fun to do, trying to solve the given problem is one thing but the real challenge is getting your code as short as possible.
Some languages are perfect for golfing because of their short commands, sadly Delphi isn't one of them.
I'm looking for tips that are useful for golfing in Delphi.
Tips like "Use 1 letter variables" don't really count in my opinion since that is pretty obvious.
Tips I learned working with Delphi or found in other peoples answers so far are:
* Semicolon isn't always required (Example 1)
* Use `int8` or `int16` as datatype rather than integer (saves 3 or 2 characters)
* Combine string manipulations(Example 2)
### Example 1:
```
Procedure Example1(i:int16);
var x:int16;
begin
for x:=0to 99do
if i=1then
inc(i)//Semicolon not allowed because of "else"
else
i:=i+3//No semicolon required
end;//Semicolon required
```
### Example 2
```
function WrongExample2(myString:string):string;
const
f:string='The result of your manipulation is: %s';
begin
myString:= StringReplace(s,'x', '_', [RfReplaceAll]);
Result := Format(f,[myString])
end;
function CorrectExample2(myString:string):string;
const
f:string='The result of your manipulation is: %s';
begin
Result := Format(f,[StringReplace(s,'x', '_', [RfReplaceAll])])
end;
```
[Answer]
### Group definitions by keyword
This will save you from having to retype the keyword.
```
type WD=(Su,M,Tu,W,Th,F,Sa);M=(Ja,F,Mr,Ap,My,Jn,Jl,Ag,S,O,N,D);
const A=1;B=2;
var X,Y,Z:string;
```
### Use function name instead of `Result` for holding function return value
Functions' return value can be referenced by the function name. Unless the function is required to be a particular name it will usually be shorter than `Result`.
```
function F:Int8;
begin
F:=1
end;
```
Using the `Exit` short hand (Delphi 2009 or newer) is shorter than assigning to `Result` also:
```
function F:Int8;
begin
Exit(1)
end;
```
### Use comma-separated variable declarations
```
procedure Z(A,B,C: string);
var A,B,C:string;
```
### Constants usually require fewer characters than variable declarations
With the exception of the above mentioned comma separated variable declarations constant declarations use fewer characters than variable declarations when initialization is taken into consideration.
```
const A=1; // True constant = 10 chars
const A:Int8=1; // Typed constant = 15 chars
var A:Int8; // Variable = 11 chars
begin
A:=1; // + 5 chars for initialization = 16 chars
```
### Use `set` data types and their operators
If ordering isn't important, then use sets instead of arrays or lists for more concise statements. Unfortunately you are limited to a maximum of 256 elements in a set
```
+ The union of two sets
* The intersection of two sets
- The difference of two sets
= Tests for identical sets
<> Tests for non-identical sets
>= Is one set a subset of another
<= Is one set a superset of another
in Test for set membership of a single element
```
The `in` operator is particularly useful when testing if a variable equals any one of possible values. Silly example using `in` and `..` (the range operator):
```
// expensive:
if ( A = 1 ) or ( A = 2 ) or ( A = 3 ) or ( A = 6 ) then ...;
if ( A > 0 ) and ( A < 4 ) or ( A = 6 ) then ...;
// better:
if A in [ 1 .. 3, 6 ] then ...;
```
] |
[Question]
[
Write a program that takes a list of n space-separated integers, and outputs a permutation of that list using a maximum of 2\*n comparisons.
It should loop this until an empty line is input. Alternatively, it can accept inputs until an empty line is given, then output all the permutations.
Though your program only has to work on integers, it should be possible to implement your algorithm for any comparable data structures. For example, using `sign(a-b)` to get extra comparisons is illegal, because the same algorithm can't be applied to data structures without numerical values.
Example session:
```
>0 1 2 3 4
0 1 2 3 4
>7 9 2 1
1 2 7 9
>6 7 4 5 2 3 0 1
0 2 3 1 4 5 6 7
>
```
or
```
>0 1 2 3 4
>7 9 2 1
>6 7 4 5 2 3 0 1
>
0 1 2 3 4
1 2 7 9
0 2 3 1 4 5 6 7
```
note: `>` shouldn't actually be printed, it's just being used to notate input vs output.
## Scoring
Scoring is based mostly on how well sorted the permutations are, but also favours concise code.
Run your program with [this file](https://www.dropbox.com/s/q6gfpvajjor0xcq/input.txt) as input. Use your program's output as input to this python script. This script works under both python 2.7 and 3.3. Other versions weren't tested.
```
import sys
def score(l):
n = len(l)
w = n**2 // 2
s = sum(abs(l[i]-i)for i in range(n))
return float(s)/w
s = 0.0
for i in range(40000):
s += score([int(n) for n in sys.stdin.readline().split()])
print (int(s))
```
**Your score is the output of the above script plus the length of your program**
## Explanation of Scoring
In the input file, there are 1000 lists for each length n in the range `10 <= n < 50`. In total, there are 40000 lists. No two elements of a list will be equal.
To score a list, we define the unsortedness of a list as the sum of distances of each element from where it should be. For example, for the list `[0,1,4,3,2]`, the unsortedness is 4, because 4 and 2 are each 2 positions from where they should be, and the rest of the numbers are correct.
The worst case unsortedness of a list of length n is `n^2 / 2`, using integer division.
The score of a list is its unsortednes divided by the maximum unsortedness. This is a number between 0.0 (sorted) and 1.0 (reversed).
Your total score is the sum of all scores in the input rounded down to an integer, plus the length of your program. Because there are 40000 cases, a better pseudo-sort is likely better than shorter code, but if there is some optimal solution, then the shortest implementation of that solution will win.
[Answer]
# Python, 7910 (7704 + 206)
This was inspired by shell sort. I found relatively good coefficients for the gap sequence (`g`) by checking a few hundred alternatives. The number of comparisons is limited by counting explicitly (`n`).
```
s=1
while s:
s=map(int,raw_input().split());k=len(s);n=2*k;g=13*k/23
while g:
for i in range(g,k):
n-=1
if n<0:break
if s[i]<s[i-g]:s[i],s[i-g]=s[i-g],s[i]
g=3*g/5
print' '.join(map(str,s))
```
[Answer]
**Ruby, 10140** (9988 + 152)
```
def q a
p=a.pop
l,m=a.partition{|x|x<p}
[l,p,m]
end
while a=gets
a=a.split.map(&:to_i)
l,p,m=q a
puts (q(l)+[p]+q(m)).flatten.join(" ")
end
```
This simply performs two rounds of quicksort. It removes the last element, then divides the remaining array into those less than and those greater than that element (n-1 comparisons). Then it does the same thing to those two (n-3 comparisons) and joins the result in order. Total comparisons are 2\*n - 4 (worst case 2\*n - 2), so there's definitely room for improvement.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/7168/edit)
On a road trip, N people pay for fuel. Each pays a different amount. At the end of the trip, calculate the minimum number of transactions so that each person has paid the same amount.
e.g. on the road trip, these people pay for fuel
* Dave - $50
* John - $25
* George - $5
* Barry - $0
After the road trip:
* Barry pays Dave $20
* George pays John $5
* George pays Dave $10
---
Added: The output of the program should list the transactions.
Bonus points if the solution is written in Visual Basic.
[Answer]
# Python, 308 Characters
I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)
I didn't try and golf this very much because I'm not sure if that's the goal. This code is guaranteed to return a solution with the minimum number of transactions.
```
def t(p):
a=sum(p)/float(len(p))
q=[([],p)]
l=len(p)
r=range(l)
while q:
n=q.pop(0)
g=1
for i in r:
d=n[1][i]-a
if d>0:
g=0
for j in r:
if n[1][j]<a:
v=min(d,a-n[1][j])
y=list(n[1])
y[i]-=v
y[j]+=v
if i!=j:q+=[(n[0]+[(j,i,v)],y)]
if g:return n[0]
```
## Usage
The `t` function takes a list of the amounts that each person paid. Using the example from the question:
```
> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]
```
So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.
] |
[Question]
[
## Task
>
> Make a complete program or a function which calculates sum of all temperatures which, when written in [Celsius](http://en.wikipedia.org/wiki/Celsius) and [Fahrenheit](http://en.wikipedia.org/wiki/Fahrenheit) scale, are [anagram](http://en.wikipedia.org/wiki/Anagram) of each other.
>
>
>
## Description
For example, `275` degree Celsius = `527` degree Fahrenheit, and `527` is anagram of `275`. Non-integer temperatures (either in degree Celsius or degree Fahrenheit) and temperatures colder than 0 degree Celsius (like `-40C` = `-40F`) will *not* be considered.
## Input
Input is a temperature in format `([1-9][0-9]*)(C|F)` (example: `42F` = 42 degree Fahrenheit, `125C` = 125 degree Celsius, ...).
The program should be able to handle temperature less than `1000000C`.
## Output
Output is sum of all temperatures less than the temperature given by input, which, when written in Celsius and Fahrenheit scale, are anagram (without leading zeroes) of each other. Output will be two integers separated by a space. The first one will be the sum in degree Celsius, and the second one will be the sum in degree Fahrenheit.
If there's no such temperature, return or output `0 0`.
## Example
* Input : `42C`
+ There's no such temperature
+ Output : `0 0`
* Input : `300C`
+ There's one temperature : `275C` = `527F`
+ Output : `275 527`
* Input : `10000F`
+ There're three temperatures : `275C` = `527F`, `2345C` = `4253F`, and `4685C` = `8465F`
+ Output : `7305 13245`
[Answer]
## GolfScript, 65 61 characters
```
)\~{32- 9/5*}@70=*5/),0.@{.5*.`$@9*32+.`$@=:f*@+\f*@+\}%]' '*
```
*Edit:* incorporating the reduce operation into the loop saved 4 characters
[Answer]
## Mathematica, 77
I wish I could get this shorter, but working with function names like `IntegerDigits` I think this is about the best I can do.
```
Grid@{Total@Select[{#,9/5#+32}&~Array~#,SameQ@@(Sort@IntegerDigits@#&)/@#&]}&
```
[Answer]
## C# - 166
Due to the small number of matches, I thought it might be easier to hardcode the outputs:
```
void F(string i){int n=int.Parse(i.Substring(0,i.Length-1));
n=i.Last()=='C'?n:5*(n-32)/9;
Console.Write(n>4685?"7305 13245":n>2345?"2620 4780":n>275?"275 527":"0 0");}
```
### Edit: 352
To do it right requires a bit more work. Here's a first attempt at using a whole pile of linq:
```
using System;
using System.Linq;
class P{static void Main(string[] i)
{
int n=int.Parse(i[0].Substring(0,i[0].Length-1));
n=i[0].Last()=='C'?n:5*(n-32)/9;
var q=Enumerable.Range(1,n).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray()));
Console.Write(q.Sum()+" "+q.Sum(x=>x*9/5+32));
}}
```
Maybe the 'use a pile of linq instead of a loop' approach hurt me too much. I'll try and shorten it.
### Edit 2: 356
Since I'm already way behind in raw count, here's a one-liner from hell:
```
Console.Write(Enumerable.Range(1,i.Last()=='C'?int.Parse(i.Substring(0,i.Length-1)):5*(int.Parse(i.Substring(0,i.Length-1))-32)/9).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray())).Aggregate("0 0",(a,t)=>(int.Parse(a.Split(' ')[0])+t)+" "+(int.Parse(a.Split(' ')[1])+t*9/5+32)))
```
[Answer]
## Perl, 182 characters
```
sub F{5*($_[0]-32)/9}sub C{$_[0]*9/5+32}sub O{join'',sort split//,shift}<>=~/.$/;$c=$&;@s=(0,0);map{$v=&$c($_);if(O($_)==O($v)){$s[0]+=$_;$s[1]+=$v;}}0..$`;@s=sort{$a<=>$b}@s;say"@s"
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~44~~ 47 bytes
```
0&)Uqw70=?32- 5*9/]OOhw:"@t9*5/32+VY@Um?@4MhvXs
```
[Try it online!](https://tio.run/##y00syfn/30BNM7Sw3NzA1t7YSFfBVMtSP9bfP6PcSsmhxFLLVN/YSDss0iE0197BxDejLKL4/391IwsDZ3UA "MATL – Try It Online")
*(+3 bytes to output `0 0` for no such temperatures (instead of empty output).)*
] |
[Question]
[
## Challenge
You are to write the shortest complete program that takes a string as input from STDIN and decomposes it as far as possible, and prints the composition to STDOUT.
To decompose a string, your program finds a substring (of length greater than 1) within the original string, the repetitions of which take up a much of the string as possible. It then creates several new strings, one of which is that substring and the others are the original, split apart at where the substring occurred. You then repeat this process of finding a substring whose repetitions take up as much of those strings as possible.
The end of input is reached when there is a newline (`/n`).
Output should consist of each substring in the order that it is found, followed by two newlines, followed by everything left at the end of decomposition sorted from longest to shortest, all separated by line breaks.
## Example
**input**
```
Happy birthday to you! Happy birthday to you! Happy birthday to somebody! Happy birthday to you!
```
The longest repeated substring is `Happy birthday to you!`; however, the substring `Happy birthday to` (with a space after the "to") takes up more space because there is one more repetition of it. The `Happy birthday to` is outputted. You then end up with several new strings.
```
Happy birthday to (with space at the end)
you! (with space)
you! (with space)
somebody! (with space)
you!
```
Here, the substring `you!`is repeated the most. Even though it is not repeated within any individual string, it is repeated multiple times throughout all of the strings. The `you!` is outputted. Now you have
```
Happy birthday to (with space)
you!
(lone space character)
(lone space)
somebody! (with space)
```
Here, the substring `y`(with space) is repeated the most. The `y` is outputted. Now you have
```
Happ
birthda
to (with space)
y (with space)
you!
(lone space character)
(lone space)
somebody! (with space)
```
As far as I can tell, there are no more substrings of length > 1 (the spaces are only one character). You then output each substring that you found, followed by what is above.
**Total Output**
```
Happy birthday to
you!
y
somebody!
birthda
Happ
you!
to
y
```
There should be two lines of just a space at the end, but those are not being displayed. There should also be a space after that single y.
[Answer]
### Ruby, 232 characters
```
i=[gets.chop]
while l=((0..-2+n=(v=i*'').size).map{|s|(s+1..n).map{|m|c=v[s..m]
u=[i.map{|t|t.split(c)},c].flatten
v.size>(w=(u*'').size)&&[w,c,u]}}.flatten(1)-[false]).sort[0]
puts l[1]
i=l[2]
end
puts
i.sort_by!{|k|-k.size}
puts i
```
This code reflects my first idea towards the problem. Actually it took much more characters than I thought initially. Nevertheless I still hope to find a shorter solution using a different approach.
[Answer]
If you allow for the weak definition of a substring, then here's a trivial solution.
**R, 9 characters (10 with `\n`)**
```
d=scan()
d
```
But I suspect you mean strict substring, in which case parroting back the input string will not suffice :-)
**R, not yet condensed**
```
d <- "Happy birthday to you! Happy birthday to you! Happy birthday to somebody! Happy birthday to you!"
#d=scan()
# Shorten things
l=list
# Break up into consituent parts
e=strsplit(d,"")[[1]]
g=l()
for(i in 1:nchar(d)) g[[i]]=embed(e,i)
g=lapply( g, function(x) apply(x,1,paste,collapse="") )
# Find max coverage (function takes each element of the g list and returns max X its length) (if type=2 then returns the string instead)
m=function(x,t=1) {
r=rle(sort(x))
w=which.max(r$l)
if(all(r$l[w]<2)) return(0)
v=r$v[w]
switch(t,r$l[w]*nchar(v),v)
}
m(g[[which.max(sapply(g,m))]],2)
```
Which returns `" ot yadhtrib yppaH !uoy ot yadhtrib yppaH"`.
Easy enough to reverse and to iterate this over the remaining string, but I'm going to hold off pending clarification of whether overlapping substrings are allowed. I suspect not from the example, but this one has more coverage (82 characters) if so.
] |
[Question]
[
I'd be interested to see who can come up with the fastest function to produce multiplication tables, in the following format:
```
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
```
Use the following template to benchmark your code using a 12-width table, and post your code and the resulting time here.
```
#!/usr/bin/python
import timeit
cycles = 100000
referencecode = r'''
def multable(width):
'\n'.join(''.join('{0:4}'.format(x*y) for x in range(1,width+1)) for y in range(1,width+1))
'''
yourcode = r'''
def multable(width):
pass # Your function here
'''
referencetime = timeit.Timer('multable(12)', setup=referencecode).timeit(number=cycles)
yourtime = timeit.Timer('multable(12)', setup=yourcode).timeit(number=cycles)
print 'Your code completed', referencetime / yourtime, 'times faster than the reference implementation'
```
[Answer]
## About 352 times faster, according to the benchmark code
(on my machine)
Python 2.7
Exactly how much faster it is will vary widely between machines. I tested it on my web server also and there it was only 288 times as fast.
```
import itertools as i, operator as o
def multable(width, m={}):
if not width in m.keys():
m[width] = '\n'.join(['%4d'*width]*width)%tuple(i.starmap(o.mul,i.product(range(1,width+1),repeat=2)))
return m[width]
```
The actual algorithm is only about 1.25 times as fast as the reference one, but if you have a function which is called often, caching the result saves a lot of time.
[Answer]
```
def multable(width):
R=range(1,width+1)
M=[i*j for i in R for j in R]
return(('%4d'*width+'\n')*width)%tuple(M)
```
about 3.3x faster than the reference implementation.
[Answer]
My approach (python2.7):
# 1.63x Faster
```
from itertools import imap, izip, starmap, product
from operator import mul
def multable(width):
return '\n'.join(imap(''.join, izip(*((imap('{:4}'.format, starmap(mul, product(xrange(1,13), repeat=2))),) * 12))))
```
# 2.32x Faster
```
from itertools import starmap, product
from operator import mul
def multable(width):
return (('{:4}' * width + '\n') * width).format(*starmap(mul, product(xrange(1,13), repeat=2)))
```
] |
[Question]
[
*This is a sequel to [Ragged list pattern matching](https://codegolf.stackexchange.com/questions/246280/ragged-list-pattern-matching). In this challenge, the wildcard may match a sequence of items of any length instead of just a single item.*
Given a pattern and a ragged list of integers, your task is to decide whether the pattern matches the ragged list.
The pattern is also represented by a ragged list. But in addition to positive integers, it may contain a wildcard value.
Here is the rule for matching:
* A positive integer matches the same positive integer.
* The wildcard value matches a sequence of items (integer or list) of any length, including the empty sequence.
* A ragged list matches a ragged list if each item in the pattern matches the corresponding item in the list.
For example, if we write the wildcard as `0`, then the pattern `[0, [4, [5], 0]]` matches the ragged list `[[1, 2], [3], [4, [5]]]`: here the first `0` matches the sequence `[1, 2], [3]`, and the second `0` matches the empty sequence.
You may choose any fixed value as the wildcard, as long as it is consistent.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
This is [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"). You may use your language's convention for truthy/falsy, or use two distinct, fixed values to represent true or false.
## Testcases
Here I use `0` to represent the wildcard. The input here are given in the order `pattern, ragged list`.
### Truthy
```
[], []
[0], []
[0], [1, 2]
[0], [[[]]]
[0, 0], [1, 2, 3]
[1, 0], [1, [[2, 3]]]
[1, 0, 2], [1, 2, 2, 2]
[1, 0, [2, 3]], [1, [2, 3]]
[1, [2, 0], 4], [1, [2, 3], 4]
[0, [4, [5], 0]], [[1, 2], [3], [4, [5]]]
```
### Falsy
```
[1], []
[[]], []
[[0]], [3]
[[4]], [4]
[1, 0], [2, 1]
[[0]], [[1], [2]]
[1, 0, 2], [1, 2, 3]
[1, 0, 2, 0], [1, [3, 2, 3]]
[1, [0, 2], 4], [1, [2, 3], 4]
[[0], [4, [5], 0]], [[1, 2], [3], [4, [5]]]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 71 bytes
```
>
,>
<,
<
~(L$`^.+
\n$&$
_,
(\d+,|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>,)$*
```
[Try it online!](https://tio.run/##jY4xDsIwDEV3nyJDQQk1SKVlIkovwAaba1ykMrAwIDYKVy9Jm1YgMSAlyvf3d/xu5/vlesq6md7XWzjUStPjyaYWa63rHKADi2DhpXdJfVylUF2TeQKCoKsmxdZqXVpx1rT@XYpzpq2aFk2qSy3maByaZNF1xFtFDCSfb4ZqPWoiZq@9NbaI1qjyyQ3ZODOcyY@5ODUUMGphVMVXL9R@qS8LfzccMj1Bj@OtEIm9/qOITDyKIZ8HWfSy@CD3O7JfyHlkkmHLLyYS/pPqDQ "Retina – Try It Online") Takes two newline-separated <>-wrapped lists but link is to test suite that deletes spaces, splits on semicolons and converts other types of brackets for convenience. Uses \_ to represent the wild card. Explanation: Based on my Retina answer to [Ragged list pattern matching](https://codegolf.stackexchange.com/q/246280/).
```
>
,>
<,
<
```
Ensure that non-empty lists end in a comma.
```
~(
```
Evaluate the result of the transformations below on the comma-safe input. Since they result in a single line, this makes Retina attempt to match the comma-safe input against the result.
```
L$`^.+
\n$&$
```
Take only the first line of the input and wrap it in `\n` and `$` so that it will match against the second line of the input.
```
_,
(\d+,|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>,)$*
```
Replace each `_,` with a match against any number (`$*` represents a literal `*` which would otherwise be the string repetition operator) of comma-safe non-negative integers or lists, using a .NET balancing group to ensure that the lists are properly balanced. A named capturing group `?<_>` is used here because .NET allows capturing groups to be reused in this way and it's golfier than calculating the capturing group number.
[Answer]
# [Haskell](https://www.haskell.org), 89 bytes
**Assumption**: ragged lists are defined in the following way:
```
data RL a = L [RL a] | N a | W
deriving Eq
```
**Solution**:
```
L(W:p)#L x|L p#L x=1>0
L(W:p)#L(_:x)=L(W:p)#L x
L(q:p)#L(y:x)=q#y&&L p#L x
a#b=a==W||a==b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rVRdS8MwFH3xKb_iQmU0kIH7EKQYHwQFoexBhCIjjMxms1i7rs1kg_4TX_Yi_ib9NSbNurVbO30QSm_IOefec3ubvH8-8_RFhOH6i_hccrh3gQMFF4Z6xSCDgdrIwEMAvkiCtyCaws38YyEn7YuvR9f2nBhbLiwzF2IdaefqDBXb9shZYrojKWBugJUG5taq1droELfGlFPqZZl6j02B75ORFKlMwXFgaF_PZiEBWxm7iyQBEzFmyHAoDJVJ-yFZCKKiaoER3QjDmOwB3m_IADpEdd5tZpiHsToGgb00-tWrYeZ4mWuybhV12Y3GuDso0m1yXagq2St1d9sN6oKj_Q6g36A2WO1HyWn9TTxnOhPbtdyptNRjB_ytsVsepirtxlh1lCUsH88R0GO7YrUE3cjWRn3x0vTy_jvHS5Ud62YbkzaMt85oSXDwLylFSdskNtMxBf842P32_mW4DCE0UcfYtjBK9HGeQMylFEkECZ9Ohe8GqQRKQSxj8SSFr-4lu1grMxsyKbExhss25PcDQ688iFTaOAkiCafAIx8Sc8-s1yb-AA)
] |
[Question]
[
[Nerdle](https://www.nerdlegame.com/) is a Wordle variant, in which instead of words, the answers are equations. Each equation entered in the game must be a valid one.
Examples: `13³-1=2196`, `(1/1)²*8=8`, `(((3)))²=9`
The task is to generate and output to a .txt file, one equation per line, all possible 10 character equations that could be an answer for the game (specifically the Maxi Nerdle) as fast as possible (note that the code should be limited to 100KB to avoid hardcoding).
**The possible symbols for a Maxi Nerdle equation are:**
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, \*, /, ², ³, ), (, =
**The rules that make an equation a possible answer to the game, besides being mathematically true, are:**
* There are no leading zeros
* There are no lone zeros (There can't be a `+0` in the equation, for example)
* There are no operators in sequence, that is, +, -, \*, / can't be adjacent to each other (`+++----1=1`, for example)
* The right-hand side of the equation must be a non-negative integer
* Operations must be explicit, that is, `9(10-8)=18` is not valid, for example, as there should be a \* between 9 and (
* There can only be one `=` symbol
Also note that commutativity doesn't apply. If the order of the numbers changes, it must be treated as a different equation.
**Expected output**
For 10 characters long equations with the Maxi Nerdle symbols, there should be 2,177,017 equations. They can be viewed [here](https://github.com/PedroKKr/Nerdle-Equations/blob/main/NerdleMaxi.txt) (this was generated in 1 hour with a simple Python script).
**Score**
As this is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, the score will be based on the time taken to run it on my computer (Windows 10). Here are my specs:
* Intel(R) Core(TM) i5-9300H CPU 2.40GHz
* 8 GB RAM with 2667 MHz speed
Please include instructions for how to compile/run your code.
[Answer]
# C, about 6.3 seconds on my M1 MacBook Pro
Here's a start. I think there is a lot more optimisation to do here.
All credit for the [recursive descent parser](https://stackoverflow.com/a/9329509/2113226) to @Henrik. I have lightly modified it to operate on doubles instead of ints, and to calculate 2nd and 3rd powers.
* Compile with `cc -O3 nerdle.c -o nerdle`
* Run as `time ./nerdle`. Generates a file `nerdle.txt` in the current directory.
On MacOS, the default `cc` is clang. `-O3` sped up runtime by a factor of 4, over default optimisation. This should compile just as well with gcc.
The `gen_*()` functions recursively generate all valid expressions. Then these are evaluated with a recursive descent parser, and output if mathematically true.
I have taken care to output the results in the same order as NerdleMaxi.txt, so they may easily be verified with `diff` / `cmp`.
This code is not pretty, and would benefit from a good deal of deodorising.
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
char * expressionToParse;
FILE *fp;
char peek()
{
return *expressionToParse;
}
char get()
{
return *expressionToParse++;
}
double expression();
double number()
{
double result = get() - '0';
while (peek() >= '0' && peek() <= '9')
{
result = 10*result + get() - '0';
}
return result;
}
double factor()
{
if (peek() >= '0' && peek() <= '9')
return number();
else if (peek() == '(')
{
get(); // '('
double result = expression();
get(); // ')'
return result;
}
else if (peek() == '-')
{
get();
return -factor();
}
return 0; // error
}
double expon()
{
double result = factor();
while (peek() == 's' || peek() == 'c')
if (get() == 's')
result *= result;
else
result *= (result * result);
return result;
}
double term()
{
double result = expon();
while (peek() == '*' || peek() == '/')
if (get() == '*')
result *= expon();
else
result /= expon();
return result;
}
double expression()
{
double result = term();
while (peek() == '+' || peek() == '-')
if (get() == '+')
result += term();
else
result -= term();
return result;
}
static void gen_nz_digit(int level, int br_level, char * buf, int ndigits);
static void gen_digit(int level, int br_level, char * buf, int ndigits);
static inline void gen_oper(int level, int br_level, char * buf, int ndigits);
static inline void gen_squared(int level, int br_level, char * buf, int ndigits);
static inline void gen_cubed(int level, int br_level, char * buf, int ndigits);
static inline void gen_open(int level, int br_level, char * buf, int ndigits);
static inline void gen_close(int level, int br_level, char * buf, int ndigits);
static inline void gen_equals(int level, int br_level, char * buf, int ndigits);
static void
gen_nz_digit (int level, int br_level, char * buf, int ndigits)
{
int i;
if (level >= 8) {
return;
}
int next_level = level + 1;
for (i = 1; i < 10; i++) {
buf[level] = '0' + i;
gen_equals(next_level, br_level, buf, 0);
gen_digit(next_level, br_level, buf, 1);
gen_oper(next_level, br_level, buf, 0);
gen_squared(next_level, br_level, buf, 0);
gen_cubed(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
}
static void
gen_digit (int level, int br_level, char * buf, int ndigits)
{
int i;
if (level >= 8) {
return;
}
if (ndigits >= 4) {
return;
}
int next_level = level + 1;
for (i = 1; i < 10; i++) {
buf[level] = '0' + i;
gen_equals(next_level, br_level, buf, 0);
gen_digit(next_level, br_level, buf, ndigits + 1);
gen_oper(next_level, br_level, buf, 0);
gen_squared(level +1, br_level, buf, 0);
gen_cubed(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
buf[level] = '0';
gen_equals(next_level, br_level, buf, 0);
gen_digit(next_level, br_level, buf, ndigits + 1);
gen_oper(next_level, br_level, buf, 0);
gen_squared(level +1, br_level, buf, 0);
gen_cubed(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
static inline void
gen_oper (int level, int br_level, char * buf, int ndigits)
{
if (level >= 7) {
return ;
}
int next_level = level + 1;
buf[level] = '-';
gen_nz_digit(next_level, br_level, buf, 0);
gen_open(next_level, br_level, buf, 0);
buf[level] = '+';
gen_nz_digit(next_level, br_level, buf, 0);
gen_open(next_level, br_level, buf, 0);
buf[level] = '*';
gen_nz_digit(next_level, br_level, buf, 0);
gen_open(next_level, br_level, buf, 0);
buf[level] = '/';
gen_nz_digit(next_level, br_level, buf, 0);
gen_open(next_level, br_level, buf, 0);
}
static inline void
gen_squared (int level, int br_level, char * buf, int ndigits)
{
if (level >= 8) {
return;
}
int next_level = level + 1;
buf[level] = 's';
if (level >= 3) {
gen_equals(next_level, br_level, buf, 0);
}
gen_oper(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
static inline void
gen_cubed (int level, int br_level, char * buf, int ndigits)
{
if (level >= 8) {
return;
}
int next_level = level + 1;
buf[level] = 'c';
if (level >= 2) {
gen_equals(next_level, br_level, buf, 0);
}
gen_oper(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
static inline void
gen_open (int level, int br_level, char * buf, int ndigits)
{
if (level >= 7) {
return;
}
int next_level = level + 1;
buf[level] = '(';
br_level++;
gen_nz_digit(next_level, br_level, buf, 0);
gen_open(next_level, br_level, buf, 0);
}
static inline void
gen_close (int level, int br_level, char * buf, int ndigits)
{
if (level >= 8) {
return;
}
int next_level = level + 1;
buf[level] = ')';
br_level--;
gen_equals(next_level, br_level, buf, 0);
gen_oper(next_level, br_level, buf, 0);
gen_squared(next_level, br_level, buf, 0);
gen_cubed(next_level, br_level, buf, 0);
if (br_level > 0) {
gen_close(next_level, br_level, buf, 0);
}
}
static inline int
int_len (int n) {
if (n < 10) {
return 1;
} else if (n < 100) {
return 2;
} else if (n < 1000) {
return 3;
} else if (n < 10000) {
return 4;
} else if (n < 100000) {
return 5;
} else {
return 6;
}
}
static inline void
gen_equals (int level, int br_level, char * buf, int ndigits)
{
double result;
double int_part;
double frac_part;
if (br_level > 0) {
return;
}
buf[level] = '\0';
expressionToParse = buf;
result = expression();
frac_part = modf(result, &int_part);
if (frac_part == 0) {
int rhs = (int)int_part;
if (rhs >= 0) {
if (level + int_len(rhs) == 9) {
char out_str[20];
char *ptr = out_str;
char tmp_str[20];
strcpy(out_str, buf);
while (NULL != (ptr = strchr(ptr, 's'))) {
strcpy(tmp_str, ptr + 1);
sprintf(ptr, "²%s", tmp_str);
}
ptr = out_str;
while (NULL != (ptr = strchr(ptr, 'c'))) {
strcpy(tmp_str, ptr + 1);
sprintf(ptr, "³%s", tmp_str);
}
fprintf(fp, "%s=%d\n", out_str, rhs);
}
}
}
}
int
main (int argc, char ** argv)
{
fp = fopen("nerdle.txt", "w");
char buffer[20] = "";
gen_nz_digit(0, 0, buffer, 0);
gen_open(0, 0, buffer, 0);
fclose(fp);
}
```
] |
[Question]
[
Given an integer \$n > 1\$, output a balanced binary tree with \$n\$ leaf nodes.
The tree should be constructed out of (space), `\` and `/` (slashes). Each slash represents a branch.
* A node is represented by adjacent slashes: `/\`. There must be a root node at the top of the tree (i.e. the first row of the output).
* To construct the next row of the output, take each slash in the previous row at position \$i\$. You can do one of the following:
+ Terminate the branch: put a space. That branch now ends in a leaf.
+ Extend the branch: put a slash in the same direction as the slash above (i.e. if there's a `\` in column \$i\$ above, put a `\` in column \$i+1\$; if there's a `/` in column \$i\$ above, put a `/` in column \$i-1\$.
+ Create another branch: put an internal node (`/\`) at the appropriate location below the slash above.
* You cannot have different branches converge - i.e. no `\/`.
Since this is a *balanced* binary tree, at each branching off point, the height of the left and right subtrees cannot differ by more than one. In other words, you must fill up level \$l\$ with leaves/branches before putting leaves/branches in level \$l+1\$.
### Examples
A balanced binary tree with \$2\$ nodes could look like:
```
/\
```
or
```
/\
/ \
```
but not, for example,
```
/\
\/
/\
```
If \$n=3\$, you could have
```
/\
/\ \
```
or
```
/\
/ /\
/ / \
```
If \$n=4\$, you could have
```
/\
/ \
/\ /\
```
but not
```
/\
/\/\
```
or
```
/\
\
/\
/\
```
Standard loopholes apply, shortest code wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
Nθ≔L↨⊖θ²ηFηF⌊⟦X²ι⁻θX²ι⟧«≔X²⁻⊖ηιζJ×ζ⊕×⁴κ±⊖ζ↗ζ↓↘ζ
```
[Try it online!](https://tio.run/##VY47bwIxEIRr@BVbriVT8KhIFUQDAoQQVFGKy2U5W2D78AOkQ/x2Z3kouTS72plPM1uqwpeuOOY8s3WKq2S@yONJvHXfQ9CVxQXZKiqcFIFwSqUnQzbSNyMSBoKHYnbvPKAS8NhLbbVJBj/W7sJZAwmaMVZTwJOElio@hYBrt/Oq@nWebLtNiQcvoeG2zjyZeutwqw0FbCTM7B/5FEcSDuLOr6gq4v/PGzY4ZO21jTje1RtdqfhKXroz4XjqLraF3M8WdMu5P8y98/EH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ≔L↨⊖θ²ηFη
```
Input `n` and loop up until the ceiling of its logarithm to base 2. (This represents the "height" of the tree.)
```
F⌊⟦X²ι⁻θX²ι⟧«
```
Loop over the branches in pairs. (For the last row, the number of branches might be less than a power of 2, so that the final number of leaves is `n`.)
```
≔X²⁻⊖ηιζJ×ζ⊕×⁴κ±⊖ζ↗ζ↓↘ζ
```
Draw each pair of branches. Bottom branches are 1 character tall while each higher branch is extended to be twice as tall in total as the previous.
If trailing blank lines are allowed then the last `⊖` can be removed. (Alternatively, I'm hoping to fix the Charcoal bug that generates those blank lines, but there are so many edge cases that it will take some time to work through them all.)
] |
[Question]
[
## Synopsis
Your goal is to implement the (asymptotically) fastest growing function within bounded code on a fictional CPU utilizing a quite limited, yet (probably) turing-complete instruction set.
## Environment
The CPU utilizes unbounded RAM as well as two registers, the accumulator A and the program counter C, with words consisting of arbitrary integers, such that neither overflows nor underflows are possible. RAM is used to store data as well as code, allowing for self-modifying programs. Each instruction takes one parameter and therefore consists of two words; all instructions of your program are stored sequentially in RAM, starting at address 0. The following instructions can be used, P representing the parameter of the instruction:
| Mnemonic | Corresponding word | Behavior |
| --- | --- | --- |
| LOAD P | 0 | A := RAM[P]; C += 2 |
| SAVE P | 1 | RAM[P] := A; C += 2 |
| CNST P | 2 | A := P; C += 2 |
| ADDT P | 3 | A += RAM[P]; C += 2 |
| NEGA P | 4 | A := -RAM[P]; C += 2 |
| JUMP P | 5 | C := P |
| JMPN P | 6 | If A <= 0 then C := P else C += 2. |
| HALT P | every other number | The program halts. |
At each step, the instruction at address C will be executed using the parameter stored at C + 1. Both A and C will be initialized to 0 at the start of a program's execution. The word at -1 is supposed to be your input which can be guaranteed to be non-negative, other words not storing any instructions initially contain 0. The number stored at -2 will be considered your program's output, which must also be positive in all but finitely many cases.
## Rules
At the initial state, your program may not occupy more than the first 2048 words each storing integers between -2^64 and 2^64, however, during execution, there are no bounds. Of course, you don't have to write your program in bytecode, using some assembly equivalent or ultimately any other language is fine as well, as long as you provide some rules/translator and show the result does not exceed the given bounds.
Every answer should come with some rough argument showing the program always halts, as well as some approximate lower bound on its growth rate. As the given space might very well suffice for some extremely fast-growing functions, it might be helpful to utilize the slow-/fast-growing hierarchy, as it provides a relatively simple way to compare two answers. Answers will be ranked by lower bounds that can be shown to hold.
[Answer]
x=>x\*2^x, 29 words
I use only some constants in addition to constant valued pointers, which you can replace into their values for a true program, along with C-style comments. I believe with enough patience and macros, any function ala "Largest Number Printable" should be implementable.
```
// constant definitions
// do not take any space of their own
IN = -1
OUT = -2
NULL = 0
/*
PROGRAM x => x*2^x
*/
LOAD IN // VALUE = in; COUNTER = in;
SAVE VALUE //
SAVE COUNTER //
loop: // do {
LOAD VALUE // VALUE *= 2;
SAVE (INC_BY+1) //
INC_BY: ADDT NULL //
SAVE VALUE //
LOAD COUNTER // COUNTER--;
ADDT NEGONE //
SAVE COUNTER //
JMPN end // if (COUNTER<=0) break;
JUMP loop // } while (true)
end: //
LOAD VALUE // return VALUE;
SAVE OUT //
NEGONE: HALT 0 // HALT is -1
COUNTER: NULL // var COUNTER, VALUE;
VALUE: NULL // these variables are both trailing 0s, so can be ignored as the tape defaults to 0.
```
Also push and pop, which I think much helps a turning completeness proof.
```
/*
MACRO stack_manipulation_push_a
14 words
*/
STACKPTR: -2 // put outside of codespace.
CNST 01337 // assume A has the value you want, in this cse, 1337 in base 8
SAVE 0 // probably not being used.
LOAD STACKPTR // move the stack pointer down to the next open free space.
ADDT NEGONE //
SAVE STACKPTR //
SAVE (EAT_ME+1) // put the fresh stack position into the save command, basically dereference.
LOAD 0 // load back in value to be saved
EAT_ME: SAVE NULL // save the orignal A value to where stackptr points
/*
MACRO stack_manipulation_pop_a
16 words
*/
LOAD STACKPTR // *0 = *STACKPTR;
SAVE (EAT_ME+1) //
DRINK_ME: LOAD NULL //
SAVE 0 //
LOAD STACKPTR // move the stack pointer up to the last space.
ADDT 1 //
SAVE STACKPTR //
LOAD 0 // put the value back in A
```
] |
[Question]
[
# Inputs:
The program or function should take 2 vector-like (e.g. a list of numbers) O and V of the same number of dimensions, and a number T (all floating-point numbers or similar)
### Constraints:
* T >= 0
* All elements of Vector O will be in the range `[0,1)`
# Output:
The program or function should output the N dimensional cutting sequence given an infinite ray whose origin is the first vector, and whose velocity is the second vector. The sequence should include every cut the ray makes on the time interval `(0, T]`, appearing in order of when they occur. Details on the format and specification of the sequence are explained below
# Cutting sequence
In a N dimensional Cartesian coordinate system, there exist **axis-aligned unit coordinate facets**, e.g. the integer points on a 1 dimensional number line, the unit grid lines on a 2D grid, planes like `x = 1`, `z =- 10` or `y = 0` in 3D space. As this problem is generalized to N dimensions, from here forward we will no longer use lettered axes, but instead number the axes starting with 0. Every facet can be defined by some equation like `Axis j = k`, where `j` and `k` are integers, and `j` is the characteristic axis of the facet.
As the ray extends through N dimensional space, it intersects these facets. This is called a cut. Each of these cuts is described by 2 things.
1. The characteristic axis of the facet.
2. The direction of the cut, i.e. whether the ray extending positively or negatively with respect to the characteristic axis.
Hence each cut shall be outputted in the sequence as a string of a plus or minus sign corresponding to the direction of the cut, then the number (base 10) of the characteristic axis of the cut facet.
The sequence will be outputted as a continuous string of these cuts, e.g. `+0+1+0+0+1-2+0`
# Examples
[](https://i.stack.imgur.com/nVnz5.png)
This image from the Wikipedia page for [Cutting Sequence](https://en.wikipedia.org/wiki/Cutting_sequence) shows a 2D example. This is equivalent to `O=[0,0] V=[1,0.618] T = 6.5`, where the output is `+0+1+0+0+1+0+1+0+0+1`
For 1 dimension, all non-empty cutting sequences will look like `+0+0+0...` or `-0-0-0...`
More examples / test cases to be added
# Special cases
* If two or more cuts occur at exactly the same time (to the precision
of your numeric type), they must appear in the sequence in order of their axis from least to greatest
* Your program should be accurate for extreme input values
+ e.g. for `V=[1, -0.0009765625]`, the sequence will have a repeating pattern of `+0` 1024 times and then a `-1`. This pattern should hold exactly for arbitrarily large values of T
* Your program must always output a sequence, e.g.
+ If Vector V has a length 0, the program should not loop indefinitely, but output an empty sequence.
+ If the inputs are of 0 dimensions, the program should output an empty sequence
[Answer]
# [Python](https://docs.python.org/3/), 226 bytes
Assumes the lists `O` and `V` are defined, as well as the time `T`, either an int or a float.
[Try it online](https://tio.run/##TY9BboMwEEX3OYWFFGkGBjCqElWk7hXYoGyQFyRA6zbYyKYW6eUpjlqpu/ma/0Zvpvv8bvTTemaCNQWxlGfH4lnuqpA5MS539TYes8PqxK0dL13LllLpGZa8vThYEE9W2Fa/9afhr1DRmeoyirIPozSM7QS/i7mcm0KSM3buO3BfIzQNgEoN5p6ifdJFe3DgMb4iDsYyxZRmFsC/ckzBv3CMwQjBkYIBmKSOPeZ5gcmjQoFFGcgrGfKB/lYTWLj1GipE2sxQUiORPvu7@GfFJSKukw13B3g8sOUf "Try it online")
```
s=lambda x:int(x/abs(x));r=range;f=lambda O,V,T:"".join(map(lambda t:t[1],sorted(sum([[((i-o)/v,"%+d"%(s(v)*c))for i in r((v>0)-(v<0)*(o==0),int((o+T*v)//1)+(v>0),s(v))]for c,o,v in zip(r(len(O)),O,V)],[]),key=lambda t:t[0])))
```
The idea of the code is simple, first we loop over all coordinates, and for each coordinate we:
1. find where the first cut is, depending on the sign of `v` and the origin being `0` or not, the first cut might be at `-1`, `0` or `1`;
2. find how far the ray goes in the time given with `o + v*T` (which then needs proper rounding to be an argument for the `range` function);
3. find the time `t` for which each successive cut occurs, by solving `o + v*t = i` iff `t = (i - o)/v`, for the successive integer values of `i` (this amounts to finding the time for which the ray crosses the hyperplane `x_c = i`);
4. sort everything by the time and drop the time, as it was just an auxiliary thing.
The code un-golfed:
```
# sign function, returns 1 for positive numbers and -1 for negative numbers
sgn = lambda x: int(x/abs(x))
l = []
# c is the coordinate we are in,
# o is the origin in this coordinate and v the velocity
for (c, o, v) in zip(range(len(O)), O, V):
# find all the cuts for this coordinate
sub_l = []
# this is how far the ray goes, rounded to integers, in T seconds
stop_at = int((o + T*v)//1) # if this is negative, //1 pushes the result away from 0
if v > 0:
stop_at += 1
# this is where the first cut occurs (depends on o == 0 and the sign of v)
if v > 0:
start_at = 1
elif o > 0:
start_at = 0
else:
start_at = -1
for i in range(start_at, stop_at, sgn(v)):
# this is the time at which the ray cuts the x_c = i hyperplane
t = (i - o)/v
# append the time of the cut and the signed axis
sub_l.append((t, "%+d"%(sgn(v)*c)))
l.append(sub_l)
print(l)
# flatten list
l = sum(l, [])
# order list by the time at which the cut occurs
l.sort(key = lambda tup: tup[0])
# remove the times, keep the coordinates
l = map(lambda tup: tup[1], l)
# join and print
print("".join(l))
```
Then we just need to note a couple of things, like I can save some bytes if I redefine `r = range` or if I assign `start_at = (v>0)-(v<0)*(o==0)` and `stop_at = int((o+T*v)//1)+(v>0)`.
I don't feel this is properly golfed, I just wrote a program that works and then crammed everything together. Please feel free to give me some feedback.
I used a flatten from <https://stackoverflow.com/a/952946/2828287> and getting the sign of a number from <https://stackoverflow.com/a/2763445/2828287>
] |
[Question]
[
On CodingGame, there is a [Puzzle](https://www.codingame.com/ide/puzzle/ascii-art "Coding-game ascii art Puzzle") that ask to write words with ascii art.
I solve the puzzle then tried to golf it. What improvement can I do on it?
```
INPUT
>>> 20
>>> 11
>>> MANHATTAN
>>> .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .-----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------.
>>> | .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |
>>> | | __ | || | ______ | || | ______ | || | ________ | || | _________ | || | _________ | || | ______ | || | ____ ____ | || | _____ | || | _____ | || | ___ ____ | || | _____ | || | ____ ____ | || | ____ _____ | || | ____ | || | ______ | || | ___ | || | _______ | || | _______ | || | _________ | || | _____ _____ | || | ____ ____ | || | _____ _____ | || | ____ ____ | || | ____ ____ | || | ________ | || | ______ | |
>>> | | / \ | || | |_ _ \ | || | .' ___ | | || | |_ ___ `. | || | |_ ___ | | || | |_ ___ | | || | .' ___ | | || | |_ || _| | || | |_ _| | || | |_ _| | || | |_ ||_ _| | || | |_ _| | || ||_ \ / _|| || ||_ \|_ _| | || | .' `. | || | |_ __ \ | || | .' '. | || | |_ __ \ | || | / ___ | | || | | _ _ | | || ||_ _||_ _|| || ||_ _| |_ _| | || ||_ _||_ _|| || | |_ _||_ _| | || | |_ _||_ _| | || | | __ _| | || | / _ __ `. | |
>>> | | / /\ \ | || | | |_) | | || | / .' \_| | || | | | `. \ | || | | |_ \_| | || | | |_ \_| | || | / .' \_| | || | | |__| | | || | | | | || | | | | || | | |_/ / | || | | | | || | | \/ | | || | | \ | | | || | / .--. \ | || | | |__) | | || | / .-. \ | || | | |__) | | || | | (__ \_| | || | |_/ | | \_| | || | | | | | | || | \ \ / / | || | | | /\ | | | || | \ \ / / | || | \ \ / / | || | |_/ / / | || | |_/____) | | |
>>> | | / ____ \ | || | | __'. | || | | | | || | | | | | | || | | _| _ | || | | _| | || | | | ____ | || | | __ | | || | | | | || | _ | | | || | | __'. | || | | | _ | || | | |\ /| | | || | | |\ \| | | || | | | | | | || | | ___/ | || | | | | | | || | | __ / | || | '.___`-. | || | | | | || | | ' ' | | || | \ \ / / | || | | |/ \| | | || | > `' < | || | \ \/ / | || | .'.' _ | || | / ___.' | |
>>> | | _/ / \ \_ | || | _| |__) | | || | \ `.___.'\ | || | _| |___.' / | || | _| |___/ | | || | _| |_ | || | \ `.___] _| | || | _| | | |_ | || | _| |_ | || | | |_' | | || | _| | \ \_ | || | _| |__/ | | || | _| |_\/_| |_ | || | _| |_\ |_ | || | \ `--' / | || | _| |_ | || | \ `-' \_ | || | _| | \ \_ | || | |`\____) | | || | _| |_ | || | \ `--' / | || | \ ' / | || | | /\ | | || | _/ /'`\ \_ | || | _| |_ | || | _/ /__/ | | || | |_| | |
>>> | ||____| |____|| || | |_______/ | || | `._____.' | || | |________.' | || | |_________| | || | |_____| | || | `._____.' | || | |____||____| | || | |_____| | || | `.___.' | || | |____||____| | || | |________| | || ||_____||_____|| || ||_____|\____| | || | `.____.' | || | |_____| | || | `.___.\__| | || | |____| |___| | || | |_______.' | || | |_____| | || | `.__.' | || | \_/ | || | |__/ \__| | || | |____||____| | || | |______| | || | |________| | || | (_) | |
>>> | | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | || | | |
>>> | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
>>> '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
```
```
OUPUT:
.----------------. .----------------. .-----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .-----------------.
| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |
| | ____ ____ | || | __ | || | ____ _____ | || | ____ ____ | || | __ | || | _________ | || | _________ | || | __ | || | ____ _____ | |
| ||_ \ / _|| || | / \ | || ||_ \|_ _| | || | |_ || _| | || | / \ | || | | _ _ | | || | | _ _ | | || | / \ | || ||_ \|_ _| | |
| | | \/ | | || | / /\ \ | || | | \ | | | || | | |__| | | || | / /\ \ | || | |_/ | | \_| | || | |_/ | | \_| | || | / /\ \ | || | | \ | | | |
| | | |\ /| | | || | / ____ \ | || | | |\ \| | | || | | __ | | || | / ____ \ | || | | | | || | | | | || | / ____ \ | || | | |\ \| | | |
| | _| |_\/_| |_ | || | _/ / \ \_ | || | _| |_\ |_ | || | _| | | |_ | || | _/ / \ \_ | || | _| |_ | || | _| |_ | || | _/ / \ \_ | || | _| |_\ |_ | |
| ||_____||_____|| || ||____| |____|| || ||_____|\____| | || | |____||____| | || ||____| |____|| || | |_____| | || | |_____| | || ||____| |____|| || ||_____|\____| | |
| | | || | | || | | || | | || | | || | | || | | || | | || | | |
| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------'
```
### Python 3: 145 bytes
```
i=input;l=int(i());h=int(i());t=[ord(c)-65if c.isalpha()else 26for c in i().upper()]
while h:h-=1;r=i();print(''.join(r[j*l:l*(j+1)] for j in t))
```
[Try it online!](https://tio.run/##7VdNb9pAEL37V8zNdip2S6rmEEql/ID2lFs2WkeUCCMEiBBVlfa/051drz0za4Xea0vB4fF2Zt58GY5/zpvD/svl0i7b/fH9vNj5@7lqq7pebIZ/z8unw@lXtapnd1/bV1ip9u1ld9y8VPV697aG27vXwwlW0O7B09X78bg@VfVz8XvT7tawud/MlvPFaek/WxxPaLQs1fbQ7qvT0/Zmd7@7qbaf5vUzoJUtWjnX9eVy@7mYz4sfL/ubh8fHh58FqJm4FEyYB6e8QOEkqsBN2IQh5pvDQbisjXeHRBcAvDhG0IRZOxAlZq9g1AnlpVfpdywWcTYdFTqYtgSEO8PsqN9/yEvvQurNedfzYmkwPGYW3xhvNH@jOb1ej745NIBhQlyIJYL9YVVC5yFhrgsZGpVjYzyCUXOM50LwjgQdjzsmJMMQcPhindThiLaAmCDZf0CxxKV6/YXShL2YGKIDoFQ0f5Q22NN5XjDJ4c@x@Gx/6zEbrfbxjfE6BuONYrFngOfKx2dhqGVqDg3aCCHBak0L51khDYYZjK/enmGYHeEJjJrjPOuAN0JycwXDszpUnesQU43vjQbWqAEDJ/TislWhlXheYmJ6HZ6mQORvoFEfFTaMpUOjg1OWKxp4wmJ5ojjK04bzIpHzxjB0DCJXHsPFkbQVfcdYMQ1db5UKsqCzgiQlBAsdaTkvDfAwNQ4gW3ddS19tDjvaHCnkrDks14HJcrw5PGacKGZepM6J1VLHQKY6eKOWyp9sZoproxo7X2FjlVnRZTHB4cYX8X2HpoRvPAcGh0EMjR9NXN0Mi6sNZzY1Rxo2b8GS5GcT4gmNCmfJJEUa2tMS0/RstxRpEjpzz2zd2SRVPPvTcZIYW4rmsGnG2LM1BENjCYjR0STDuofVoBea2awMOeP2hA5PKyG4/TAW1xg6mWk4eoOkEYJfLQocEb7ttOEbEItZNiIH8eHBv7MhUdQIOWTLFuHZZW08jPdhxcSLBRiK2XdWXIvdNYax9dm9pwESc4yXQqJBp@PsbPxO8OFZl8XS2Uo3ihnhNwZI42NCeCwm0xtveSwkV8zgoBctRnFkQIzVYsOE8oz4lflzNstfnhe0XPnOZc0B7KKrfML@a8w3R8l/35ZInLAJ880hsfCInbAJ81jxFw "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~131 130 128 126~~ 125 bytes
```
i=input
L=int(i())
exec("t=[L*[27,ord(c)%32][c.isalpha()]for c in i()]"+";r=i();print(''.join(r[j-L:j]for j in t))"*int(i()))
```
A few golfs of the provided code.
Note: I upper-cased `l` to `L` and replaced a couple of `;` with newlines just for legibility.
**[Try it online!](https://tio.run/##7VdNb9swDL37VxABBtndIq3pYcC6Dui926m3KJCLrEMTDEmQZcAG6L9nomTZJGU0u88GajevTyQfv5we/pxe9rub83lzt9kdfp2qh/A81Zu6aarn38/rena6Wz5cLRcf3u2P3@p18@ZmsVqu9ebn04/Dy1PdrL7vj7CGzQ7CmdXs7ez2eBd@uz0c0Y5Servf7Orjcjt/@LiN5C2ST00zu8qemvN58b66vq6@PO2u7h8f779WoOfi0jBhAZzyApWXqAY/YROGWGgOD/FyLj09En0E8OIYQTPm3ECUmLuAUSeUl@/S71gs4mw@KnQwbRmIT4a5Ub//kJfehdRb8i7nxdFgeMwsvjHeaP5Gc3q5Hn1zGADLhPgYSwL7w1pB5yFjvgsZWl1iYzyCUXOM52PwngSdjnsmpMAQ8HhzXurwRFtEbJQc/kCxzKV6w4XShL2UGKIDQGmaP0ob7JkyL5jk@ONZfK5/9JhLVvv4xngdg/FGsdQzwHMV4nMw1DI3hwFjhZBotaGFC6yYBssMpnuwZxnmRngCo@Y4z3ngjZDdXMDwrIlV5zrEVONna4A1asTAC724bHVsJZ6XlJheR6BpEPkbaNRHjQ3j6NCY6JTligaesVSeJI7yjOW8ROS8MQwdg8hVwHBxZG1V3zFOTEPXW0pDEXRRkKyEYLEjHeflAR6mxgMU665r6YvN4UabI4dcNIfjOjBZnjdHwKwXxSyL1DlxRuoYyFQHb1Slw8l2rrk2qrHzFTeWKoouiwkeN76I7zO0Cj7xHFgcBjE0YTRxdTMsrTac2dwcediCBUeSX0xIILQ6niWTlGhoz0jM0LPdUqRJ6Myt2LpzWap49@fjJDFOieZwecbYuzUGQ2OJiDXJJMO6l9WgF9r5XMWccXtCR6ApiG5fjcW3lk5mHo7eIGmE6NeIAieEbztj@QbEYqpW5CC9PPh3NiSKGiGHbNkqvrucS4fxOayYdLEAYzH7zkprsbvGMLY@u880QGKO8XJINOh8nJ1N3wlePeuLWDpb@UExK/ymAGl8TAiPxRZ606OMheSKGRz0osUkjgyIdUZsmFieEb8yf94V@Svzgpbr0LmsOYBddJVP2H@NheZQ/P9bhcQJm7DQHBKLr9gJm7CAVX8B "Python 3 – Try It Online")**
1. When characters are alphabetical their ordinals are ranges \$[65,90]+[97,122]\$ which modulo \$32\$ are \$[1,27]+[1,27]=[1,27]\$. As such we can remove the `.upper()` and work with `ord(c)%32` in this case.
2. Rather than an `if-else` we can either use the fact that `False` is `0` and `True` is `1` and multiply (as originally suggested by manatwork in comments) or use list indexing for the two cases like above (`[27,ord(c)%32][c.isalpha()]` chooses the slice stop rather than its start).
3. We can save a little by replacing the `while` loop with the `exec` of a string of code produced using string multiplication.
4. We can save a byte by moving `t=...` into the `exec`-ed code so we do not have to assign to `h` at all. Another is saved by moving the repeated string's trailing `;` to the beginning so that the `t` assignment string doesn't require its own.
5. Rather than `[(j-1)*L:j*L]`, or even `[~-j*L:j*L]`, we can multiply by `L` once in the construction of `t` and just do `[j-L:j]`.
] |
[Question]
[
Given: a width, a height, and a set of sets of points. Output: An image where each set of points is connected and colored in (like a shape). Each shape *must* be a different color from all of the other shapes, but **the actual color doesn't matter as long as each color is distinct**. The shapes must be in order; whether you start at the end or the beginning of the set doesn't matter, though. **The dots must be connected in the order they're given in the set.**
Output formats are in accordance with standard image rules.
## Examples
```
//the code here has nothing to do with the actual challenge and just shows examples
document.getElementById("one").getContext("2d").fillRect(0, 0, 300, 300)
const ctx = document.getElementById("two").getContext("2d")
ctx.fillStyle = "black"
ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(0,300);ctx.lineTo(300,0);ctx.closePath();ctx.fill()
ctx.fillStyle = "lime"
ctx.beginPath();ctx.moveTo(200,0);ctx.lineTo(600,0);ctx.lineTo(300,300);ctx.closePath();ctx.fill()
```
```
canvas {border: 1px dotted black}
```
```
<pre>Width: 500, Height: 500, Set: [[[0, 0], [0, 300], [300, 300], [300, 0]]]</pre>
<canvas id="one" width="500" height="500"></canvas>
<pre>Width: 600, Height: 300, Set:
[
[[0,0], [0,300], [300,0]],
[[200,0], [600,0], [300,300]]
]</pre>
<canvas id="two" width="600" height="300"></canvas>
```
Scoring is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [R](https://www.r-project.org/), ~~122~~ 71 bytes
```
function(w,h,p){plot.new();plot.window(c(0,w),c(0,h));polygon(p,c=1:8)}
```
[Try it online!](https://tio.run/##NYtRCsIwEESvk4VBNimBovTDC3gIo7GFkoRSWUQ8e9wY/FjmMbNvq3Gq8ZnCvuRkBDMKvcua90O6i6HTD2VJtywmGIYQWsykU15fD5UKwmSPI31qNAMzvN52VUUFq@yYm6SBoaNvT4TLudUetrf8B6e78x1HBhNR/QI "R – Try It Online")
[RDRR - actually shows graphics](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(w%2Ch%2Cp)%7Bplot.new()%3Bplot.window(c(0%2Cw)%2Cc(0%2Ch))%3Bpolygon(p%2Cc%3D1%3A8)%7D%0Af(300%2C500%2Crbind(c(100%2C200)%2Cc(200%2C300)%2Cc(50%2C50)%2CNA%2Cc(25%2C100)%2Cc(0%2C100)%2Cc(250%2C250)%2Cc(280%2C0))))
A function that takes arguments width, height and a matrix of points detailing the shapes. Each shape is separated by a row of NAs. Output is a plot to the screen of the shapes.
] |
[Question]
[
For functions \$f, g: \{0,1\}^n \rightarrow \{0,1\} \$, we say \$f \sim g\$ if there's a permutation of \$1,2,3,...,n\$ called \$i\_1,i\_2,i\_3,...,i\_n\$ so that \$f(x\_1,x\_2,x\_3,...,x\_n) = g(x\_{i\_1},x\_{i\_2},x\_{i\_3},...,x\_{i\_n})\$. Therefore, all such functions are divided in several sets such that, for any two functions \$f, g\$ in a same set, \$f \sim g\$; for any two functions \$f, g\$ in different sets, \$f \not\sim g\$. (Equivalence relation) Given \$n\$, output these sets or one of each set.
Samples:
```
0 -> {0}, {1}
1 -> {0}, {1}, {a}, {!a}
2 -> {0}, {1}, {a, b}, {!a, !b}, {a & b}, {a | b}, {a & !b, b & !a}, {a | !b, b | !a}, {a ^ b}, {a ^ !b}, {!a & !b}, {!a | !b}
```
You can output the function as a possible expression(like what's done in the example, but should theoretically support \$n>26\$), a table marking outputs for all possible inputs (truth table), or a set containing inputs that make output \$1\$.
Shortest code win.
[Answer]
# [J](http://jsoftware.com/), 62 bytes
```
f=:3 :'~.(2#~2^y)([:<@~.@/:~((i.@!A.i.)y)|:(y#2)$])@#:i.2^2^y'
```
[Try it online!](https://tio.run/##y/r/P83WyljBSr1OT8NIuc4orlJTI9rKxqFOz0Hfqk5DI1PPQdFRL1NPs1KzxkqjUtlIUyVW00HZKlPPKA6oWP1/anJGvkKagtF/AA "J – Try It Online")
-3 bytes for anonymous function (removing `f=:`)
For each boolean function (truth table), generate its equivalence class, then remove duplicates.
] |
[Question]
[
**Related:**
* [Determine the position of a non-negative number in the infinite spiral](https://codegolf.stackexchange.com/questions/87178/determine-the-position-of-a-non-negative-number-in-the-infinite-spiral)
* [Wind me a number snake!](https://codegolf.stackexchange.com/questions/125966/wind-me-a-number-snake?noredirect=1&lq=1)
**Challenge:**
Given a grid, with an ID starting at the center and spiraling out, what is the ID given a position in the fewest number of bytes?
**Grid:**
```
+---------------+---------------+---------------+---------------+---------------+
| id: 20 | id: 19 | id: 18 | id: 17 | id: 16 |
| pos: (-2, -2) | pos: (-1, -2) | pos: (0, -2) | pos: (1, -2) | pos: (2, -2) |
+---------------+---------------+---------------+---------------+---------------+
| id: 21 | id: 6 | id: 5 | id: 4 | id: 15 |
| pos: (-2, -1) | pos: (-1, -1) | pos: (0, -1) | pos: (1, -1) | pos: (2, -1) |
+---------------+---------------+---------------+---------------+---------------+
| id: 22 | id: 7 | id: 0 | id: 3 | id: 14 |
| pos: (-2, 0) | pos: (-1, 0) | pos: (0, 0) | pos: (1, 0) | pos: (2, 0) |
+---------------+---------------+---------------+---------------+---------------+
| id: 23 | id: 8 | id: 1 | id: 2 | id: 13 |
| pos: (-2, 1) | pos: (-1, 1) | pos: (0, 1) | pos: (1, 1) | pos: (2, 1) |
+---------------+---------------+---------------+---------------+---------------+
| id: 24 | id: 9 | id: 10 | id: 11 | id: 12 |
| pos: (-2, 2) | pos: (-1, 2) | pos: (0, 2) | pos: (1, 2) | pos: (2, 2) |
+---------------+---------------+---------------+---------------+---------------+
```
**Tests:**
```
f(0, 0) = 0
f(1, 1) = 2
f(0, -1) = 5
f(2, 0) = 14
f(-2, -2) = 20
f(x, y) = id
```
### Notes:
* Grid will always be square (height == width)
* Grid can be infinite in size
[Answer]
# JavaScript (ES6), 64 bytes
Takes input in currying syntax `(x)(y)`.
```
x=>y=>(d=(A=Math.abs)(A(x)-A(y))+A(x)+A(y))*d+(d-x+y)*(-y>x||-1)
```
[Try it online!](https://tio.run/##ZcxNCoMwEAXgvadwOWMYTaRdJpAD9BCp0f4gpjRSEvDuaWpLoRbewIOPeVfzML67X24zTc72aZApSBWlAitBy4OZz7U5egQNAUlDRGSvytZaWQaWAotYAUUVloUEps5N3o19PboTDMAxB8umKXnxKwJzVmmLvx/60H5D7XdO7DZE2fK9F3l6Ag "JavaScript (Node.js) – Try It Online")
Heavily inspired by [this answer](https://math.stackexchange.com/a/2639611) from math.stackexchange.com.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 58 bytes
```
y=>x=>(m=Math.max)(4*x*x-m(x+y,3*x-y),4*y*y+m(-x-y,x-3*y))
```
[Try it online!](https://tio.run/##ZczdCoMwDAXge5/Cy6Y2WrW7rG@whyhO94O1MmWkT9@FbQzm4AQSPnJu7uHW/n5dNpzDaUijTdF2ZDvh7dFtl9I7AmEkSUIvqIiq5S2CMjLKWHiBfCnCVkaA1Id5DdNQTuEsRqGBA3lV5Tr7lRo4L2myvx/80GFHzbeuNjtCNp53o05P "JavaScript (Node.js) – Try It Online")
Use the formula from [my previous answer](https://codegolf.stackexchange.com/a/154458), with some edit (because Javascript doesn't vectorize).
I came up with the formula myself. Basically, knowing that the formula must be quadratic in each 1/4 grid section, I find out the formula mostly by trial-and-error and then find a way to fit those together.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
|sQtE1YLqwG+X{)
```
[Try it online!](https://tio.run/##y00syfn/v6Y4sMTVMNKnsNxdO6Ja8///aCMFg1gA) Or [verify all test cases](https://tio.run/##y00syfmf8D/Cq6Y4sMTVMNKnsNxLO6Ja879LyP9oAwWDWK5oQwVDIGmgoAuijMBCukYKukaxAA).
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
(g@[-+<.-+[+[)>.(g=:4**:)@]-+>.]+]+-~
```
[Try it online!](https://tio.run/##PY2xCsMgFEV3v@LRRY2opbSLGMnSrv2A4JBITJSioTrn19NSQpc7HDjnjkNZ9vUdUvWAfaswGFhFiAW5oYLWcH8@wBxsJ3PXc6YFZz3rqRFkbtW1aRTtLGdGWGYZ3/avgia3ZMC/JbrzpzOVG7nwLYgbxf8gknmtMsoxJBldTiW/puPqAw "Bash – Try It Online")
My first J answer! Use the formula from my Javascript answer.
1. Precedence rules are weird. (at least I don't need to memorize too much, but it's counterintuitive)
2. More than half of the characters are BF keywords.
3. `-+>` and `:)`.
] |
[Question]
[
Given a double-precision float, find the closest double-precision float whose binary representation is a palindrome.
# Input
A floating point number `x`. You may use any format you like for input, but the format you chose must be able to represent every possible IEEE 754 binary64 value, including denormals, distinct representations for `+0` and `-0`, and `+Inf`, `-Inf`, and `NaN`.
# Output
A floating point number `y`. You may use any format you like for output, with the same restrictions as the input format.
# The Task
`y` is any value such that:
* The IEEE 754 binary64 bitstring for `y` is a palindrome. That is, the first 32 bits are the reverse of the last 32 bits.
* `abs(x-y)` is minimal by the `totalOrder` predicate.
# Notes
* `abs(x-y)` must be computed with strict IEEE 754 double-precision floating point arithmetic.
* `totalOrder` puts non-numeric values and signed zeroes in this order: `- NaN < -Inf < -1 < -0 < +0 < +1 < +Inf < +NaN`. Otherwise it behaves like the normal `<` operator.
* The rules for performing arithmetic on non-numeric values can be found [at this website](http://www.iki.fi-jhi.s3-website-us-east-1.amazonaws.com/infnan.html)
* For an overview of how binary64 floats work, [see wikipedia](https://en.wikipedia.org/wiki/Double-precision_floating-point_format).
* If there is more than one value for `y` that satisfies the conditions, output any one of them. Note that this can only occur if `abs(x-y1) == abs(x-y2)`, or if they are both `NaN`.
* The input and output formats may be different if desired; both formats still need to obey all the rules.
* It may be convenient to use a raw binary format for IO; this is permitted.
* For the purposes of this challenge you may consider all `NaN` values as equivalent, since `NaN` payload behavior is implementation defined.
* It is **not sufficient** to just mirror the first 32 bits. See test cases 2, 4, 5, and 7 for examples.
* Any non-`NaN` double palindrome is valid output for x=`+Inf` or x=`-Inf`, since the distance is still just `+Inf`. Reversing the first 32 bits would not be correct though since the resulting `NaN` value would have a distance of `+NaN > +Inf` from the input.
* A `NaN` though, any double palindrome would be correct.
# Test Cases
```
Input: 0x8A2B_7C82_A27D_6D8F = -1.1173033799881615e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259
Input: 0x5000_0000_0000_0001 = 2.3158417847463244e+77
Output: 0x4FFF_FFFF_FFFF_FFF2 = 2.3158417847463203e+77
Input: 0x5000_0000_0000_0002 = 2.315841784746325e+77
Output: 0x5000_0000_0000_000A = 2.315841784746329e+77
Input: 0x7FF0_0000_0000_0000 = +Inf
Output: 0x0000_0000_0000_0000 (others are possible)
Input: 0xFFF0_0000_0000_0000 = -Inf
Output: 0x0000_0000_0000_0000 (others are possible)
Input: 0x7FFC_0498_90A3_38C4 = NaN
Output: 0x0000_0000_0000_0000 (others are possible)
Input: 0x8000_0000_0000_0000 = -0
Output: 0x0000_0000_0000_0000 = +0
Input: 0x0000_0000_0000_0000 = +0
Output: 0x0000_0000_0000_0000 = +0
Input: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259
Input: 0x000F_FFFF_FFFF_FFFF = 2.225073858507201e-308
Output: 0x000F_FFFF_FFFF_F000 = 2.2250738585051777e-308
Input: 0x0000_B815_7268_FDAF = 1e-309
Output: 0x0000_B815_A81D_0000 = 1.0000044514797e-309
```
---
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring, [Standard Loopholes](https://codegolf.meta.stackexchange.com/q/1061/7981) forbidden.
[Answer]
# C (gcc), 172 bytes
```
#define D double
i;D f(D x){unsigned a[]={0,0};D*A=&a;D c=0;do{for(i=0;i<32;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(31-i))<<i;};c=fabs(x-*A)<fabs(x-c)?*A:c;}while(++a[1]);return c;}
```
(Almost) purely brute-force; takes about 24 minutes per run on my machine.
`f` is a function that takes a double and returns the closest palindromic double. It iterates over every palindromic 64-bit sequence (as a double), storing the closing one, and returns it at the end.
This solution uses gcc on Ubuntu 16.04 32-bit, on a little-endian 32-bit single-core Pentium 4 2.8 GHz CPU.
Explanation/Ungolfed:
```
int i;
double f(double x) {
unsigned int a[]={0, 0}; // a 2-array of ints is much easier to maipulate bitwise
double *A = &a; // than a double, so refer to the same memory
// in two different ways, a as int[2], A as double*
double current = 0.0;
do {
for(i = 0; i < 32; ++i) {
*a = ( *a&~(1<<i) )|( (!!( (a[1]&1)<<(31-i) ))<<i);
// reverse the bits of the second half into the first half
// (*a is shorter than a[0])
}
current = fabs(x-*A)<fabs(x-current) ? *A : current;
// if *A is closer to x than current, replace c with *A
} while (++a[1]);
// do-while instead of while to ensure each value is tried
// at UINT32_MAX, overflows to 0, ending the loop.
return current;
}
```
A C float (binary32) version that takes ~0.0015% as long to run (about 0.02 seconds on my machine) because it checks 1/65536 as many values: (~~185~~ 179 bytes)
```
#define F float
i;F f(F x){unsigned short a[]={0,0};F*A=&a;F c=0;do{for(i=0;i<16;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(15-i))<<i;};c=fabsf(x-*A)<fabsf(x-c)?*A:c;}while(++a[1]);return c;}
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/126507/edit).
Closed 6 years ago.
[Improve this question](/posts/126507/edit)
# Backstory:
I think that my boss might finally realize that I don't any enough work, despite being paid by the hour. I want to throw him off track, by writing as many valid programs as I can to send to him. Unfortunately, due to budget cuts, my keyboard only allows each key to be pressed once.
# Specification:
Write as many different valid programs as you can for your language. You may not reuse any character at any time (even within the same program). A program is "valid" is it compiles and runs without any errors (warnings are acceptable), for any given input. Your score is the number of unique programs written.
It does not matter what the program actually does. It does not need to take input, produce output, or even terminate. The only restriction is that may never return an error.
# Example (JavaScript):
1. `b=1`
2. `alert(2)`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 225 programs
```
(empty program)
¢
¤
¥
¬
®
µ
½
Æ
Ç
Ñ
×
Ø
Œ
ß
æ
ç
ð
ı
ȷ
ñ
÷
ø
œ
(space)
!
$
%
&
(
)
*
+
,
-
.
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
A
B
C
D
E
F
G
H
I
J
K
L
N
O
P
Q
R
S
U
V
W
X
Y
[
]
^
_
a
b
c
e
f
g
h
i
j
k
l
m
n
o
p
q
r
u
v
w
x
|
~
¶
°
¹
²
³
⁴
⁵
⁶
⁷
⁸
⁹
⁺
⁻
⁼
⁽
⁾
Ɓ
Ƈ
Ɗ
Ƒ
Ƙ
Ɱ
Ɲ
Ƥ
Ƭ
Ʋ
Ȥ
ɓ
ƈ
ɗ
ƒ
ɦ
ƙ
ɱ
ɲ
ƥ
ʠ
ɼ
ʂ
ƭ
ʋ
ȥ
Ạ
Ḅ
Ḍ
Ẹ
Ḥ
Ị
Ḳ
Ḷ
Ṃ
Ṇ
Ọ
Ṛ
Ṣ
Ṭ
Ụ
Ṿ
Ẉ
Ỵ
Ẓ
Ȧ
Ḃ
Ċ
Ḋ
Ė
Ḟ
Ġ
Ḣ
İ
Ṁ
Ṅ
Ȯ
Ṗ
Ṙ
Ṡ
Ṫ
Ẇ
Ẋ
Ẏ
Ż
ạ
ḅ
ḍ
ẹ
ḥ
ị
ḳ
ḷ
ṇ
ọ
ṛ
ṣ
ṭ
ụ
ṿ
ẉ
ỵ
ẓ
ȧ
ḃ
ċ
ḋ
ė
ḟ
ġ
ḣ
ṁ
ṅ
ȯ
ṗ
ṙ
ṡ
ṫ
ẇ
ẋ
ẏ
ż
«
»
‘
’
“
”
```
224 characters in Jelly's 256-byte codepage are valid, non-error-throwing programs on their own, plus an empty program. The other characters could be used in literals, but since all the literal-denoting characters are already in use on their own, no new programs can be made from them.
All of these were tested, one by one, on [tio.run](https://tio.run/#jelly).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) version 16.0, ~~83~~84 programs
```
⍝ empty program
⍝ single space
⍝ single tab
0
1
2
3
4
5
6
7
8
9
+
-
×
÷
⌈
⌊
*
⍟
|
!
○
~
∨
∧
⍱
⍲
<
≤
=
≥
>
≠
≡
≢
⍴
,
⍪
⍳
↑
↓
?
⍒
⍋
⍉
⌽
⊖
∊
⊥
⊤
⍎
⍕
⌹
⊂
⊃
∪
∩
⍷
⌷
→
⎕
1 2 3 ⍝ input for above program
⍞
Hello, World! ⍝ input for above program
/
⌿
\
⍀
¨
&
⍨
⌶
#
⊆
⊣
⊢
⌸
⍸
⍝
⋄
L:
⍬
{}
⍝ just a newline
⍝ this line belong with the previous one
```
[Try it online!](https://tio.run/##hY@5SgNRFIZr/6c4QbDQJGYSjQsurYW9jc2ExCCOucO4EVwQlSGZJaASU7knGMXGBY2FCOZN7ovoP1jYCB74zj37Ode0rUS@bFqq@EWBoAcpGEgjgyEMI4sRjGIMA0ig20D3FTqoEA/90OE5thCDbvjYga60yQ2jD@QRE9DVJiapW5iiviCX5IrZZ8Sp78gTtHtIjjFN74j4pMoN79DeCSd6fFukyXiN1Jl7o79H9pnnlMot49FlxOWMWh2GpCUjv6LDU1ks2WursqAcMXNqvSC2o4qOuczeM8wULEvFZU45Vj72T/0gN31gnn27@Gyjjwa/HrygF1Gb9lxRJassG8pZWuEUMbLJVJLnXhN@P@j81IWdP@qiFLR/gNlxmvfY3Aa@AQ "APL (Dyalog Unicode) – Try It Online") (except for two which cannot run on TIO's version 15.0)
### Explanations:
Most of the programs just print their content. Exceptions are:
* The four whitespace ones do nothing.
* `→` terminates
* `⎕` asks for evaluated input
* `⍞` asks for character input
* `⍝` is a comment
* `⋄` is a statement separator (i.e. two statements that each do nothing)
* `⍬` prints an empty numeric list (i.e. just a newline)
[Answer]
# Python REPL, 24 programs
```
[empty]
[space]
[tab]
[newline]
0
1
2
3
4
5
6
7
8
9
sum
pow
chr
next
id
()
{}
[]
#
\
```
] |
[Question]
[
A [Ken Thompson virus](http://wiki.c2.com/?TheKenThompsonHack) is a virus that infects your compiler and other programs. Since it infects all your tools, you can not detect it without using tools from before the virus was introduced.
Your will create a prototype for inserting the Ken Thompson virus into code. The goal of this virus will be to allow you to (fake) destroy any computer running a program infected with it.
Inserting a Ken Thompson virus is defined as follows. Start with an input program `P`. Your program will output a modified program `Q` that works as follows:
* If the input to `Q` is `aNouIQ5xKvUfdZVzo0Xs`, it will output `BOOM` (in a real Ken Thompson virus, this would actually do something bad, but since it this is a fake virus, outputing `BOOM` is done instead).
* For any other input to `Q`, run program `P` with that input
+ If the output of `P` is valid source code in the language you are using, insert the Ken Thompson virus into it and then `Q` will output the resulting infected program.
+ Otherwise, the output of `Q` is just the output of `P`.
You will write a program that takes `P`'s code as input and produces `Q`'s code as output.
You can use either a currently (at the time of this post) existing programming language, or a subset of one, for this challenge. (The idea is that language you are using would be the target language of some self-compiling compiler, but this is not required.) Since you want to be as subtle as possible, the shortest code (in bytes) wins!
[Answer]
For some other languages, determining `If the output of P is valid source code in the language you are using` is almost impossible, unless you use/rewrite a compiler. For some other languages you can `eval` a string and catch for error, if any. However, for `Mathematica`, it is just check for if the head of the result is a function - Mathematica doesn't allow output invalid function, like `1!-!&`.
So,
## Mathematica, 209 bytes
(obviously can be golfed more, for example by assign long names to global variables)
```
With[{p=#,c=With[{p=#,c=6},If[#==="aNouIQ5xKvUfdZVzo0Xs","BOOM",With[{r=p@#},If[Head@r===Head@p,(c/.3!->c)[r],r]]]&]&},If[#==="aNouIQ5xKvUfdZVzo0Xs","BOOM",With[{r=p@#},If[Head@r===Head@p,(c/.3!->c)[r],r]]]&]&
```
The function takes a function as input, and output a function according to the specification.
Note that the input must be a pure function, not something like `f[x_] := ...`. So all Mathematica built-in functions fail the criteria.
Although *Mathematica* have `#0` parameter, I explicitly disallow that in my answer because a quine is not allowed to read the code of itself.
(I thought that question is trivial until I read the third rule)
] |
[Question]
[
(yes, that title was intentional)
Your task is to correct common grammatical mistakes.
You must:
* Capitalise the first letter of each sentence, ie the first non-whitespace letter after any of `.!?` and, additionally, capitalise the first letter of the input
* Remove repeating punctuation, such as `!!! -> !`. Ellipses (`...`) are not special, and will collapse into `.`.
* Remove repeating whitespace `<space><space><space> -> <space>`
* Remove whitespace directly before any of `.,;!?` as in: `Hello , World ! -> Hello, World!`
* If there is no space directly after any of `.,;!?`, add it.
* Add a `.` at the end of the input if there is not any of `.!?` at the end.
* ~~Not use Mathematica's builtins~~
## Examples:
```
This is a sentence .Unfortunately, it's not very grammatically correct.can you fix it ???
This is a sentence. Unfortunately, it's not very grammatically correct. Can you fix it?
buffalo, buffalo;buffalo buffalo? Buffalo.buffalo Buffalo buffalo
Buffalo, buffalo; buffalo buffalo? Buffalo. Buffalo Buffalo buffalo.
i'm not sure what to put for this test case...
I'm not sure what to put for this test case.
!this is a test. .Can ...you . . . 'ear me Ground-Control? ?! 'ere as in what you do with you're [sic] ears !
! This is a test. Can. You. 'ear me Ground-Control?! 'ere as in what you do with you're [sic] ears!
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~80~~ ~~74~~ ~~73~~ ~~71~~ ~~74~~ ~~64~~ ~~65~~ ~~62~~ ~~78~~ 72 bytes
```
*([.,;!? ])(\1| )*
$1
T`l`L`[.!?].|^.
([.,;!?])(\w|')
$1 $2
[^.!?]$
$&.
```
[Try it online!](https://tio.run/nexus/retina#PU9BTsMwELz7FRMpkLYKlsq1B0v0UA4ciziEVjGuQy05NrI3lEj9e7FLirzSjj2zntm72aa9YDFreL0qBHbz2fvyjPmClUu2bW370ja8EDt@3nM2ibLmdK7mSYLykTX7LChZec8vl2dtrUeNNx/sAQXbHk1EKglE7Ug7pcFfXecDDU6StmMNQ1WE84RvHUZ8Btn3koyS1o5QPgStiCvpMPoBnflJeggh2MfQddL6GhNYTR24vYgb4DfqaerTnZmqvzrHIWicjpJAHl8DIQUE5eykI0HJqDnnrPOeFfS/UuY4@DplS2yOx6@n0jKg19gEP7jDw9o7Ct4KiCJRyUimefdnl4cOHidDx4yrxDbRqB3SFxHFLw "Retina – TIO Nexus")
This is my first Retina answer.
-12 bytes thanks to [@BusinessCat](https://codegolf.stackexchange.com/users/53880/business-cat)!
-3 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil).
] |
[Question]
[
Your challenge is to query the SE API and find out whose rep on PPCG is tied, and output it. If these were all the users on PPCG:
```
Martin Ender: 10000 rep
Dennis: 10000 rep
xnor: 5000 rep
sp3000: 3000 rep
```
You should output `Martin Ender, Dennis`. If these were the only users:
```
Jon Skeet: 1000000 rep
Martin Ender: 10000 rep
Dennis: 10000 rep
xnor: 5000 rep
sp3000: 3000 rep
Digital Trauma: 2000 rep
Luis Mendo: 2000 rep
Helka Homba: 2000 rep
```
You should output:
```
Martin Ender, Dennis
Digital Trauma, Luis Mendo, Helka Homba
```
Note that **you can use different output formats**, as long as it is clear whose rep is tied and who they are tied with. **Users with <200 rep can be ignored.**
[Answer]
# JavaScript (ES6), ~~259~~ ~~257~~ ~~248~~ 241 bytes
Returns a `Promise` object containing `\n` separated groups, in ascending order of reputation, of profile links for users with the same rep, with each link separated by a comma. As the question only states that users with 200 reputation or less *can* be ignored (rather than *should* be ignored), this solution includes a couple of users who do have <200 rep.
```
f=(x=95,s="",c=0)=>fetch(`//api.stackexchange.com/users?page=${x}&site=codegolf`).then(a=>a.json()).then(j=>(i=j.items.reverse()).map(x=>(r=x.reputation)>c?(c=r,t.length-1&&(s+=t+`
`),t=[x.link]):t.push(x.link),t=[i[0].link])&--p?f(p,s,c):s)
```
---
## Caveat
Between this challenge, "[Martin vs. Dennis](https://codegolf.stackexchange.com/questions/119907/martin-vs-dennis-round-1/119912#119912)" and a couple of others, I've managed to get myself (temporarily) booted from the API for a few hours! I was, therefore, unable to run my final tests on this but it *should* be working (although, I suspect it might not include users from page 1 in the output). There's probably a bit more I can golf off it, so I'll come back to it when my ban is lifted.
---
## Try it
**WARNING:** The first Snippet below will submit *95*(!) requests to the SE API - running it a couple of times may result in you also having your access to the API temporarily revoked. If you'd prefer to test this with a reduced number of API calls and, therefore, a reduced result set, change the value of the first parameter to something *much* lower than 95. Alternatively, you can test it with no API calls, using the second batch of sample data from the question by using the second Snippet below, which returns usernames instead of profile links (for now).
---
```
f=(x=95,s="",c=0)=>fetch(`//api.stackexchange.com/users?page=${x}&site=codegolf`).then(a=>a.json()).then(j=>(i=j.items.reverse()).map(x=>(r=x.reputation)>c?(c=r,t.length-1&&(s+=t+`
`),t=[x.link]):t.push(x.link),t=[i[0].link])&--p?f(p,s,c):s)
f().then(console.log)
```
---
```
f=(x=95,s="",c=0)=>Promise.resolve(JSON.parse(`{"items":[{"display_name":"John Skeet","reputation":1000000},{"display_name":"Martin Ender","reputation":10000},{"display_name":"Dennis","reputation":10000},{"display_name":"xnor","reputation":5000},{"display_name":"sp3000","reputation":3000},{"display_name":"Digital Trauma","reputation":2000},{"display_name":"Luis Mendo","reputation":2000},{"display_name":"Helka Homba","reputation":2000}]}`)).then(j=>(i=j.items.reverse()).map(y=>(r=y.reputation)>c?(c=r,t.length-1&&(s+=t+`
`),t=[y.display_name]):t.push(y.display_name),t=[i[0].display_name])&--x?f(x,s,c):s)
f().then(console.log)
```
] |
[Question]
[
The task is to create a program (or a function), which outputs array elements in the order, determined by two numbers **F** and **B**. **F** is number of elements to print, **B** is the rollback distance (from last printed element). Each element must be printed on separate line and blank line must be inserted after each rollback. Run till the end of array. If endless loop or backward progression requested, program should print nothing and exit. Same for empty arrays.
**F** and **B** cannot be negative numbers. Be positive while dancing!
For example, if given:
```
array is 2, 3, 5, 7, 11, 101, 131;
F is 4;
B is 1;
```
then output must be:
```
2
3
5
7
5
7
11
101
11
101
131
```
Init array, **F** and **B** as you like.
Shortest code wins. Imperative beauty will be enjoyed.
**Test cases:**
```
Empty array.
Any F.
Any B.
```
Produces no output (array is empty).
---
```
Array: [42]
F = 0;
B = 1;
```
Produces no output (zero elements to print).
---
```
Array: [42, 17, 84]
F = 2;
B = 1;
```
Produces no output (endless printing).
---
```
Array: [7, 16, 65]
F = 2;
B = 3;
```
Produces no output (will be moving backward to negative indices).
---
```
Array: [7, 16, 65]
F = 2;
B = 0;
```
Output:
```
7
16
16
65
```
---
```
Array: [7, 16, 65]
F = 3;
B = 2;
```
Output:
```
7
16
65
```
(no rollback, end of array is reached).
---
```
Array: [7, 16, 65]
F = 17;
B = 15;
```
Output:
```
7
16
65
```
(run till the end)
---
```
Array: [7, 16, 65]
F = 17;
B = 16;
```
Output:
```
7
16
65
```
Whole array can be printed in first iteration, run till the end is working, even if F and B form endless-loop condition.
[Answer]
# JavaScript, 119 bytes
```
(a,b,c)=>{o="";for(s=++b;(s<(t=c.length)||s==b)&&s>=0&&b<a;)s-=b,o+=c.slice(s,s+=a<t?a:t).join`
`+`
`;return s>0?o:""}
```
[Try it online!](https://tio.run/nexus/javascript-node#jcy9DoIwFIbhnaswDE2bHgk/IgY4cCHGBEoAMQ1NOHUSrx1xw7iwfMv75Otw4TUoaAQWL4Oum3Vm4oRSqoxTzi02nm7H3t7FPBOiEoxRgT5jKq8zQUdUYOSKSA9NywlIYp3bsk6t8B5mGCunkpXjVNnU2uc0HqjwS5O67ntpzEhGt542Pe94ACFcvxPBCWI4QwKXmxDOrwoh2KGSNW7Vv4h2/sQbtfblAw "JavaScript (Node.js) – TIO Nexus")
Receives input in the format F, B, [Array]
[Answer]
# [Python 2](https://docs.python.org/2/), ~~135~~ ~~128~~ 126 bytes
Pretty naive solution:
```
a,f,b=input()
b+=1
l=len(a)
i=0
e=min(l,f)
while f>b:
print'\n'.join(map(str,a)[i:e])+'\n';i=e-b
if e==l:f=b
e=min(l,e+f-b)
```
[Try it online!](https://tio.run/nexus/python2#NUzLCsIwEDx3v2JvTehWGqsIkfVH1EMCG4xNY6kVP7@mBw8zzDCP1VEgzzFPn0Vp8A0bSJwkK6chcgfCY8wqUSg2YLh4C/h9xCRoLFTTHPNS33K9e75KbXSTei8zOX2NVu662aJzZGk9VGUuzMn6WdwA1f9YmtB6va5qT9gTHglPhMYUdBv1RhMeivgB "Python 2 – TIO Nexus")
Input format is `[array], F, B` except you can also use `()`. (You can't use `{}` because that's unordered; thanks to Felipe Batista for pointing that out because I forgot).
Output format is as specified in the challenge, with a single trailing newline at the end of all output and no leading whitespace.
-7 bytes by changing `if f>b: while 1:` to `while f>b`
-2 bytes by changing `break` to `f=b` because that causes the `while` loop to exit.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes
```
gD²³+‹iq}©0U[XD²<+Ÿv¹yè,}¶,³X+U®X³2*+-0‹#
```
[Try it online!](https://tio.run/nexus/05ab1e#@5/ucmjToc3ajxp2ZhbWHlppEBodARSx0T66o@zQzsrDK3RqD23TObQ5Qjv00LqIQ5uNtLR1DYCKlf//jzbUMdIxjuUy4TL@mpevm5yYnJEKAA "05AB1E – TIO Nexus")
That output format, and inability to limit inputs for F/B made this less fun, will explain soon.
[Answer]
## Python 2, 116
Finally beat javascript!
Now in case of endless loop outputs full array only if it fits in one step, otherwise ouputs nothing. Output all array in every case of endless loop was harder.
Uncomment different test cases in footer in [Try it online](https://tio.run/nexus/python2#bVDLUtswFF3HX3GGLLDjGxrnVSD1Jov8RPBCcW6IQA9XksvQRX89lXFgQotmpIXuued1ErShdSlN04Y0S1Sp2KQiG29Wutzkf9awblysfKm@6ZXPyyJP/Uj/UFlysA4S0sAJ88ipz@4bJ024ejBXN09WmlSLJvXBkci2eiTvN7kc6SrfXl9X2Sk5baeEGWFB@E4oingn3TPrnnmcFYs4LZbzihY0HQyGMDaAf7ZCYads/ew7aduGaBtjuNZ4BKkUwpHBZg97gHBOvCbDbSewJCwXFU1pMujOEGuUmAzi9AsfFS2p6GHGwlnFO1E/R5lLYjgW9ZH3nwVmndm3zYhV7D2UtQ29O31qfcDLMTKeSaypGTuuResZhzYG6P8PMvQJDcMHbpIoU9Gkt/Xu7CM@6ya8fuSdTy@QZ2CP@83OghVrNpE@WOylb9Tnkgi3t4S7u66s2f9S2v6S5hFdIV9vnRv4x@BFGX8B)
```
a,F,B=input()
l=len(a)-F;m=F+~B or-1;s=l/m;s+=1+(s*m<l)
for i in range(s):print"\n".join(map(str,a)[m*i:F+i*m]+[''])
```
Explanation:
```
a,F,B=input()
l=len(a)-F # length of input array minu F stored to compact code
m=F+~B or-1 # get the difference beetween blocks of output
# if F-B-1 == 0, which means endless loop, makes m = -1, which will make s < 0 and for loop won't execute
s=l/m # get number of blocks (does not count first block)
s+=1+(s*m<l) # +1 for first block (brackets are still needed)
# s*m<l-F equals +1 for numbers at the end of array, that are not enough to make full block
# s becomes 2 in case of F-B-1==0, but it doesn't matter
for i in range(s):
# print elements from slices, joined by line separator
# additional empty element added at the end of each block to divide blocks with newline
print"\n".join(map(str,a)[m*i:F+i*m]+[''])
```
[Answer]
# Ruby, ~~78 76~~ 72 bytes
```
->a,f,b{i=b-=f-1;puts a[i,f]+[""]while 0>b&&a[f+i-=b];b<i&&puts(a[i,f])}
```
### Explanation
* Initialize the index so that the first step brings it back to zero.
* Print `f` elements from the array starting with the current index, then a newline
* Move the index `f-b-1` elements forward, but only if `(b-f+1)` is negative
* If the increment is not negative, or we reached the end of the array, stop.
* If everything went Ok, the increment is negative, and the index is not (we took at least one step forward), in this case print the remaining elements.
[Answer]
## Mathematica, ~~136~~ 123 bytes
Here's my answer:
```
""<>r[#~(r=Riffle)~"\n"&/@Quiet@Check[Partition[#,#2,n=#2-#3-1,1,{}]~Take~-Floor[(L=#2-Length@#)/n-1],If[L<0,{},{#}]],"\n\n"]&
```
(where `\n`s are replaced by newlines). It's a function that takes a list of strings (e.g. `{"1", "2", "3", ...}`) and two integers.
Mathematica has a function that almost solves this challenge on its own, namely `Partition[#, #2, #2-#3-1, 1, {}]`. However, the output format isn't what we want, it returns errors if **F** and **B** would put the program into a loop, and it doesn't stop when it reaches the end of a list (so if the inputs are `{"1", "2", "3"}`, `3`, `1`, for instance, it returns `{{"1", "2", "3"}, {"2", "3"}, {"3"}}` instead of just `{{"1", "2", "3"}}`). We deal with those technicalities as follows:
* `...~Take~-Floor[(L=#2-Length@#)/n-1]` gets rid of the extra bits after we hit the end of the list.
* `Quiet@Check[...,If[L<0,{},{#}]]` deals with the infinite loop cases by `Check`ing if the earlier code gives errors (but it does it `Quiet`ly, so it doesn't actually print them), and instead returns an empty list or the entire list as appropriate.
* `""<>r[#~(r=Riffle)~"\n"&/@...,"\n\n"]&` formats the output properly, by putting newlines between everything, including double newlines between the separate groups, and string-joins that all together.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 123 bytes
```
[[[dx]dx]sOzlF!>O]sO?1+sBsFlFlB-1>O_1sq[lq1+:Rlq1+sqz0<k]dskx0sd[[10PlqlB+sq]sWld0<W]sz[ldlF%0=zlq;Rplq1-dsqld1+sd0!>g]dsgx
```
Much longer than it should have been because of strict output regulations. Takes input on one line in the format
```
n_1 n_2 ... n_k F B
```
where `n_i` represents the `i`th element of the `k` length array. I hope this is an okay input format.
[Try it online!](https://tio.run/nexus/dc#FcsxC8IwEAXgv5IOTiWQaEDRGiFD1kiXDkcQ6UmFHmq4JeR/O8cIj8fjwVcBAHNs4VDIdza0cdE9O/bkyUltw01zAkq6P47/5lTUsEbkNStGAK2ulMi1P/JEqIYpcgFC8ht1LpRO46cxiZwIm0bV2aXpJddqtkLvxcEII3bf11vO9/n5@AE "dc – TIO Nexus")
] |
[Question]
[
# String Similarity
String similarity is basically a ratio of how similar one string is to another. This can be calculated in many ways, and there are various algorithms out there for implementing a ratio calculation for string similarity, some being more accurate than others. It's actually very useful to use these methods in diff algorithms for the calculation of how similar one document or string is to one another.
A couple of the most popular algorithms are:
* [The Levenshtein Distance Algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance)
* [Jaro-Winkler Distance Algorithm](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance)
* [Adjacent Pairing Algorithm](http://www.catalysoft.com/articles/StrikeAMatch.html)
In practice, calculating all three and taking the average works very well for most purposes. However, to keep the challenge more simple, I am not going to over-ask. For the purpose of this challenge, you must implement the **Jaro-Winkler algorithm**.
# Rules
* Built ins are welcome, but must be marked non-competing, (E.G. `.L` *- **05AB1E***)
* Your input must only be 2 strings `f(a,b)`.
* The comparison should be Case insensitive, that is to say: `f('aBc','aBC')=f('abc','Abc')=f('abc','abc')=1.0`
In other words, convert the strings to lower case before the comparison or something like that.
* Your output must be a double, float or ratio appropriately expressed in the language of your choice; as long as the output is obviously interpreted, it's fine.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins.
# Examples
* `jw(a,b)` represents Jaro-Winkler similarity.
## [Example Algorithm in Java](https://github.com/idafensp/WicusAnnotationTool/blob/master/WicusWebAnnotatorUI/src/net/oegupm/wicus/webannotator/utils/stringsimilarity/JaroStrategy.java)
```
/**
* Calculates the similarity score of objects, where 0.0 implies absolutely
* no similarity and 1.0 implies absolute similarity.
*
* @param first
* The first string to compare.
* @param second
* The second string to compare.
* @return A number between 0.0 and 1.0.
*/
public static final double jaroSimilarity(final String first,
final String second) {
final String shorter;
final String longer;
// Determine which String is longer.
if (first.length() > second.length()) {
longer = first.toLowerCase();
shorter = second.toLowerCase();
} else {
longer = second.toLowerCase();
shorter = first.toLowerCase();
}
// Calculate the half length() distance of the shorter String.
final int halflength = (shorter.length() / 2) + 1;
// Find the set of matching characters between the shorter and longer
// strings. Note that
// the set of matching characters may be different depending on the
// order of the strings.
final String m1 = getSetOfMatchingCharacterWithin(shorter, longer,
halflength);
final String m2 = getSetOfMatchingCharacterWithin(longer, shorter,
halflength);
// If one or both of the sets of common characters is empty, then
// there is no similarity between the two strings.
if (m1.length() == 0 || m2.length() == 0)
return 0.0;
// If the set of common characters is not the same size, then
// there is no similarity between the two strings, either.
if (m1.length() != m2.length())
return 0.0;
// Calculate the number of transpositions between the two sets
// of common characters.
final int transpositions = transpositions(m1, m2);
// Calculate the distance.
final double dist = (m1.length() / ((double) shorter.length())
+ m2.length() / ((double) longer.length()) + (m1.length() - transpositions)
/ ((double) m1.length())) / 3.0;
return dist;
}
/**
* Gets a set of matching characters between two strings. Two characters
* from the first string and the second string are considered matching if
* the character's respective positions are no farther than the limit value.
*
* @param first
* The first string.
* @param second
* The second string.
* @param limit
* The maximum distance to consider.
* @return A string contain the set of common characters.
*/
private static final String getSetOfMatchingCharacterWithin(
final String first, final String second, final int limit) {
final StringBuilder common = new StringBuilder();
final StringBuilder copy = new StringBuilder(second);
for (int i = 0; i < first.length(); i++) {
final char ch = first.charAt(i);
boolean found = false;
// See if the character is within the limit positions away from the
// original position of that character.
for (int j = Math.max(0, i - limit); !found
&& j < Math.min(i + limit, second.length()); j++) {
if (copy.charAt(j) == ch) {
found = true;
common.append(ch);
copy.setCharAt(j, '*');
}
}
}
return common.toString();
}
/**
* Calculates the number of transpositions between two strings.
*
* @param first
* The first string.
* @param second
* The second string.
* @return The number of transpositions between the two strings.
*/
private static final int transpositions(final String first,
final String second) {
int transpositions = 0;
for (int i = 0; i < first.length(); i++) {
if (first.charAt(i) != second.charAt(i)) {
transpositions++;
}
}
transpositions /= 2;
return transpositions;
}
```
Here's all my test cases, if you want another one, ask me.
```
jw ('abc','AbC')=1.0
jw ('i walked to the store','the store walked to i')=0.7553688141923436
jw ('seers','sears')=0.8666666666666667
jw ('banana','bandana')=0.9523809523809524
jw ('abc','xyz')=0.0
jw ('1234567890qwertyuiopasdfghjklzxcvbnm','mnbvcxzlkjhgfdsapoiuytrewq0987654321')=0.5272904483430799
jw ('#faceroll:j4565j6eekty;fyuolkidsujkr79tp[8yiusyweryhjrn7ktgm9k,u[pk7jf6trhvgag5vhbdtnfymghu,','#faceroll:ezbrytnmugof7ihdgsyftwacvegybrnftiygihdugs5ya4tsyrdu6htifj7yif')=0.6512358338650381
```
[Answer]
# Python 3, ~~351~~ ~~350~~ ~~347~~ 346 bytes
```
l=len
r=range
a,b=input(),input()
x,y=(a.lower(),b.lower())[::1-2*(l(a)>l(b))]
h=l(y)//2+1
n=o=''
for a,b in(x,y),(y,x):
for i in r(l(a)):
for j in r(max(0,i-h),min(i+h,l(b))):
if b[j]==a[i]:o+=a[i];b=b[:j]+'*'+b[j+1:];break
n,o=o,n
q,z=l(n),l(o)
print(0if(any((n,o))-1or z!=q)else(z/l(y)+q/l(x)+(z-sum(n[i]!=o[i]for i in r(l(n)))/2)/z)/3)
```
Expects the two inputs on STDIN, newline-separated. Example run:
```
$ echo -e "seers\nsears" | python jaro.py
0.8666666666666667
```
*Saved 1 byte thanks to @Shebang!*
] |
[Question]
[
# Challenge
Your program will take in a string from **stdin**, and output multiple lines to **stdout**.
An example of input looks like this:
My favorite Chipotle order:
>
> B1113YNNY
>
>
>
Let's break it down:
* The first character is either A (burrito), or B (burrito bowl).
* The second character is 1 (black beans), or 2 (pinto beans).
* The third character is either 1 (white rice), or 2 (brown rice).
* The fourth character is either 1 (chicken), 2 (sofritas), or 3 (steak).
* The fifth character is either 1 (mild salsa), 2 (medium salsa), or 3 (hot salsa).
* The last four characters are Y if they want the item, or N otherwise:
* character 6 is corn
* character 7 is guacamole
* character 8 is sour cream
* character 9 is cheese
A working program for this challenge will output this to **stdout**:
>
> burrito bowl with:
>
> black beans
>
> white rice
>
> chicken
>
> hot salsa
>
> corn
>
> cheese
>
>
>
Replace the above words with the words acquired from input.
# Clarifications.
Standard loopholes are disallowed.
You may *only* get input from stdin, and *only* put output to stdout.
[Answer]
# Python 3, 293 bytes
```
j=input();a,b,c,d,e,f,g,h,i=[1-ord(c)%7%5for c in j];print('\n'.join(('burrito'+[' bowl',''][a]+' with:',['pinto','black'][b]+' beans',['brown','white'][c]+' rice',['sofritas','chicken','steak'][d],['medium','mild','hot'][e]+' salsa'))+'\ncorn'*f+'\nguacamole'*g+'\nsour cream'*h+'\ncheese'*i)
```
Mostly basic lookups with a little modulo trickery for the indexes of items:
`AB123YN` yielding indexes `-1,-2,1,0,-1,1,0` respectively, and
using string multiplication for the optional items rather than a lookup.
[Answer]
## Python 2, ~~302~~ 298 bytes
```
o=input()
print"\n".join([s[0]+s[1+(ord(c)+1)%3]+s[-1]for(x,c)in zip(["burrito ,,bowl, with:",",black,pinto, beans",",white,brown, rice",",chicken,sofritas,chicken,",",mild,medium,hot, salsa"],o)for s in[x.split(",")]]+[x for(x,c)in zip(["corn","guacamole","sour cream","cheese"],o[5:])if c=="Y"])
```
EDIT: according to the [consensus on meta](https://codegolf.meta.stackexchange.com/questions/7633/string-input-with-or-without/7634#7634), I'm allowed to use `input` instead of `raw_input`, requiring the user of the program to type his or her Chipotle order in quotes! Thanks, @StevenH. for informing me of this.
[Answer]
# Python 2, ~~336~~ 335 Bytes
```
q,i=input(),int
print"burrito "+{"A":"","B":"bowl"}[q[0]]+" with:\n"+["black","pinto"][i(q[1])-1]+" beans\n"+["white","brown"][i(q[2])-1]+" rice\n"+["chicken","sofritas","steak"][i(q[3])-1]+"\n"+["mild","medium","hot"][i(q[4])-1]+" salsa\n"+"\n".join([x for y,x in enumerate(["corn","guacamole","sour cream","cheese"]) if q[y+5]=="Y"])
```
[Try it online!](https://repl.it/CqXv/0)
Removed one byte by renaming `int`: `i=int`
[Answer]
# Pyth, 225 Bytes
```
=rQ0s["burrito "?xGhQ"bowl "k"with:")+@,"pinto""black"shtQ" beans"+@,"brown""white"shttQ" rice"@c"steak chicken sofritas")s@Q3+@c"hot medium mild")s@Q4" salsa"seMf}\y@QhT[,5"corn\n",6"guacamole\n",7"sour cream\n",8"cheese\n")
```
[Answer]
## Batch, ~~445~~ 364 bytes
```
@echo off
set/ps=
set l=call:l
%l%"burrito with:" "burrito bowl with:"
%l%"black beans" "pinto beans"
%l%"white rice" "brown rice"
%l%chicken sofritas steak
%l%"mild salsa" "medium salsa" "hot salsa"
%l%corn
%l%guacamole
%l%"sour cream"
%l%cheese
exit/b
:l
for %%a in (B N 2 3 3)do if %s:~0,1%==%%a shift
if not "%~1"=="" echo %~1%
set s=%s:~1%
```
New rewrite saved me 81 bytes. Reading from STDIN conveniently saves a byte over using the command line. Each character of the input is processed in turn to select from a list of options; the characters `B`, `N` and `2` cause the second option to be chosen, while `3` causes the third option to be chosen.
[Answer]
## Racket 544 bytes
```
(let*((s(read-line))(l(string->list s))(lr list-ref)(d displayln)(p display)(c -1)(g(λ()(set! c(+ 1 c))(lr l c))))
(match(g)[#\A(d"burrito with:")][#\B(d"burrito bowl with:")])(match(g)[#\1(d"black beans")][#\2(d"pinto beans")])
(match(g)[#\1(d"white rice")][#\2(d"brown rice")])(match(g)[#\1(d"chicken")][#\2(d"sofritas")][#\3(d"steak")])
(match(g)[#\1(p"mild ")][#\2(p"medium ")][#\3(p"hot ")])(d"salsa")(match(g)[#\Y(d"corn")][#\N""])
(match(g)[#\Y(d"guacamole")][#\N""])(match(g)[#\Y(d"sour cream")][#\N""])(match(g)[#\Y(d"cheese")][#\N""]))
```
Ungolfed:
```
(define (f)
(let* ((s (read-line))
(l (string->list s))
(lr list-ref)
(d displayln)
(p display)
(c -1)
(g (lambda() (set! c (add1 c)) (lr l c))))
(match (g)
[#\A (d "burrito with:")]
[#\B (d "burrito bowl with:")])
(match (g)
[#\1 (d "black beans")]
[#\2 (d "pinto beans")])
(match (g)
[#\1 (d "white rice")]
[#\2 (d "brown rice")])
(match (g)
[#\1 (d "chicken")]
[#\2 (d "sofritas")]
[#\3 (d "steak")])
(match (g)
[#\1 (p "mild ")]
[#\2 (p "medium ")]
[#\3 (p "hot ")])
(d "salsa")
(match (g)
[#\Y (d "corn")]
[#\N ""])
(match (g)
[#\Y (d "guacamole")]
[#\N ""])
(match (g)
[#\Y (d "sour cream")]
[#\N ""])
(match (g)
[#\Y (d "cheese")]
[#\N ""])))
```
Testing:
```
(f)
burrito bowl with:
black beans
white rice
chicken
hotsalsa
corn
cheese
```
[Answer]
# PHP, 301 Bytes
```
<?="burrito".($i=$_GET[a])[0]>A?" bowl":""," with:\n".[black,pinto][$i[1]>1]." beans\n".[white,brown][$i[2]>1]." rice\n".[_,chicken,sofritas,steak][$i[3]]."\n".[_,mild,medium,hot][$i[4]]." salsa".["","\ncorn"][$i[5]>N].["","\nguacamole"][$i[6]>N].["","\nsour cream"][$i[7]>N].["","\ncheese"][$i[8]>N];
```
Previous version 311 Bytes
```
<?printf("burrito%s with:\n%s beans\n%s rice\n%s\n%s salsa%s%s%s%s",($i=$_GET[a])[0]>A?" bowl":"",[black,pinto][$i[1]>1],[white,brown][$i[2]>1],[_,chicken,sofritas,steak][$i[3]],[_,mild,medium,hot][$i[4]],["","\ncorn"][$i[5]>N],["","\nguacamole"][$i[6]>N],["","\nsour cream"][$i[7]>N],["","\ncheese"][$i[8]>N]);
```
[Answer]
# C#, 737 Bytes
*Not going to win any prizes here...*
Golfed:
```
string O(string s){var c=new List<string>();var m=new Dictionary<int,List<string>>(){{0,new List<string>(){"burrito","burrito bowl"}},{1,new List<string>(){"","black beans","pinto beans"}},{2,new List<string>(){"","white rice","brown rice"}},{3,new List<string>(){"","chicken","sofritas","steak"}},{4,new List<string>(){"","mild salsa","medium salsa","hot salsa"}},{5,new List<string>(){"corn"}},{6,new List<string>(){"guacamole"}},{7,new List<string>(){"sour cream"}},{8,new List<string>(){"cheese"}},};for(int i=0;i<s.Length;i++){if(i==0){c.Add(s[0]=='A'?m[0][0]:m[0][1]+" with:");continue;}if(i>4){c.Add(s[i]=='Y'?m[i][0]:"");continue;}c.Add(m[i][int.Parse(s[i]+"")]);}return string.Join("\n",c.Where(o =>!string.IsNullOrEmpty(o)));}}
```
Ungolfed:
```
public string O(string s)
{
var c = new List<string>();
var m = new Dictionary<int, List<string>>()
{
{0, new List<string>(){"burrito", "burrito bowl"}},
{1, new List<string>(){"", "black beans", "pinto beans"}},
{2, new List<string>(){ "", "white rice", "brown rice"}},
{3, new List<string>(){ "", "chicken", "sofritas", "steak"}},
{4, new List<string>(){ "", "mild salsa", "medium salsa", "hot salsa"}},
{5, new List<string>(){"corn"}},
{6, new List<string>(){"guacamole"}},
{7, new List<string>(){"sour cream"}},
{8, new List<string>(){"cheese"}},
};
for (int i = 0; i < s.Length; i++)
{
if (i == 0)
{
c.Add(s[0] == 'A' ? m[0][0] : m[0][1] + " with:");
continue;
}
if (i > 4)
{
c.Add(s[i] == 'Y' ? m[i][0] : "");
continue;
}
c.Add(m[i][int.Parse(s[i]+"")]);
}
return string.Join("\n", c.Where(o => !string.IsNullOrEmpty(o)));
}
```
Testing:
```
var chipotleOrder = new ChipotleOrder();
Console.WriteLine(chipotleOrder.P(Console.ReadLine()));
Console.ReadLine();
```
Output:
```
burrito bowl with:
black beans
white rice
chicken
hot salsa
corn
cheese
```
[Answer]
# JavaScript (ES6), 267
```
a=>[...a].map((c,i,a,s=x=>`
`+(','+x).split`,`[c])=>i--?i--?i--?i--?i?c>'N'?(c=i,s`corn,guacamole,sour cream,cheese`):'':s`mild,medium,hot`+' salsa':s`chicken,sofritas,steak`:s`white,brown`+' rice':s`black,pinto`+' beans':'burrito'+(c>'A'?' bowl':'')+' with:').join``
```
*Less golfed*
```
a=>
[...a].map((c,i,a,s=x=>'\n'+(','+x).split`,`[c])=>
i--?i--?i--?i--?i?
c>'N'?(c=i,s`corn,guacamole,sour cream,cheese`):''
:s`mild,medium,hot`+' salsa'
:s`chicken,sofritas,steak`
:s`white,brown`+' rice'
:s`black,pinto`+' beans'
:'burrito'+(c>'A'?' bowl':'')+' with:'
).join``
```
**Test**
```
f=
a=>[...a].map((c,i,a,s=x=>`
`+(','+x).split`,`[c])=>i--?i--?i--?i--?i?c>'N'?(c=i,s`corn,guacamole,sour cream,cheese`):'':s`mild,medium,hot`+' salsa':s`chicken,sofritas,steak`:s`white,brown`+' rice':s`black,pinto`+' beans':'burrito'+(c>'A'?' bowl':'')+' with:').join``
function update()
{
O.textContent=f(I.value);
}
update()
```
```
<input id=I value="B1113YNNY" oninput='update()'><pre id=O></pre>
```
] |
[Question]
[
**Uptime** is a very important metric, as we all know, so we'd like to measure the uptime since our service was first launched. The SLA specifies an uptime of a certain number of nines, such as 3 nines for at least `99.9%` uptime, or 1 nine for at least `90%` uptime, and you're wondering if you've actually met the SLA or not. Since you know the service went down last friday night when *someone* pushed to production, and since this is basically standard practice here, you figure there's no need for your code to handle 100% uptime as a special case.
Everytime a server stops or starts, Nagios sends you an email. The service in question has some level of fault tolerance, so only `m` servers have to be online for the service to be available. You just wrote a quick script to extract the important information from these emails. Now it's time for the fun part, and you're in the mood for golfing.
**Your task** is to write a program or function that analyzes the input, figures out the uptime, and prints the largest integer number of nines achieved by the service.
**Input:**
* The number of servers required to be running for the service to be considered online: `m` > 0.
* Followed by at least one line, one for each server. Each line contains start/stop times for that server. Since we've measured this since the service was launched, the first number is the time the server started the first time. The second time is a stop time, the third another start time etc.
* No single server is ever started and stopped at the same time.
* This means that if the server is currently running, you haven't gotten an email about it shutting down yet, so the number of numbers on that line would be odd.
* The lines are sorted, but the ordering between different lines is not enforced.
* The input is EOF-terminated. The last character of the input will be `\n` followed by `EOF` (ctrl+D).
* The time starts at time `0` and ends at the last recorded start/stop of a single server, since that's all the information we have so far. This can be done by adding max(last number on each line) to the end of all odd-length lines.
* Time is discrete.
* All input numbers are guaranteed to fit inside a 32bit integer.
* The service will never have 100% uptime.
* If you would like to add an integer telling you how many servers there are, you may do so. You may also add an integer in the beginning of each server line telling you how many measurements there are for that server. See example in first testcase. **You may also use whatever native format you'd like.**
**Output:**
The output consists of a single integer; the highest number of nines that you can guarantee you had in hindsight, i.e. `3` for at least `99.9%` uptime or `4` for at least `99.99%` uptime.
**Testcases:**
First:
```
1
0 5 8 10
0 1 7
-> 1
```
First, with counts (if you prefer that):
```
1 2
4 0 5 8 10
3 0 1 7
-> 1
```
Second:
```
1
0 999 1001 2000
-> 3
```
Third:
```
3
0 42
-> 0
```
**Reference implementation:** (Python 2)
```
"""
Slow and huge, but useful for checking smaller inputs.
input: m, followed by n lines of start and stop times, all servers are turned off in the beginning, all numbers fit inside 32bit signed integers, counts are optional
output: number of nines of uptime
example:
1
0 5 8 9
0 1 7
parsed:
1st node: on 0:5, 7:9
2nd node: on 0:1, 6:9
at least one server is running during:
0:5, 7:9
known time interval: 0:9, only timestep 6 is down, so 90% uptime during the part we can see.
output:
1
"""
import sys
def rangeify(l):
res = []
for i in range(0, len(l), 2):
res += range(l[i], l[i + 1] + 1)
return res
def parse():
m = input()
lines = [map(int, x.split()) for x in sys.stdin.read().split("\n")[:-1]]
if not lines:
return [], m
top = max(map(max, lines))
nlines = [x + [top] if len(x) % 2 else x for x in lines]
n2lines = map(rangeify, nlines)
return n2lines, m
def flatten(ls):
res = []
for l in ls:
res += l
return sorted(res)
def join(ups):
res = {}
for up in ups:
if up not in res:
res[up] = 0
res[up] += 1
return res
def bin(ups, m):
res = []
for up in range(max(ups)+1):
res += [up in ups and ups[up] >= m]
return res
def nines(a):
s = ("%.15f" % a)[2:]
s2 = s.lstrip("9")
return len(s) - len(s2)
def solve(l, m):
if len(l) < m:
return nines(0)
b = bin(join(flatten(l)), m)
return nines(sum(b) / float(len(b)))
print solve(*parse())
```
[Answer]
# Pyth - 26 bytes
```
/`.Omgsm%lf<dTk2.QQeSs.Q`9
```
[Try it online here](http://pyth.herokuapp.com/?code=%2F%60.Omgsm%25lf%3CdTk2.QQeSs.Q%609&input=1%0A0%2C+999%2C+1001%2C+2000&debug=0).
[Answer]
## JavaScript (ES6), 161 bytes
```
(m,a)=>a.map(b=>b.map(n=>l=n>l?n:l),l=0)|a.map(b=>c.map((_,i)=>{k=b[j]==i;j+=k;n^=k;c[i]+=n|k},j=n=0),c=Array(++l).fill(0))|Math.log10(l/c.filter(n=>n<m).length)
```
Accepts an integer representing the minimum number of concurrent servers and an array of arrays representing the start and stop times of each server. Edit: Now uses inclusive ranges, so correctly returns 1 for the first example.
] |
[Question]
[
**Pre-Note**
Because of popular demand, and to avoid disqualifying certain languages, the dictionary can now be provided as input parameter.
# Intro
Given a dictionary of words, you should write an autocomplete program or function.
# Autocompletion
*"Autocomplete, or word completion, is a feature in which an application predicts the rest of a word a user is typing."* ([Wikipedia](https://en.wikipedia.org/wiki/Autocomplete))
Autocompletion is oftenly used to reduce the time needed for typing sentences. After typing a single character, the program will start guessing what the user is trying to say. In this challenge we will simulate the behaviour of autocompleting words.
If the program encounters a word it doesn't know, and no matching autocompletion words can be found, it will assume that the user is trying to type a word the program doesn't know. Good autocompletion software will own and edit a custom dictionary of words, but for the sakes of complexity that's not part of this challenge.
# Input
Your program/function will take at least a single parameter of input. This parameter can either be a string or an array of characters, and will consist of lowercase characters `[a-z]`.
Optionally, your program/function will take a second parameter containing a dictionary of words. More info on this in the paragraph **Dictionary**.
# Output
You should print or return an array of autocompleted words. For each character in the input, an autocompletion should be added to the output array.
The autocompletions will be taken from the provided dictionary. If a word doesn't exist in the dictionary, it will alphabetically search for the next word matching your characters. If no matching word is found, the input will be returned (see test cases)
# Dictionary
If you choose to read the dictionary from a file, the file structure should be your list of words, seperated by newlines.
If you choose to submit the dictionary of words as a parameter of a function call, it should be structured as an ordered list of strings; `['cat', 'cake', ...]`.
The input is always fully lowercase and sorted alphabetically.
# Test case
`a.txt` content:
```
alpha
calf
cave
coax
code
codegimmick
codegolf
cool
gamma
```
Test cases:
```
"codegolf" // ["calf", "coax", "code", "code", "codegimmick", "codegolf", "codegolf", "codegolf"]
"alpaca" // ["alpha", "alpha", "alpha", "alpa", "alpac", "alpaca"]
["t", "h", "i", "s"] // ["t", "th", "thi", "this"]
("catses", ["cake","cats"]) // ["cake", "cake", "cats", "cats", "catse", "catses"]
```
This is code-golf, shortest code in bytes wins
[Answer]
## Pyth, ~~22~~ 13 bytes
```
mhf!xTd+Qd._z
```
```
m _z map over prefixes of second input...
hf +Qd find the first element in (dictionary+word) which...
!xTd ... starts with k
```
Sample run:
```
llama@llama:~$ pyth -c 'mhf!xTd+Qd._z'
['alpha', 'calf', 'cave', 'coax', 'code', 'codegimmick', 'codegolf', 'cool', 'gamma']
codegolf
['calf', 'coax', 'code', 'code', 'codegimmick', 'codegolf', 'codegolf', 'codegolf']
```
Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for 4 bytes!
[Answer]
# JavaScript (ES6), 56
Input: array of characters, array of words
Output: array
```
(s,d,w='')=>s.map(c=>d.find(e=>e.startsWith(w),w+=c)||w)
```
**Test**
```
f=(s,d,w='')=>s.map(c=>d.find(e=>e.startsWith(w),w+=c)||w)
dict=['alpha','calf','cave','coax','code','codegimmick','codegolf','cool','gamma']
console.log=x=>O.textContent+=x+'\n'
;[['c','o','d','e','g','o','l','f'],['a','l','p','a','c','a'],['t','h','i','s']]
.forEach(t=>console.log(t+' -> '+f(t,dict)))
```
```
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6 / Node.js), 94 bytes
```
s=>s.map(c=>(d.match(`\\b${p+=c}.*`)||p)+"",p="",d=require("fs").readFileSync("a.txt","utf8"))
```
Anonymous function that takes an array of characters.
Or **52 bytes** in **JavaScript (ES6)** with passing the dictionary as a string:
```
d=>s=>s.map(c=>(d.match(`\\b${p+=c}.*`)||p)+"",p="")
```
[Answer]
# Python 3, 94 bytes
```
s=""
for c in input():s+=c;print(next((o for o in open("a.txt")if o.startswith(s)),s).strip())
```
[Answer]
# Mathematica, ~~108~~ 89 bytes
```
Select[Append[#2,c=b~StringTake~a],StringStartsQ@c][[1]]~Table~{a,StringLength[b=""<>#]}&
```
No, it isn't very pretty.
[Answer]
# Javascript ES6, ~~80~~ 77 chars
```
(w,d)=>[...w].map((x,i)=>RegExp(`\\b${x=w.slice(0,i+1)}\\w*`).exec([d,x])[0])
```
Test:
```
d="alpha,calf,cave,coax,code,codegimmick,codegolf,cool,gamma".split`,`;
f=(w,d)=>[...w].map((x,i)=>RegExp(`\\b${x=w.slice(0,i+1)}\\w*`).exec([d,x])[0])
;[
f("cat", ["cat"])[0] === "cat",
f("codegolf", d) == '' + ["calf", "coax", "code", "code", "codegimmick", "codegolf", "codegolf", "codegolf"],
f("alpaca", d) == '' + ["alpha", "alpha", "alpha", "alpa", "alpac", "alpaca"],
f("this", d) == '' + ["t", "th", "thi", "this"],
f("catses", ["cake","cats"]) == '' + ["cake", "cake", "cats", "cats", "catse", "catses"]
]
```
Can reduce 4 chars (73 in total) if return array of single-element arrays:
```
(w,d)=>[...w].map((x,i)=>RegExp(`\\b${x=w.slice(0,i+1)}\\w*`).exec(d)||x)
```
Test:
```
d="alpha,calf,cave,coax,code,codegimmick,codegolf,cool,gamma".split`,`;
f=(w,d)=>[...w].map((x,i)=>RegExp(`\\b${x=w.slice(0,i+1)}\\w*`).exec(d)||x)
;[
// f("cat", ["cat"])[0] === "cat", // will be failed
f("cat", ["cat"])[0][0] === "cat", // ok
f("codegolf", d) == '' + ["calf", "coax", "code", "code", "codegimmick", "codegolf", "codegolf", "codegolf"],
f("alpaca", d) == '' + ["alpha", "alpha", "alpha", "alpa", "alpac", "alpaca"],
f("this", d) == '' + ["t", "th", "thi", "this"],
f("catses", ["cake","cats"]) == '' + ["cake", "cake", "cats", "cats", "catse", "catses"]
]
[false, true, true, true, true]
```
] |
[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/77526/edit).
Closed 7 years ago.
[Improve this question](/posts/77526/edit)
This question will be deleted soon, do not read/answer it
### Introduction
Given one matrix `A x A` and a number of movements `N`.
You will need to walk like a spiral starting in `(1; 1)`:
1. right while possible, then
2. down while possible, then
3. left while possible, then
4. up while possible, repeat until got `N`.
### Challenge
You can only take as input the numbers `A` and `N`.
You must output the final `(row; column)` after walking `N` steps in the conditions explained above. You can not invert the output order.
You can use indexes starting with zero as well. Just state it in your answer.
Program or function allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins.
### Sample
For input (`A = 8; N = 54`).
[](https://i.stack.imgur.com/Ndnfh.png)
The output should be (`5; 6`).
### Another samples
```
input: A=8, N=64
output: [5, 4]
```
---
```
input: A=15, N=14
output: [1, 14]
```
---
```
input: A=26, N=400
output: [22, 9]
```
---
```
input: A=1073741824, N=1152921504603393520
output: [536871276, 536869983]
```
### Restrictions
1 <= A <= 230
1 <= N <= (A2 **OR** the below higher number supported in your language).
---
And, if you want a [generic formula](https://stackoverflow.com/a/33575439/4227915).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 24 bytes
This works in [release 16.0.0](https://github.com/lmendo/MATL/releases/tag/16.0.0) of the language, which predates the challenge.
```
2^Q6Y3GYLG2\?!P!}P]-=2#f
```
Output is 1-based, as in the examples.
`A^2` and `N` are limited to 2^53 as per the language's default data type (`double`). In addition, since the whole matrix is being generated, memory will limit `A` to significantly lower values.
[**Try it online!**](http://matl.tryitonline.net/#code=Ml5RRzZZM1lMRzJcPyFQIX1QXS09MiNm&input=MjYKNDAw) (In the online version I have changed the order of `G` and `6Y3` so it works in the new 16.1.0 release)
### Explanation
This uses MATL's builtin for generating an outward spiral. To make it inward, a subtraction and a reversal are needed. The direction of reversal depends on whether `A` is odd or even.
```
2^Q % take input A implicitly. Compute A^2+1
6Y3GYL % outward spiral of side length A
G2\ % is A odd?
? % if so
!P! % flip matrix horizontally
} % else
P % flip matrix vertically
] % end if
- % compute A^2+1 minus the matrix element-wise, so (1,1) contains 1
= % take input N implicitly. Set matrix entry that contains that value to true
2#f % row and column index of that true value
```
] |
[Question]
[
Some of you may have heard of the Wargame series of computer based real time strategy game. These games pit teams of players with primarily cold war era units to see how a hot cold war would have played out. The goal of this challenge is to simulate a tank battle in these games.
**Input**
* Two "tanks" (one red and one blue) will be entered into your program or function. Each tank is classified by a rate of fire, accuracy, armor value, and attack power value.
**Challenge**
From the inputs above, simulate the two tanks fighting. You will do this by having each tank fire according to its rate of fire. If it hits (randomly determined by accuracy), a tank will do damage according to the armor value of its target and its own attack power. The formula for damage is `floor[(attackpower - armor)/2]`. Therefore a tank with 10 attack power against a tank with 5 armor would do 2 damage.
Tank crews also have morale, which follows the following rule
* There are four possible morale values; calm, worried, scared, and panicked. Tanks always start calm. These names do not need to be in your code, in the sample below I've used calm = 1, worried = 2, etc.
* Each morale value reduces the accuracy as follows: Calm -> 100% (no change), worried -> 75%, scared -> 50%, panicked -> 25%. Therefore a panicked tank which normally has 60% accuracy now has 0.25 \* 0.6 = 15% accuracy
* Each hit by the opposing tank degrades morale by one level, each miss upgrades the morale by one level.
For example:
```
morale: calm | worried | calm | worried | scared
hit: hit miss hit hit
```
**Rules:**
* Input should be two parameters to repesent each tank (I've used two tuples in the example below). Inputs may be provided in any order, just be sure to state which one is which. Input may be provided by user input via STDIN, read from a file, or parameters passed to a function call.
* Each tank starts with 10 health.
* Rate of fire will either be 8.5, 7.5, 6.5, 6, 5, or 3 seconds between shots.
* Tanks start loaded, so each fires at time = 0. Because Communists are sneaky, red fires first.
* Accuracy must be randomly rolled.
* Ineffective hits (hits which do no damage) have an effect on morale! (because it probably sounds terrifying)
* Naturally since we want to see the action, output will be an update after each shot. The update will contain the time of the shot, whom it was made by (red or blue), health of both tanks, and the morale of both tank crews. Output maybe be presented in any format so long as it contains all of the required information in a human readable fashion (items must be delimited in some way). Similar to input, please describe your output format in the answer.
* Engagements are limited to 100 seconds. If you play the game you know this is because a plane has swooped in by then. For our purposes if both tanks are alive at this point, it is a draw.
* After one tank reaches 0 health (or after 100 seconds), print which tank is victorious (`"Red"` or `"Blue"`) or `"Draw"` if appropriate. I don't care about trailing whitespace or newlines.
* Printing output may be printing to STDOUT or writing to a file
* Shortest answer in bytes wins
**[Sample Python Implementation](https://ideone.com/tTu4uv)**
This is a little sample I worked up to demonstrate some of the methodology. It takes the two tanks as tuples to the `main()` function, then outputs a nice little table. Your output does not need to be so fancy. For the curious, it's 1,930 bytes. You can do better.
**Sample Tanks:**
Some tanks to use for you, the numbers are ROF, accuracy, armor, and power.
* T-72A: 8.5, 45%, 12, 16
* T-72BU: 8.5, 55%, 22, 23
* T-80: 7.5, 40%, 14, 16
* T-80U: 7.5, 60%, 20, 23
* M1 Abrams: 7.5, 55%, 16, 18
* M1A2 Abrams: 7.5, 60%, 22, 24
* Leclerc: 6, 65%, 20, 20
* STRV-103D: 5, 60%, 18, 16
* Zhalo (I know, not a tank): 3, 60%, 2, 18
[Answer]
# Python 3, 465
Saved 8 bytes thanks to wnnmaw.
Saved 34 bytes thanks to DSM.
Expects tanks as lists as follows, `[Rate of Fire, Accuracy, Armor, Attack]`
```
from random import*
def f(r,b):
r+=10,1;b+=10,1
for x in range(200):
if r[4]<1:return"Blue"
if b[4]<1:return"Red"
if x%int(r[0]*2)<1:
if random()>=(r[1]*r[5]):b[4]-=(r[3]-b[2])//2;b[5]-=(b[5]!=0.25)/4
else:b[5]+=(b[5]<1)/4
print('r,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
if x%int(b[0]*2)<1:
if random()>=(b[1]*b[5]):r[4]-=(b[3]-r[2])//2;r[5]-=(r[5]!=0.25)/4
else:r[5]+=(r[5]<1)/4
print('b,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
return"Draw"
```
Prints the output as `Attacker,TimeOfShot,RedHealth,RedMorale,BlueHealth,BlueMorale`. Morale is represented as a float.
] |
[Question]
[
# Symbolic Differentiation 2: Back on the Chain Gang
## Task
Write a program that takes in a certain sort of function from stdin and differentiates it with respect to *x*, using the chain rule.\* The input function will be a string of the following form:
```
"trig_1 trig_2 trig_3 ... x"
```
where `trig_n` is a trigonometric function `sin` or `cos`, and there are at most four functions in the term. The example string
```
"cos sin sin x"
```
represents the function cos(sin(sin(x))).
Your output must take the following form:
```
k(trig_1 trig_2 x)(trig_a trig_b trig_c x)(trig_m trig_n x) et cetera
```
where `k` is a constant and parentheses represent groups to be multiplied together.
\*The [chain rule](https://en.wikipedia.org/wiki/Chain_rule) states that `D[f(g(x))] = f'(g(x)) * g'(x)`
## Examples
```
"sin sin sin sin x" ==> 1(cos x)(cos sin x)(cos sin sin x)(cos sin sin sin x)
"cos x" ==> -1(sin x)
"cos sin x" ==> -1(cos x)(sin sin x)
```
## Scoring
Your score is the length of your program in bytes, multiplied by three if you use a built-in or a library that does symbolic algebra.
## Similar Challenges
[The previous installment: polynomial differentiation](https://codegolf.stackexchange.com/questions/54162/symbolic-differentiation-of-polynomials)
[Polynomial integration](https://codegolf.stackexchange.com/questions/66714/symbolic-integration-of-polynomials)
[General differentiation](https://codegolf.stackexchange.com/questions/31930/help-me-with-differential-calculus/31935#31935)
[Answer]
# Java 8, ~~224~~ 214 bytes
Let the games begin!
```
interface B{static void main(String[]a){String o="";int v=2,z=a.length-1,i=z,k;for(;i>0;o+="x)"){if(a[--i].equals("cos")){o+="(sin ";v=(v+2)%4;}else o+="(cos ";for(k=i;++k<z;)o+=a[k]+" ";}System.out.print(v-1+o);}}
```
This could (theoretically) extend infinitely.
Output for `sin cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x`:
```
1(cos x)(sin sin x)(sin cos sin x)(sin cos cos sin x)(cos cos cos cos sin x)(sin sin cos cos cos sin x)(cos cos sin cos cos cos sin x)(cos sin cos sin cos cos cos sin x)(sin sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos cos cos sin x)(cos sin cos sin sin cos sin cos cos cos sin x)(cos sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)
```
[Answer]
# sed, 88 + 1 = ~~123~~ 89 bytes
`+1` for the `-r` (extended regex) flag.
```
s/^/d/
:
s/d(-?)sin (.*)/(\1cos \2)d\2/
s/d(-?)cos (.*)/(\1-sin \2)d\2/
s/--//
s/dx/1/
t
```
## Explanation
Note: A single `d` is used as short version of `d/dx` in the golfed program.
First, preceed the string with `d/dx`. Then, reapeat the following replacements until the string does not change anymore:
```
d/dx sin ... => (cos ...)d/dx ...
d/dx cos ... => (-sin ...)d/dx ...
d/dx -sin ... => (-cos ...)d/dx ...
d/dx -cos ... => (sin ...)d/dx ...
d/dx x => 1
```
Edit: The positive and negative cases are now handled within a single regex. This requires an additional search and replace to drop a double minus and is less elegant, but way shorter.
[Answer]
# Mathematica, 115 bytes
```
ToExpression["d["<>StringReplace[#,{" "->"@"}]<>"]"]//.d[x_[y__]]->d[x][y]d[y]/.{d[sin]->cos,d[cos]->-sin,d[x]->1}&
```
] |
[Question]
[
[Pike](http://pike.lysator.liu.se) is a dynamically typed interpreted scripting language, heavily influenced by C, which typically compiles to C99 with a few `#define`s. (It even has a preprocessor!)
What general tips do you have for golfing in Pike? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pike (e.g. "remove comments" is not an answer).
[Answer]
Array operators.
Pike's arrays have some operators that act ... weird.
* `({1})+({2})` returns `({1,2})` (concatenation)
* `({1,3,8,3,2}) - ({3,1})` returns `({8,2})` (the former argument without elements in the latter argument)
* `({1,3,7,9,11,12}) & ({4,11,8,9,1})` will return: `({1,9,11})` (intersection)
* `({1,2,3}) | ({1,3,5})` will return `({1,2,3,5})` (union)
* `({1,3,5,6}) ^ ({4,5,6,7})` will return `({1,3,4,7})` (symmetric difference)
* `({1,2,3,4,5})/({2,3})` will return `({ ({1}), ({4,5}) })` (split at occurences)
* `({1,2,3,4})/2` will return `({ ({1,2}), ({3,4}) })` (split by length, truncates the excess.)
* `({1,2,3,4,5})/2.0` will return `({ ({1,2}), ({3,4}), ({5}) })` (split by length, keeps the excess.)
* `({1,2,3,4,5})%3` will return `({4,5})` (excess of split by length).
[Answer]
### Abuse `mixed`.
Pike is unfortunately not *exactly* identical to C; for instance the type of a list of strings is `array(string)`, not `char[][]` or even `string[]`.
Any time you need a type declarator and it's not `int`, `mixed` (the "any" type, which gets promoted to the actual type of the RHS at runtime) is liable to be shorter.
A function that takes a list of ints and sorts it, then returns it, for a whopping **41 bytes**:
```
array(int)s(array(int)l){return sort(l);}
```
Or, the type-inferencing version, which is **31 bytes**:
```
mixed s(mixed l){return sort(l);}
```
[My answer](https://codegolf.stackexchange.com/a/74206/46231) to [Manage Trash So](https://codegolf.stackexchange.com/questions/74164) uses a lot of `mixed`.
] |
[Question]
[
## The Scenario
I am building a fancy oscilloscope but I need your help. The oscilloscope can display any number of individual waveforms at the same time (e.g. sine waves) but I don't know how to synchronise the display so it doesn't jump around too much.
## The Challenge
Your program or function will take a series of floating point numbers as its input. The first number will be the width of the oscilloscope screen (there will be different models with larger or smaller screens). The remaining numbers will be the wavelength (not the frequency) of each waveform and will always be less than the width of the display. The amplitude of the waveforms is unimportant, so is not given. The only thing you need to know about the amplitude is that it will never be zero.
Your code must output the distance from the start where all the waveforms are as in-sync as possible for the width of the display. This is assumed to be when there is the smallest horizontal distance possible when each waveform is at 0 degrees (therefore, also with a height of zero). If there are multiple best matches, use the largest one (furthest from the left edge of the display).
An example is displayed below. The vertical lines are where each of the waves are most in-sync with the others. The inputs are `100 [3.14159265358979, 2.71828182845905, 1.41421356237310]` (the image has been scaled up by a factor of 10) and the outputs, in order, are `[40.8407044966673, 40.7742274268858, 41.0121933088199]`. Your code must display at least 5 significant digits unless the decimal representation ends before that. The numbers must be output in the same order as the inputs.
[](https://i.stack.imgur.com/X63gf.png)
**You need to find the greatest multiple of each input number where the maximum distance between them all is as small possible, without going over the upper bound of the screen width.** If there is even a **single** irrational ratio the smallest maximum distance will never be `0` for finite numbers. `[0 ...]` will never be an answer as all of the waveforms will fit at least once on the display before repeating. The maths to calculate the numbers is a lot easier than it appears initially. You can separate the output numbers with any delimiter - it doesn't have to be a space or a comma; use brackets if there is an easier option in your language, as long as the digits are correct to as many places as shown. The same goes for the input; if it's easier to tab separate the numbers, for example, that's OK, as is any other delimiter as long as the numbers are input exactly as shown in the test data.
Test data:
```
In: 10 [3.16227766016838]
Out: [9.48683298050514]
In: 100 [3.16227766016838]
Out: [98.0306074652198]
In: 105 [6, 7]
Out: [84, 84]
In: 1050 [6, 7]
Out: [1050, 1050]
In: 90 [5, 6, 7]
Out: [85, 84, 84]
In: 100 [5, 6, 7]
Out: [90, 90, 91]
In: 200 [5, 6, 7]
Out: [175, 174, 175]
In: 300 [5, 6, 7]
Out: [210, 210, 210]
In: 100 [1.4142135623731, 3.14159265358979, 2.71828182845905]
Out: [41.0121933088199, 40.8407044966673, 40.7742274268858]
In: 100 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [40.8407044966673, 40.7742274268858, 41.0121933088199]
In: 300 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [141.371669411541, 141.350655079871, 141.42135623731]
In: 900 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [383.274303737954, 383.277737812726, 383.25187540311]
In: 1000 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [907.920276887449, 907.906130705323, 907.92510704353]
In: 100 [1.73205080756888, 2, 2.23606797749979, 2.44948974278318, 2.64575131106459]
Out: [24.2487113059643, 24, 24.5967477524977, 24.4948974278318, 23.8117617995813]
In: 1000 [1.73205080756888, 2, 2.23606797749979, 2.44948974278318, 2.64575131106459]
Out: [129.903810567666, 130, 129.691942694988, 129.822956367509, 129.641814242165]
```
As an example, lets take the following test case:
```
In: 200 [5, 6, 7]
Out: [175, 174, 175]
```
At `[5, 6, 7]` (`[1*5, 1*6, 1*7]`) you can show that each number is as close as possible to its neighbours without changing any of the multiples. The minimum distance to contain all the numbers is `2` (`7-5`). But is there a smaller solution less than `200`? At `[35, 36, 35]` (`[7*5, 6*6, 5*7]`) the minimum distance to contain all the numbers is now only `1` (`36-35`). Can we get it smaller? The next smallest distance is at `[210, 210, 210]` (`[42*5, 35*6, 30*7]`) which is optimal at `0` (`210-210`), however, `210` is larger than `200` so is not allowed in this case. The largest solution below or equal to `200` is `[175, 174, 175]` (`[35*5, 29*6, 25*7]`), also with a distance of `1` (`175-174`).
This is code-golf, so shortest solution wins!
[Answer]
## Python (3.5) 240 bytes
A non optimal solution.
It works on all test but that's a really really slow solution since we test each possibility.
## Solution
```
import numpy as n
def f(w,s):
l = len(s)
def g(t,m,k,z):
if t!=[]:
u,*v=t
for i in n.arange(u,w+1,u):
m,k=g(v,m,k,[*z,i])
else:
j=sum(abs(sum(z[1:])/l-i) for i in z[1:])
if j<=m+1e-9 :
return j,z
return m,k
print(g(s,w,0,[0])[1][1:])
```
## Explanation
Importation of numpy module
```
import numpy as n
```
Function definition w:screen length s:"wavelength"
```
def f(w,s):
l = len(s)
```
Définition of the recursive function
with t wavelength, m minimum, k value of the minimum point, z current point
```
def g(t,m,k,z):
```
the recursive test : if t is non empty we go "deeper" in the recursion
```
if t!=[]:
u,*v=t
```
loop on each zeros of the sinus function
```
for i in n.arange(u,w+1,u):
```
call the recursive function
```
m,k=g(v,m,k,[*z,i])
else:
```
the "function" to minimize
```
j=max(z[1:])-min(z[1:])
```
test for the minimum (1e-9 because there is a precision issu)
```
if j<=m+1e-9 :
return j,z
return m,k
print(g(s,w,0,[0])[1][1:])
```
## Results:
```
>>> f(300, [5, 6, 7])
[210, 210, 210]
>>> f(100, [5, 6, 7])
[90, 90, 91]
```
## Previous iteration
In first try i use the distance between points and barycenter
```
j=sum(abs(sum(z[1:])/l-i) for i in z[1:])
```
] |
[Question]
[
My fifth-grade daughter is learning about codes and ciphers. She has reached the point of decoding a ciphertext that has been encoded with the Caesar cipher where the offset is not provided in advance.
Without computers this can be time-consuming, especially for long blocks of text. Luckily, we do have computers, and let's prove it.
Cipher definition and other bounds:
1. Every letter is offset by a fixed (but unknown) number of characters, while retaining the same case. Spaces and punctuation marks are unaffected. Thus, with offset 1, "A"→"B" and "c"→"d" but "," stays as ",".
2. Offset will be a positive integer.
3. English plaintexts only, and no accent marks in the ciphertext or the plaintext.
Your task: Given a ciphertext, determine the most likely correct plaintext via brute force with a dictionary lookup. Thus, generate all 26 possible solutions, then check for the presence of every word in each potential decryption in an English dictionary and select the potential solution with the highest percentage of words that are found there.
The ciphertext should be the only input to your program, and the plaintext should be the only output.
For the sake of this challenge: garbage in, garbage out — given an undecryptable input, your code can return any output. And if multiple solutions tie for % found in the dictionary, you can return any of them.
Sample inputs:
```
"Fsyvoxmo kxn mywwsddoo woodsxqc."
"Gwbqs Sadwfs Ghfwysg Poqy, Ghof Kofg vog pssb bchvwbu pih o pzif ct wbobs waousg kwhv ob slqszzsbh gcibrhfoqy."
"Pda pnqpd sehh oap ukq bnaa. Xqp jkp qjpeh ep eo bejeodaz sepd ukq."
```
Your system should accept any string as input and attempt to decode it, and must be able to decode these examples correctly. I completed an ungolfed solution in Mathematica in about 700 characters. Standard rules apply; no hard-coded solutions, etc. Smallest number of bytes wins.
[Answer]
## Python 2, ~~384~~ 319
```
a=raw_input()
e=lambda v,b:(ord(v)+b-65-32*(v>"``"))%26+65+32*(v>"``")
c=lambda b:''.join(chr(e(f,b))if f.isalpha() else f for f in a)
p=map(c,range(26))
w=map(str.strip,open('w'))
l=[0]*26
for k,i in enumerate(p):
for j in i.split():
if j.lower() in w:l[k]+=1
m=[i for i,j in enumerate(l)if j==max(l)][0]
print p[m]
```
I named my wordlist `w`, which is a newline-separated list of lowercase words.
[Answer]
# Pyth, ~~39~~ ~~34~~ 31 bytes
```
h.Msm}@Grd0'\wcZd.u.r.rNrG1G25z
```
Solves all test cases. Expects the newline-separated lowercase word list to be in the file `w`.
You can also [try it online](https://pyth.herokuapp.com/?code=h.Msm%7Dsf%7DTGrd0.zcZd.u.r.rNrG1G25z&input=Fsyvoxmo+kxn+mywwsddoo+woodsxqc.%0Aand%0Abar%0Acommittee%0Afoo%0Aipsum%0Alorem%0Ameetings%0Aviolence). The online version expects input on the first line and the dictionary words in lowercase on the next lines. Note that trying to send a large dictionary to the server may not be a good idea.
The algorithm tries to maximize the amount of correct words in the text, so if there are impossible-to-decipher words they are just ignored. In case of completely impossible input just outputs it back.
### Explanation
* `z` is preinitialized to input.
* `.u ... 25z` repeats the following process 25 times, starting with the input, and returns all 26 results:
+ `.rNrG1` shifts uppercase letters (`rG1`) by one
+ `.r.rNrG1G` shifts all letters by one
* `.M` finds the ones from said results that produce the maximum result for:
+ `cZd` splits the current string by spaces
+ `sm` counts the occurrences where:
- `rd0` lowercases the word
- `@G` removes non-alphabetic letters
- `} ... '\w` checks whether the word is in the file `w`
] |
[Question]
[
You work for the military as a coder and are responsible for writing software to control missiles. Your task is to write a program or function that will output a code sequence (any length ASCII string) to launch a missile. The program should be based on a loop taking the code sequence from memory and output it in a particular order. Then the code is sent to the missile controller, which launches the missile.
However, you work as one of our spies. We believe that writing the sequence in reverse order will cause the missile to explode in the silo as a form of sabotage! We are able to change by some way (the method is top secret and it is not important how we can do it) one byte of code in the missile controller software. You need to write such a program that changing one byte during the loop will change the loop so that the text will be typed in reverse order.
### The task
Write a program or function in any language of your choice that will use a loop to return ASCII sequence. The sequence can be stored in the memory or given from `stdin` or equivalent, function arguments, being a string or array of any length (>0, <=255 characters).
Changing one character or byte in the loop, in any iteration, should reverse the loop direction, making characters that have already been returned show again, from last to first.
For example, if the input text (the missile code sequence) would be `abcdefgh` and the loop switch begins in the 5th iteration, the result should be `abcdedcba`. We believe this would be enough to destroy the missiles.
However, we know that they are aware of our new weapon. We are not able to switch from or to any of the following characters, in your code:
* `+` (plus sign, addition)
* `-` (minus sign, subtraction, or unary negative operator)
* `>` and `<` (greater than, less than), we also expect this won't work for `<<` and `>>` operators (bit shift left/right), however you can change commands doing bit shift, if there are any in your language (eg. change `shr` to `shl`).
You may not change a whitespace character to a non-whitespace character (eg. you cannot change `[space]or` to `xor`).
You may not assign any constants or variables to values or codes so you will bypass the said characters (e.g. you cannot say `p = 1; n = -1;` and change `p` to `n` in such a line `i = i + p`).
If necessary, after the character switch, you are allowed to leave the loop and output the rest of the string in any way you like.
You are free to choose if one and only one character/byte will be switched or all of the same value. For example, you may switch all occurrences of `*` to `/`.
Any `GOTO`, `DJNZ` and equivalents also do count as loops.
The program must return no errors, so the enemy will never realize what has happened. The program should return the whole string if no switch would be made.
This is a codegolf, so shortest answer in bytes wins.
To make program simpler, you may insert in your code a conditional statement to switch program flow in particular iteration. This must simulate the line to be changed. If so, you do not have to count the bytes of the conditional in your code. However, you cannot modify anything in this part of code and use it for any other purposes.
### Example
The example below was written in PHP. Note, **it is invalid**, because it changes `+` sign to `-` sign, which is not allowed, however I hope it would be clear to understand what I mean.
```
function f($s){
$result = ''; // initialize result
$array = str_split($s); // convert string to array
$char = 0; // loop start
$increase = 1; // loop direction
while($char>=0 && $char < strlen($s)){ // start loop
$result = $result . $array[$char]; // add next character for the output
// The conditional statements below simulate character switch
// The number 5 means it will happen in the 5th iteration
// The lines in if... and else... statements must have exactly the same length
if(strlen($result) < 5){ // for iteration 5 and lower...
$char = $char + $increase; // count only this line in the block
}
else{
$char = $char - $increase;
}
// end of the block
} // end while loop
return $result; // end of program
}
```
The usage of the function is to call it `echo f("abcdefghijkl");` which returns `abcdedcba`. Golfed a bit (removed some whitespaces and the conditional block):
```
function f($s){$result='';$array=str_split($s);$char=0;$increase=1;while($char>=0 && $char<strlen($s)){
$result=$result.$array[$char];
$char=$char+$increase; // this line instead of the block
}
return$result;}
```
(175 bytes)
Note, that the golfed version, without the conditional block (or `5` is replaced with `13` or more), returns `abcdefghijkl`.
*This is my very first task here. Let me know if I did something wrong.*
[Answer]
## Python ~~76~~ 63 Bytes
This anon-function basically prints it's input as is.
```
lambda x:`[x[(~~e,e)[e<len(x)/2]]for e in range(len(x))]`[2::5]
```
Outputs - `z("123456") -> 123456`
But by changing the `~` to whitespace , it prints the second part of the string in reverse.
```
lambda x:`[x[( ~e,e)[e<len(x)/2]]for e in range(len(x))]`[2::5]
^
```
Outputs - `z("123456") -> 123321`
] |
[Question]
[
# Introduction
You may remember *sudoku*, where there can only be one of each number in each row, column and block of nine.
The general idea is that if the array contains but one element, you can submit that as a deterministic solution. If there are already filtered arrays (by rows, columns and 3×3 blocks) the remainder can still be deterministic.
Where
* a=[1,2];
* b=[1,3];
* c=[2,3];
* d=[1,2,3,4]
d should be reduced to [4] as it apparently cannot be anything else.
# Challenge
Provide a sniplet that compares *n* arrays.
For every X, if only X numbers appear at least once in a set of X arrays, then all those X numbers should be removed from each array not in the set.
The elements are *integer numbers* ranging *[1, n]*.
# Winning criterion
Lowest character count.
## "I'm too young to die" version
9 arrays at most, 9 elements at most.
# Test Cases
>
> [1,2]; [2,3]; [1,3]; [1,2,3,4]
>
> [1,2,3]; [2,3,4]; [1,5,6]; [2,3]; [1,4]; [1,2,3,4,6]
>
>
> ## Test outputs
>
>
> [1,2]; [2,3]; [1,3]; **[4]**
>
> [1,2,3]; [2,3,4]; **[5]**; [2,3]; [1,4]; **[6]**
>
>
>
[Answer]
# [Pyth](https://github.com/isaacg1/pyth): ~~37~~ ~~29~~ 28 bytes
```
um?d|-lHl{sHsmg{kdH-dsHGtyQQ
```
Input is a list of lists like `[[1,2], [2,3], [1,3], [1,2,3,4]]`. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/)
## Explanation:
```
um?d|-lHl{sHsmg{kdH-dsHGtyQQ
u Q G = input array
u tyQQ For each H in powerset(input):
m G G = [ ... for d in G]
?d -dsH [d if ... else d-sum(H) for d in G]
-lHl{sH len(H)-len(set(sum(H)))!=0
| or
smg{kdH sum(d is subset of k for k in H)>0
```
[Answer]
# C# - 231 characters
```
static int[][] P(int[][]a){var m=a.GetUpperBound(0)+1;var j=0;for(var i=0;i<m;i++){var u=new List<int>();for(j=0;j<=i;j++)u=u.Union(a[j]).ToList();if(u.Count()==m)for(j=0;j<m;j++)if(i!=j)a[i]=a[i].Except(a[j]).ToArray();}return a;}
```
Ungolfed and harness
```
using System.Collections.Generic;
using System.Linq;
namespace ArrayCombCompar
{
class Program
{
static void Main(string[] args)
{
var testArray1 = new int[][] {
new int[] {1,2},
new int[] {2,3},
new int[] {1,3},
new int[] {1,2,3,4}
};
var testArray2 = new int[][] {
new int[] {1,2,3},
new int[] {2,3,4},
new int[] {1,5,6},
new int[] {2,3},
new int[] {1,4},
new int[] {1,2,3,4,6}
};
var result1 = P(testArray1);
var result2 = P(testArray2);
} // Put breakpoint here to see results
static int[][] P(int[][]a)
{
var m = a.GetUpperBound(0) + 1;
var j = 0;
for (var i = 0; i < m; i++)
{
var u = new List<int>();
for (j = 0; j <= i; j++)
u = u.Union(a[j]).ToList();
if (u.Count() == m)
for (j = 0; j < m; j++)
if (i != j) a[i] = a[i].Except(a[j]).ToArray();
}
return a;
}
}
}
```
] |
[Question]
[
tl;dr [True] Billy got a Stack Overflow pen from Tim Post. Billy was stupid enough to *use* the pen, knowing that he was not worthy. Billy's friend took the pen apart, so Billy put the pen in a drawer at his house, hoping he would eventually fix it. A year later, Billy can only find half of the pen's pieces, and not the main part that has the words "Stack Overflow" on it. [EndTrue] [Fake] Billy looked at his home security camera and saw that a burglar had come in his house while he was sleeping and taken his pen. Billy vows revenge! Why can't he just ask for another Stack Overflow pen? Because this is the last one in existence. [EndFake] Err, technically this whole thing is fake because my name isn't Billy.
Help Billy find the scumbag that stole his pen so he can ultimately deal mortal damage to him and get the other half of his pen back! You will use a World object that has the following methods:
```
objectsAtPosition(lon: Number, lat: Number)
```
This returns an array of strings. One string for every object at the specified longitude (lon) and latitude (lat). The possible strings are:
`SUP` - Super User Pen
`SFP` - Server Fault Pen
`SOP` - Stack Overflow Pen
`BD` - Bad Dog
`GD` - Good Dog
`G` - Giygas
```
destroyObjectAt(lon: Number, lat: Number, i)
```
This destroys the object at the specified longitude, latitude, and index. For example, if at a specified longitude (lon) and latitude (lat) there are two or more objects, destroy the nth object in the array depending on what the index (i) is. You will destroy every Giygas and every Bad Dog.
```
giveTreatToObjectAt(lon: Number, lat: Number, i)
```
This gives a treat to the object at the specified longitude (lon), latitude (lat), and index. For example, if at a specified longitude (lon) and latitude (lat) there are two or more objects, give a treat to the nth object in the array depending on what the index (i) is. You will give all good dogs a treat.
```
collectObjectAt(lon: Number, lat: Number, i)
```
This collects the object at the specified longitude (lon) and latitude (lat), and index. For example, if at a specified longitude (lon) and latitude (lat) there are two or more objects, collect the nth object in the array depending on what the index (i) is. You will collect Billy's Stack Overflow pen and nothing else or else you die. Keep in mind that there is only *Billy's* Stack Overflow pen left in existence.
You will index through every longitude and latitude value (look below) and treat every object found as they should be treated.
Longitude and latitude rage from 0-10. Iterate incrementing by 1. Treat lon and lat as integers if you'd like. Use whatever-based indexing the language you're coding this in uses. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytes in code wins.
Every item is an array. Here's an example of what the Array would be like. It's a 2D Array, 10x10. Longitude brings you right and latitude brings you down. So longitude with 5 and latitude with 4 would select this:
```
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['*Example*'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
['SO','SU'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example'],['Example']
```
or
```
0→[item]1→[item]2→[item]3→[item]4→[item]5→[item]0↓[item][item][item][item]
[item] [item] [item] [item] [item] [item]1↓[item][item][item][item]
[item] [item] [item] [item] [item] [item]2↓[item][item][item][item]
[item] [item] [item] [item] [item] [item]3↓[item][item][item][item]
[item] [item] [item] [item] [item][*item*]←4[item][item][item][item]
[item] [item] [item] [item] [item] [item] [item][item][item][item]
[item] [item] [item] [item] [item] [item] [item][item][item][item]
[item] [item] [item] [item] [item] [item] [item][item][item][item]
[item] [item] [item] [item] [item] [item] [item][item][item][item]
[item] [item] [item] [item] [item] [item] [item][item][item][item]
```
In case you don't see it, it will select the item "*Example*" in the first one and the item "*item*" in the second one. I'm not sure how the human brain works, use your browser's search on page feature if you still don't see it.
PS:
If you don't know what a Giygas is, just know that you have to destroy it... or pray for your life by it (which ultimately destroys it anyway).
[Answer]
# C# - 272 bytes
I couldn't find too many tricks to do here outside of some for-loop shenanigans. I was hoping to use some Linq, but the index parts of the API made it difficult to make that work concisely.
```
class A{static void Main(string[] a){
for(int x=101,y,c;x-->0;)
for(y=101;y-->(c=0);)
foreach(string s in World.objectAtPosition(x,y)){
if(s=="SOP")World.collectObjectAt(x,y,c);
if(s=="BD"||s=="G")World.destroyObjectAt(x,y,c);
if(s=="GD")World.giveTreatToObjectAt(x,y,c);
c++;}}}
```
Here's my test code:
```
using System.Linq;
class A
{
static void Main(string[] a)
{
for (int d = 0; d < 100; d++)
{
World.populate();
for(int x=101,y,c;x-->0;)
for(y=101;y-->(c=0);)
foreach(string s in World.objectAtPosition(x,y))
{
if(s=="SOP")World.collectObjectAt(x,y,c);
if(s=="BD"||s=="G")World.destroyObjectAt(x,y,c);
if(s=="GD")World.giveTreatToObjectAt(x,y,c);
c++;
}
World.verify();
}
}
static class World
{
private static System.Collections.Generic.List<Item>[,] m_Map =
new System.Collections.Generic.List<Item>[maxRange+1, maxRange+1];
private static System.Random random = new System.Random();
private const int maxRange = 100;
private const int dogCount = 20;
private class Item
{
public string id;
public bool handled;
public Item(string id)
{
this.id = id;
this.handled = false;
}
}
public static void populate()
{
for (int lat = 0; lat <= maxRange; lat++)
for (int lon = 0; lon <= maxRange; lon++)
m_Map[lat, lon] = new System.Collections.Generic.List<Item>();
addRandom("SUP");
addRandom("SFP");
addRandom("SOP");
addRandom("G");
for (int c = 0; c < dogCount; c++)
{
addRandom("BD");
addRandom("GD");
}
}
public static void verify()
{
for (int lat = 0; lat <= maxRange; lat++)
{
for (int lon = 0; lon <= maxRange; lon++)
{
for (int index = 0; index < m_Map[lat, lon].Count; index++)
{
Item item = m_Map[lat, lon][index];
if (!item.handled && item.id != "SUP" && item.id != "SFP")
{
throw new System.Exception(string.Format("Didn't handle '{0}' at '{1},{2}:{3}'.",
item.id, lat, lon, index));
}
}
}
}
}
private static int randomCoord()
{
return random.Next(maxRange + 1);
}
private static void addRandom(string item)
{
int lat = randomCoord();
int lon = randomCoord();
m_Map[lat, lon].Add(new Item(item));
}
public static string[] objectAtPosition(int lat, int lon)
{
return m_Map[lat, lon].Select(item => item.id).ToArray();
}
public static void destroyObjectAt(int lat, int lon, int index)
{
Item item = m_Map[lat, lon][index];
if (item.id == "G" || item.id == "BD")
item.handled = true;
else
throw new System.InvalidOperationException(string.Format("Tried to destroy '{0}' at '{1},{2}-{3}'",
item.id, lat, lon, index));
}
public static void giveTreatToObjectAt(int lat, int lon, int index)
{
Item item = m_Map[lat, lon][index];
if (item.id == "GD")
item.handled = true;
else
throw new System.InvalidOperationException(string.Format("Tried to giveTreatTo '{0}' at '{1},{2}-{3}'",
item.id, lat, lon, index));
}
public static void collectObjectAt(int lat, int lon, int index)
{
Item item = m_Map[lat, lon][index];
if (item.id == "SOP")
item.handled = true;
else
throw new System.InvalidOperationException(string.Format("Tried to collect '{0}' at '{1},{2}-{3}'. You die.",
item.id, lat, lon, index));
}
}
}
```
] |
[Question]
[
Your challenge is, given a series of notes, print the fingerings that minimize the amount of movements you need to make (explained below).
My not standard way of transforming fingerings to text:
The `|` line separates the left and right hand. Use `1` for the index finger, `2` for the middle finger and `3` for the ring finger. Use `a-d` for the right hand to represent the side keys played by the pinkies (and just `a` and `b` for the left hand).
An example for low A#/Bb:

which would be written as `123d|123b`.
The side keys, which are hit with the part of your hand between the thumb and index finger, are labeled as `e`, `f`, and `g`.
In addition, there is a little key between the right hand's `1` and `2` used for playing `Bb`. This is called the `i` key.
The octave key is labeled `o`
These are the fingerings (note that `b` means flat, not the note `B` which is uppercase):
```
A#3 or Bb3: 123d|123b
B3 or Cb4: 123c|123b
B#3 or C4: 123|123b
C#4 or Db4: 123b|123b
D4: 123|123
D#4 or Eb4: 123|123a
E4 or Fb4: 123|12
E#4 or F4: 123|1
F#4 or Gb4: 123|2
G4: 123| // Note that the | is still necessary
G#4 or Ab4: 123a|
A4: 12|
A#4 or Bb4: 12|g OR 1i| OR 1|1 OR 1|2
B4 or Cb5: 1|
B#4 or C5: 2| OR 1|f
C#5 or Db5: | OR o3| // No fingers down for first fingering
D5: o123|123
/* All fingerings from D5 - B#5/C6 are the same as the lower octave
but with the octave key (prefixed with o) */
C#6 or Db6: o|
D6: of|
D#6 or Eb6: oef|
E6 or Fb6: oef|e
E#6 or F6: oefg|
```
**Input**:
A series of notes separated by semicolons.
**Output**:
A series of fingerings separated by semicolons.
If there is more than one way to finger a certain note, the program must chose the fingering that minimizes *distance* from its neighbors. If it is the only note or there is a tie, you may output any fingering.
A fingering's *distance* from another is how many fingers you would have to lift/press to change the note.
Example: `12| --> 1|` has a distance of 1 because you have to lift finger 2.
Example: `12|g --> 12|` has a distance of 1 because you only have to lift one side key.
Test cases:
```
C#5;D5;C#5 --> o3|;o123|123;o3|
```
**Bonus**: -100 if your program takes an audio file (probably midi) as input and outputs the fingering corresponding to the notes played.
[Answer]
## Python 3, ~~528~~ 525 bytes (ouch!)
Not the prettiest code in the world, but I think it works. Calculates the shortest overall distance by trying all possible fingering combinations, so also not the most efficient.
```
from itertools import*
def f(x,y):a,b=x.split('|');c,d=y.split('|');return len(set(a)^set(c))+len(set(b)^set(d))
print(";".join(min(product(*["zd|zb zc|zb z|zb zb|zb z|z z|za z|12 z|1 z|2 z| za| 12| 12|g&1i|&1|1&1|2 1| 2|&1|f |&o3| oz|z oz|za oz|12 oz|1 oz|2 oz| oza| o12| o12|g&o1i|&o1|1&o1|2 o1| o2|&o1|f o| of| oef| oef|e oefg|".replace('z','123').split()["C D EF G A B".find(n[0])+" #".find(n[1:-1])+12*int(n[-1])-46].split('&') for n in input().split(';')]),key=lambda x:sum(f(x[i],x[i+1]) for i in range(len(x)-1)))))
```
Not many tricks. Saved a bit by a string-replace on "123". Simplified distance calculation by doing each half separately. Note name to pitch calculation is fairly tight but should be able to golf the rest down.
] |
[Question]
[
In investing, internal rate of return (IRR), the continuously compounded rate of return economically equivalent to a specified series of cashflows, is often a valuable concept.
Your challenge is to demonstrate how to compute IRR in the language of your choice in as few bytes as possible, subject to the following conditions:
1. Your code should accept arbitrary cashflows, subject only to the condition that the initial cashflow is negative.
2. You can assume that the cashflow has already been assigned to a variable f (use some other variable name if 'f' is a command name in your language).
3. Assume cashflow is specified as a series of (date, datum) pairs, in whatever format is most convenient for your language. This challenge is about the IRR computation, not parsing the input.
4. All functions built into your language are allowed except IRR() or the equivalent, if your language has it, because that's not interesting.
5. Output should be a real number (thus, 0.14, not "14%").
The solution requires numerical root-finding, and different methods and starting conditions will find slightly different answers. For the purposes of the contest, if you're within 0.001 of the answer reached by Excel's XIRR function, you're close enough.
Example 1:
```
f={{{2001, 1, 1}, -1}, {{2002, 1, 1}, .3}, {{2005, 1, 1}, .4}, {{2005, 1, 10}, .5}};
0.0584316
```
Example 2:
```
f = {{{2011, 1, 1}, -1}, {{2012, 2, 1}, -.3}, {{2015, 3, 1}, .4}, {{2015,3,15},.01}, {{2015, 4, 10}, .8}};
-0.2455921
```
Example 3:
```
f = {{{2011, 1, 1}, -1}, {{2012, 2, 1}, 3.3}, {{2015, 3, 1}, 5.4}, {{2015,3,15}, 6.01}, {{2015, 4, 10}, 17.8}};
2.4823336
```
More information available at <http://en.wikipedia.org/wiki/Internal_rate_of_return>
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 149
```
load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(f[1][1]+sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,2,length(f)),r,.1);
```
This code has a bug where some payments might be off by 1/24 day (1 hour). This bug happens if your local time zone moves in or out of daylight-saving time. To fix this bug, add `,0` (2 characters) after `d[2]`.
First set f to a list of lists in the form `[[flow, year, month, day], ...]`. Then paste this code at Maxima's prompt. The answer comes in the form `[[r = float]]`. If you want the float by itself, use `part(%[1][1],2);`
Example 1:
```
(%i150) f : [[-1, 2001, 1, 1], [.3, 2002, 1, 1], [.4, 2005, 1, 1],
[.5, 2005, 1, 10]]$
(%i151) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o153) [[r = .058394251994029284]]
```
Example 2:
```
(%i154) f : [[-1, 2011, 1, 1], [-.3, 2012, 2, 1], [.4, 2015, 3, 1],
[.01, 2015, 3, 15], [.8, 2015, 4, 10]]$
(%i155) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o157) [[r = - .017843072768412977]]
```
Example 3:
```
(%i158) f : [[-1, 2011, 1, 1], [3.3, 2012, 2, 1], [5.4, 2015, 3, 1],
[6.01, 2015, 3, 15], [17.8, 2015, 4, 10]]$
(%i159) load(mnewton)$y(d):=?encode\-universal\-time(0,0,0,d[4],d[3],d[2])/31536000$mnewton(sum(f[i][1]*(1+r)^(y(f[1])-y(f[i])),i,1,length(f)),r,.1);
(%o161) [[r = 2.4823712861605407]]
```
My time zone is America/New\_York. Because of the daylight-saving bug, other time zones might give slightly different answers.
## Ungolfed
```
load(mnewton)$
/*
Returns the number of 365-day periods since the epoch, when called as
year([year, month, day]).
*/
year(date):=
?encode\-universal\-time(
/* s, m, h, day, month, year, time zone */
0, 0, 0, date[3], date[2], date[1], 0) /
31536000 /* seconds in 365 days */$
/*
Finds a numerical approximation for the internal rate of return for a
list of cash flows on a list of dates. The dates must be a list of
lists in the form
[[year, month, day], [year, month, day], ...]
The first date in the list is the present date for calculating the
present value of each cash flow. Returns the rate for each 365-day
period.
*/
xirr(flows, dates):=
part(
/* Solve for rate where net present value = 0. */
mnewton(
sum(
/* present value of flows[i] on dates[i] */
flows[i] * (1 + rate)^(year(dates[1]) - year(dates[i])),
i, 1, length(flows)),
rate /* solve for rate */,
.1 /* initial guess */)
[1][1], /* extract 1st solution, 1st variable */
2 /* value in variable = value */)$
```
Here `xirr(flows, dates)` is a function, but the golfed version only has an expression that looks at `f`. The golfed version also removes the `part` call and adds the daylight-saving bug.
] |
[Question]
[
Given an `m`x`m` chess board, find a minimum number of pieces of the given kind and place them on a chess board in such a way that all squares are either occupied or attacked by at least one piece.
## Input
The input consists of two parameters: `m`, the number of squares on each side; and a letter which indicates which piece to use, according to the following key: **K**ing, **Q**ueen, **R**ook, **B**ishop, k**N**ight. For example, an input of `8 B` means that you have to find a solution for an `8`x`8` board with bishops.
The input will always consist of a positive integer and a valid letter. You may choose to implement a program which takes input either as command-line arguments or separated by a space on stdin; or to implement a named function/verb which takes two parameters.
## Output
The output should be a chess board in the following format:
```
........
.....Q..
..Q.....
....Q...
......Q.
...Q....
........
........
```
This is a solution for the input `8 Q`. Each line is separated by a newline.
Note that every valid input has a solution.
## Other points
[Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061) are not acceptable. In particular, since your program must handle any input, it is not sufficient to hard-code the answer for small inputs.
The particular case of this problem where Queens are used has been the subject of some investigation, and the number of Queens required for square boards is in the Online Encyclopaedia of Integer Sequences as [A075324](http://oeis.org/A075324). However, that probably doesn't help you for inputs larger than `18 Q`, and doesn't give you the layout for smaller cases.
As a performance constraint to prevent pure brute-force approaches, the code should output a result for `18 Q` in a reasonable time (approximately 6 hours).
[Answer]
This is a fun problem, and I'm sad that it has no solution, so I made my own!
Requires arguments in the form M P where M is the size of the board and P is the code for the piece
**Java - S.java - 1359 Characters**
```
public class S{int s;String p;String e=".";String b;String t;int c;public static void main(String[]args){new S(args);}S(String[] a){s=Integer.parseInt(a[0]);p=a[1];b="";int i;if(p.equals("P")){String r="P";for(i=1;i<s;i++)r+=e;r+="\n";for(i=0;i<s;i+=3){a(r);f(p);a(r);}m(0);}if(p.equals("B")){for(i=0;i<s-1;i++){if(s/2==i)f(p);f(e);}}if(p.equals("N")){for(i=0;i<s;i+=5){f(e);f(e);f("N");f(e);f(e);}m(0);if(s%5==2|s%5==1){m(1);f(p);}}if(p.equals("R")){f(p);for(i=1;i<s;i++)f(e);}if(p.equals("K")){String k="";for(i=0;i<s;i+=3)k+=".K.";k=k.substring(0,s-1);k+=(s%3==0)?e:"K";k+="\n";for(i=0;i<s;i+=3){f(e);a(k);f(e);}m(1);if(s%3==0)f(e);else a(k);}if(p.equals("Q"))for(i=0;i<s*s;i++){try{q(i,0,new String[s][s]);}catch(Exception e){}b=t;}System.out.println(b);}void q(int d,int g,String[][] o) throws Exception{int u=0;int i;if(g==s*s|u>c){if(u<=c){c=u;t="";for(i=0;i<s;i++){for(int j=0;j<s;j++)t+=o[i][j];t+="\n";}}throw new Exception();}int r=(d/s)%s;int c=d%s;if(o[c][r]==null){for(i=0;i<s;i++){try{o[c-r+i][i]=(o[c-r+i][i]==null)?e:o[c-r+i][i];}catch(Exception e){}try{o[i][r+c-i]=(o[i][r+c-i]==null)?e:o[i][r+c-i];}catch(Exception e){}o[i][r]=(o[i][r]==null)?e:o[i][r];o[c][i]=(o[c][i]==null)?e:o[c][i];}o[c][r]="Q";u++;}q(d+1,g+1,o);}void m(int d){b=b.substring(0,(s+1)*(s-d));}void a(String d){b+=d;}void f(String f){for(int i=0;i<s;i++){b+=f;}b+="\n";}}
```
(Pawns are attacking from left to right)
I couldn't find any proof of the minimum of any domination problem, but my Queen's solver at 8 solves with 5 queens and the others don't seem to be doing too badly (18 queens at 25x25). Someone will have to beat my other solutions to disprove them as minimums. That probably won't be hard!
Here is my de-golfed solution, for anyone interested. It's a bit of a mess... My first thought for doing the Queen's solver was to use backtracking, but I got lazy.
**Java - SimpleChessSolver.java - 3496 Characters**
(There was once a version which had a whole bunch of different classes, to represent the board, squares, pieces... But it quickly got out of control and was renamed ComplicatedChessSolver.java)
```
public class SimpleChessSolver {
int size;
String piece;
String period = ".";
String board;
String bestBoard;
int bestCount;
public static void main(String[] args) {
new SimpleChessSolver(args);
}
SimpleChessSolver(String[] args){
size = Integer.parseInt(args[0]);
piece = args[1];
board = "";
int index;
if (piece.equals("P")){
String periods = "P";
for (index = 1; index < size; index++){
periods += period;
}
periods += "\n";
for (index = 0; index < size; index += 3){
addString(periods);
fillRow(piece);
addString(periods);
}
trimToSize(0);
}
if (piece.equals("B")){
for (index = 0; index < size - 1; index++){
if (size/2 == index){
fillRow(piece);
}
fillRow(period);
}
}
if (piece.equals("N")){
for (index = 0; index < size; index += 5){
fillRow(period);
fillRow(period);
fillRow("N");
fillRow(period);
fillRow(period);
}
trimToSize(0);
if (size%5 == 2 || size%5 == 1){
trimToSize(1);
fillRow(piece);
}
}
if (piece.equals("R")){
fillRow(piece);
for (index = 1; index < size; index++){
fillRow(period);
}
}
if (piece.equals("K")){
String kings = "";
for (index = 0; index < size; index += 3){
kings += ".K.";
}
kings = kings.substring(0, size - 1);
kings += (size%3 == 0) ? period : "K";
kings += "\n";
for (index = 0; index < size; index += 3){
fillRow(period);
addString(kings);
fillRow(period);
}
trimToSize(1);
if (size%3 == 0) {
fillRow(period);
}
else {
addString(kings);
}
}
if (piece.equals("Q")){
for (index = 0; index < size*size; index++){
System.out.println(bestBoard);
System.out.println("BlankLine\n");
try {
queenSolve(index, 0, new String[size][size]);
}
catch (Exception e) {}
}
System.out.println("Final Answer");
board = bestBoard;
}
System.out.println(board);
}
void queenSolve(int start, int depth, String[][] board2D) throws Exception {
int currentCount = 0;
int index;
if (depth == size*size || currentCount > bestCount){
if (currentCount <= bestCount){
bestCount = currentCount;
bestBoard = "";
for (index = 0; index < size; index++){
for (int jdex = 0; jdex < size; jdex++){
bestBoard += board2D[index][jdex];
}
bestBoard += "\n";
}
}
throw new Exception();
}
int row = (start / size) % size;
int col = start % size;
if (board2D[col][row] == null){
for (index = 0; index < size; index++){
try{
board2D[col - row + index][index] = (board2D[col - row + index][index] == null) ? period : board2D[col - row + index][index];
} catch (ArrayIndexOutOfBoundsException e) {}
try{
board2D[index][row + col - index] = (board2D[index][row + col - index] == null) ? period : board2D[index][row + col - index];
} catch (ArrayIndexOutOfBoundsException e) {}
board2D[index][row] = (board2D[index][row] == null) ? period : board2D[index][row];
board2D[col][index] = (board2D[col][index] == null) ? period : board2D[col][index];
}
board2D[col][row] = "Q";
currentCount++;
}
queenSolve(start + 1, depth + 1, board2D);
}
void trimToSize(int additionalTrim){
board = board.substring(0, (size + 1) * (size - additionalTrim));
}
void addString(String toAdd){
board += toAdd;
}
void fillRow(String filler){
for (int index = 0; index < size; index++){
board += filler;
}
board += "\n";
}
}
```
**How it works**
Other than the queens, the other solutions are very simple. The Knights, Rooks, and Bishops can all be solved by putting a straight line in the correct place. Rooks cover their whole rank, so it works to just put a line anywhere on the board. A row of knights will cover four parallel rows, two in each direction. If there is a row of bishops on approximately (+/- 0.5) the middle row, they can cover every square. A row of pawns covers the parallel rows to their immediate left and right except for the bottom square, so I put a pawn on that square to occupy it. Kings can only cover the 3x3 squares around them, so I just stick Kings such that their squares don't overlap, with overlapping kings added if I need to fill out a size%3 != 0 board.
Queens is a little trickier. My algorithm, which may not be the best, iterates over the board, so that it starts on every square, then puts a queen there. It fills in periods for every square that queen covers, then walks along the board until it finds a square not already occupied by a Q or a period. As I said, this produces the current minimum for a 8x8 board (5 Queens) and I couldn't find a reference for any other board size.
] |
[Question]
[
This challenge challenges you to write a function that will take as its argument an array that specifies the types of input, an optional prompt, and a verification key; inputs and validates the values; and returns them.
Input types:
>
> b - Boolean values.
>
> c - Characters.
>
> i - Integer values, rejects floating point values.
>
> f - Floating point values, accepts integers.
>
> n - Strings that only contain the characters a-z and A-Z, suitable for names.
>
> s - Strings with any character type.
>
> d - Dates in the form of dd/mm/yyyy, leap years and dates previous to 01/01/1900 can be rejected.
>
>
>
Examples:
>
> b - Takes input as specified values, validates it, and returns "0" (false) or "1" (true).
>
> c - Accepts any character.
>
> i - Accepts any integer or number that, when the decimal is dropped, the resulting number is identical to the original number, such as 3 or 90.0. Rejects all other floating point values, such as 4.2 and 5.009.
>
> f - Accepts any floating point or integer values. Floating point values include any number with a decimal value between .1 and .9. Numbers with .0 can count as a integer.
>
> n - Accepts any string that contains only the characters a-z and A-Z. This input will accept "Name," but reject "Name1" and "My name."
>
> s - Accepts any type of string.
>
> d - Accepts any valid date of the form dd/mm/yyyy, such as 03/01/2014.
>
>
>
The function will take an array, vector, or other variable length type as an argument. Each element of the array will contain sub-elements of the input type request input type, an optional prompt, and for the input types `s`, `i`, and `f`, an optional validation format. Input type `b` must include a validation format in the form of "True/False". The array must be formatted as {type, prompt, validation}.
If no prompt is given, the function will use "> " as a prompt.
If a validation format for input type `s` is given, it can contain any character that must be matched exactly and a request for any number of characters matching certain criterion. To request the string to have a specific number alphabetic characters (a-z and A-Z), use the format `%(number of characters)(c)`, as in `%6c`, which requests 6 characters. To request that the input be a certain number of single-digit integers, use `%(number of digits)(i)`, as in `%6i`, which requests six digits. Any other character given must be matched directly, where `i` equals `i` and `-` equals `-`". Use `%%` to signify `%` because `%` alone is used to represent a command, as above. These rules can be combined, where `i%6c-%%%2ixx` represents an input matching `i` + 6 characters + `-%` + 2 digits + `xx`, where `ifizlwi-%62xx` is a valid example.
Input validation formats for types `i` and `f` must be the in the form `lowest/highest`, where `lowest` is the lowest acceptable number and `highest` is the highest acceptable number. Example: `6/50` would require a number between 6 and 50 (inclusive) to be input.
The function will return an array of strings that can be parsed by your program.
Return formatting:
>
> b - Returns "0" (false) or "1" (true).
>
> c, i, f, n, s, l, and d - returns input formatted as string.
>
>
>
Example call:
```
String s[][] = {{"n", "First name: "}
{"n", "Last name: "}
{"i", "Age: "}
{"d", "Date (dd/mm/yyyy): "}
{"s", "ISBN: ", "%1i-%6i-%2i-%1i"}
{"b", "Check out: ", "Yes/No"}};
String[] response = input(s);
```
The Boolean input will give the options as part of the prompt by displaying the input request as "(True/False)" after the prompt. The above example will display as
>
> "Check out: (Yes/No)"
>
>
>
The function must continue requesting input until a valid input for each request is given.
No internet resources are allowed.
Any input-functions in any language that input and validate any type must not be used. E.g. if a language contains a function to input and validate an integer besides the traditional input function (`System.in`, `cin>>`, `input()`, etc.), that function must not be used. You must do the validation yourself.
No trolling-style answers allowed. There are plenty of trolling questions for you to have fun with.
Shortest code [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") that correctly inputs each of the specified types wins.
[Answer]
# C++, 4011 characters
This is the function:
```
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<string>i(int a,const string s[][3]){vector<string>q;for(int i=0;i<a;i++){string t,r,f;cout<<(s[i][1]!=""?s[i][1]:"> ");if(s[i][0]=="b"){bool b=1;for(int j=0;j<s[i][2].size();j++){if(b&s[i][2][j]==47){b=0;continue;}b?r+=s[i][2][j]:f+=s[i][2][j];if(b&j==s[i][2].size()-1|!b&s[i][2][j]==47){b=1;q.push_back("0");}}if(s[i][2].size()==0||s[i][2][s[i][2].size()-1]==47||s[i][2][0]==47){b=1;q.push_back("0");}if(b)cin.putback('\n');while(!b){cout<<"("<<s[i][2]<<") ";cin>>t;if(t==r|t==f){q.push_back(t==r?"1":"0");break;}cout<<"Please enter "<<r<<" or "<<f<<".\n"<<(s[i][1]==""?"> ":s[i][1]);}}if(s[i][0]=="c"){while(t.size()!=1){cin>>t;if(t.size()>1)cout<<"Please enter a character.\n"<<(s[i][1]==""?"> ":s[i][1]);}q.push_back(t);}if(s[i][0]=="i"){double d;int j,l=0,b=0;bool x=1;if(s[i][2].size()>2){for(int j=0;j<s[i][2].size();j++){int k=s[i][2][j];if((k<47|k>57)&k!=45){b=0;break;}if(k==45){if(j==0||s[i][2][j-1]==47)l++;else{b=0;break;}}if(k==47){if(j==0||s[i][2][j-1]==45||j==s[i][2].size()-1){b=0;break;}else{b++;x=0;continue;}}x?r+=s[i][2][j]:f+=s[i][2][j];}}if(b==1){x=1;l=stoi(r);b=stoi(f);}else x=0;l>b?x=0:"";while(1){cin>>r;for(int k=0;k<r.size();k++){if(!isdigit(r[k])&r[k]!=45){d=.5;break;}else d=stod(r);}j=d;if(!cin|j!=d|(x&&(j<l|j>b))){cin.clear();getline(cin,t);cout<<"Please enter an integer";if(!x)cout<<".\n";else cout<<" in the range of "<<l<<" and "<<b<<endl<<(s[i][1]==""?"> ":s[i][1]);}else break;}q.push_back(to_string(j));}if(s[i][0]=="f"){double d,l=0,b=0;bool x=1;if(s[i][2].size()>2){for(int j=0;j<s[i][2].size();j++){int k=s[i][2][j];if(k<45|k>57){b=0;break;}if(k==45){if(j==0||s[i][2][j-1]==47)l++;else{b=0;break;}}if(k==47){if(j==0|s[i][2][j-1]==45|j==s[i][2].size()-1){b=0;break;}else{b++;x=0;continue;}}if(x)r+=s[i][2][j];else f+=s[i][2][j];}}if(b==1){x=1;l=stod(r);b=stod(f);}else x=0;l>b?x=0:"";while(1){cin>>r;for(int k=0;k<r.size();k++){if(r[k]<45|r[k]>57|r[k]==47){cin.putback('k');cin>>d;break;}else d=stod(r);}if(!cin||(x&&(d<l|d>b))){cin.clear();getline(cin,t);cout<<"Please enter a floating point number";if(!x)cout<<".\n";else cout<<" in the range of "<<l<<" and "<<b<<endl<<(s[i][1]==""?"> ":s[i][1]);}else break;}q.push_back(to_string(d));}if(s[i][0]=="n"){bool b=1;while(b){cin>>t;for(int j=0;j<t.size();j++){if(!isalpha(t[j])){cout<<"Please enter a string with only letters.\n"<<(s[i][1]==""?"> ":s[i][1]);break;}if(j==t.size()-1)b=0;}}q.push_back(t);}if(s[i][0]=="s"){for(int j=0;j<s[i][2].size();j++){if(s[i][2][j]==37){if(s[i][2][j+1]>47&s[i][2][j+1]<58){int n=s[i][2][j+1]-48;if(s[i][2][j+2]!=99&s[i][2][j+2]!=105){r="";break;}for(int k=0;k<n;k++){r+='%';r+=s[i][2][j+2];}j+=2;}else if(s[i][2][j+1]==37){r+="%%";j+=1;}else{r="";break;}}else r+=s[i][2][j];}while(1){getline(cin,t);if(r.size()!=0){int j=0,k=0;for(;j<r.size();j++){if(r[j]==37){j++;if(r[j]==105){if(t[k]<48|t[k]>57){j=-1;break;}else{k++;continue;}}if(r[j]==99){if(!(t[k]>64&t[k]<91|t[k]>96&t[k]<123)){j=-1;break;}else{k++;continue;}}}if(r[j]==t[k])k++;else{j=-1;break;}if(j==r.size()-1^k==t.size()){j=-1;break;}}if(j!=-1)break;cout<<"Please enter a string in the format "<<r<<"\nThe % signs indicating special characters.\nIf the symbol after the % sign is %, enter %;\nif it is i, enter any digit between 0 and 9 (inclusive);\notherwise, enter any alphabetical charater a-z or A-Z.\n"<<(s[i][1]==""?"> ":s[i][1]);}else break;}q.push_back(t);}if(s[i][0]=="d"){bool x=1;while(1){string d,m,y;int a,b,c;cin>>t;if(t.size()==10&&t[2]==47&t[5]==47){for(int j=0;j<10;j++)if(t[j]<47|t[j]>57){x=0;break;}if(x){d+=t[0];d+=t[1];a=stoi(d);m+=t[3];m+=t[4];b=stoi(m);y+=t[6];y+=t[7];y+=t[8];y+=t[9];c=stoi(y);if(c>1900&a>0){if((b==1|b==3|b==5|b==7|b==8|b==10|b==12)&a<32)break;if((b==4|b==6|b==9|b==11)&a<31)break;if(b==2&((c%4==0&c%100!=0&a<30)|(c%400==0&a<30)|a<29))break;}}}cout<<"Please enter a date after 01/01/1900 in the form dd/mm/yyyy.\n"<<(s[i][1]==""?"> ":s[i][1]);}q.push_back(t);}if(s[i][0]!="s")getline(cin,t);}return q;}
```
Run it with this as `main()`:
```
int main() try{
const int args = 10;
string s[args][3];
s[0][0]="b",s[0][1]="",s[0][2]="yes/no";
s[1][0]="c",s[1][1]="Enter a character: ";
s[2][0]="i";
s[3][0]="i",s[3][1]="",s[3][2]="4/6";
s[4][0]="f";
s[5][0]="f",s[5][1]="",s[5][2]="-2.4/6.3";
s[6][0]="n",s[6][1]="";
s[7][0]="s",s[7][1]="",s[7][2]="rt%%%1c%2id";
s[8][0]="s",s[8][1]="";
s[9][0]="d",s[9][1]="Enter a date: ";
vector<string>v=i(args,s);
for(int i=0;i<args;i++)cout<<v[i]<<endl;
}
catch(exception&e){cerr<<"Error: "<<e.what()<<endl;}
catch(...){cerr<<"Unknown error.\n";}
```

] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/15508/edit)
Given an arbitrary contiguous range of positive integers, find the decomposition in the minimum number of sub-ranges of size *L = 2^n*, with the constraint that each range must be aligned, that is the first integer *i* in the sub-range must satisfy *i = 0 (mod L)*.
Background: some (especially old) netblocks aren't a simple single CIDR, that is a range in the form 192.0.2.0/24, but are a composition of several contiguous blocks, and the whois query returns explicitly the first and last ip in the block. Try yourself with `whois 220.72.0.0`:
```
[...]
IPv4 Address : 220.72.0.0 - 220.91.255.255 (/12+/14)
[...]
```
Solving this problem means finding the list of valid CIDR blocks that summed up constitute this range.
[Answer]
The following greedy algorithm works optimally:
>
> Choose the larges block allowed which is aligned with the lower bound
> and does not exceed the total range. Add this range to your result set
> and remove it from the search space. Loop until the entire range is
> covered.
>
>
>
In the following lines I took your example and simplified it to the interesting part, i.e. take the range 72-91:
```
0) Range: 72 - 91 (Size 20)
1a) Largest block size allowed @72: 8
1b) Subrange #1: 72 - 79
1c) Remaining: 80 - 91 (Size 12)
2a) Largest block size allowed @80: 16 (exceeds size) -> 8
2b) Subrange #2: 80 - 87
2c) Remaining: 88 - 91 (Size 4)
3a) Largest block size allowed @88: 8 (exceeds size) -> 4
3b) Subrange #3: 88 - 91
3c) Remaining: empty
Result: (72-79) (80-87) (88-91)
```
The structure can be seen even better, if we express the numbers in binary format.
```
0) Range: 01001000, Size 10100
1a) Largest block size allowed @01001000: 1000
1b) Subrange #1: 01001000, Size 1000
1c) Remaining: 01010000, Size 1100
2a) Largest block size allowed @01010000: 10000 (exceeds size) -> 1000
2b) Subrange #2: 01010000, Size 1000
2c) Remaining: 01011000, Size 100
3a) Largest block size allowed @01011000: 1000 (exceeds size) -> 100
3b) Subrange #3: 01011000, Size 100
3c) Remaining: empty
```
A note for implementation: the block size for the subrange to be chosen corresponds either to the rightmost 1 bit of the lower bound or the leftmost 1 bit of the size of the range (whichever is smaller).
] |
[Question]
[
**Scenario**
Little Johnny wants to play with his friends today. But his babysitter won't let him go! After a lot of begging, the heartless nanny gives him her brand new electronic puzzle and says: "If you solve the puzzle then you are free to go". Not being aware of Little Johnny's IT skills, the nanny leaves the kid alone.
Rapidly, Little Johnny sends you an e-mail asking for your help.
The puzzle consists of three hexagons as shown in the figure. Each vertex is painted black or white. Some of them belong to just one hexagon and some of them belong to more than one. Exactly four of them are painted black, and the other nine are white. The goal is to make the shared vertexes black by means of allowed moves: rotating a hexagon 60 degrees clockwise or counter-clockwise.
Can you help Little Johnny?
**Input**
>
> Input starts with an integer T, the number of puzzles to solve
> (1<=T<=100). T lines follow, each one having 13 binary digits,
> corresponding to the top-down, left to right labeling of the vertexes
> in the puzzle. A '0' means the i-th vertex is painted white, while a
> '1' means it is painted black.
>
>
>
**output**
>
> For each test case output M on a single line, the minimum number of
> moves required to solve the puzzle. Then print M lines, each one
> describing a move in the following manner: two space separated
> integers H and C, the rotated hexagon (upper left is 0, upper right
> is 1, lower one is 2) and the direction (0 for counter-clockwise, 1
> for clockwise). If there is more than one solution, any will suffice.
>
>
>
Example 
**Input sample:**
1
0000000101011
**output sample:**
3
2 0
2 0
1 1
**source Limit**
```
50000 Bytes
```
**time limit**
```
1 sec
```
**Winning constrain**
shortest code with specified time limit wins!
I leave the question for five days to decide winner future answers after five days too welcome
[Answer]
## Python, 307 chars
```
S={'0001001011000':[]}
for i in[0]*7:
for s in dict(S):
for m in range(6):S.setdefault(''.join(s[int(x,16)]for x in['2150483769abc','3106428759abc','0326159487abc','0421753986abc','01234587a6c9b','012345976b8ca'][m]),[m]+S[s])
for j in[0]*input():
L=S[raw_input()];print len(L)
for m in L:print m/2,m%2
```
Computes `S` which is a mapping from a state (a string just like the input) to a list of move numbers which solve the state. Generates a complete `S` on startup (only 715 states), then looks up each input and prints the answer.
Moves are implemented using a string of hex digits indicating where each result vertex comes from.
Takes about 0.15 seconds regardless of how big the input is.
[Answer]
# Mathematica 831
This was a very demanding challenge that took me several days to work out and streamline, far more than a typical challenge.
This graphs all the nodes, where each node corresponds to one arrangement of 4 black hexagon vertices. Then we find the shortest distance from an input vertex to the solution vertex, `{4, 7, 9, 10}`.
```
c = Complement; h = {{7, 9, 6, 3, 1, 4}, {7, 4, 2, 5, 8, 10}, {7, 10, 12, 13, 11, 9}}; i = {4, 7, 9, 10};l = RotateLeft; n = Module; q = Sort; r = RotateRight; s = Flatten;
p[v_, x_, r_] := Block[{d}, n[{d = v \[Intersection] x},If[d != {}, {v, (r[x][[Position[x, #][[1, 1]]]] & /@ d) \[Union] c[v, d], {x /. {h[[1]] -> 0, h[[2]] -> 1, h[[3]] -> 2}, r /. {r -> 0, l -> 1}}}, {}]] /. {{a_, b_, c_} :> {q@a \[DirectedEdge] q@b, q@a \[DirectedEdge] q@b -> c}}]
o[e_, t_] := Cases[s[Outer[p, {#}, h, {l, r}, 1]~s~2 & /@ e, 1], {a_ \[DirectedEdge] w_, b_} /; \[Not] MemberQ[t, w] :> {a \[DirectedEdge] w, b} ]
m[{g_, j_, _, b_}] :=n[{e, k, u, z},{e, k} = Transpose[o[c @@ g, g[[2]]]];z = Graph[u = Union@Join[e, j], EdgeLabels -> k];{Prepend[g, c[VertexList[z], s[g, 1]]], u, z, Union@Join[k, b]}]
t[j_] :=n[{r, v, y, i = {4, 7, 9, 10}},z = Nest[m, {{{i}, {}}, {}, 1, {}}, 7];v = FindShortestPath[z[[3]], i, Flatten@Position[Characters@j, "1"]];y = Cases[z[[4]], Rule[DirectedEdge[a_, b_], k_] /; MemberQ[v, a] && MemberQ[v, b]];r = Reverse[y[[Cases[Flatten[Position[y, #] & /@ v, 1], {a_, _, 1} :> a]]]] /. (_ \[DirectedEdge] _ -> k_) :> k ;Grid@Join[{{Length[r]}}, r]]
```
**Usage**
```
t["0100000100011"]
```
>
> 
>
>
>

---
**Timing**
The search space loads at the when the code is read for the first time.
A solution takes approximately .32 seconds, regardless of the distance from the solution node.
Note: [Intersection], [Union], and [DirectedEdge] are single, dedicated characters in Mathematica.
] |
Subsets and Splits